path
stringlengths
5
304
repo_name
stringlengths
6
79
content
stringlengths
27
1.05M
app/javascript/flavours/glitch/features/ui/components/doodle_modal.js
vahnj/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Button from 'flavours/glitch/components/button'; import ImmutablePureComponent from 'react-immutable-pure-component'; import Atrament from 'atrament'; // the doodling library import { connect } from 'react-redux'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { doodleSet, uploadCompose } from 'flavours/glitch/actions/compose'; import IconButton from 'flavours/glitch/components/icon_button'; import { debounce, mapValues } from 'lodash'; import classNames from 'classnames'; // palette nicked from MyPaint, CC0 const palette = [ ['rgb( 0, 0, 0)', 'Black'], ['rgb( 38, 38, 38)', 'Gray 15'], ['rgb( 77, 77, 77)', 'Grey 30'], ['rgb(128, 128, 128)', 'Grey 50'], ['rgb(171, 171, 171)', 'Grey 67'], ['rgb(217, 217, 217)', 'Grey 85'], ['rgb(255, 255, 255)', 'White'], ['rgb(128, 0, 0)', 'Maroon'], ['rgb(209, 0, 0)', 'English-red'], ['rgb(255, 54, 34)', 'Tomato'], ['rgb(252, 60, 3)', 'Orange-red'], ['rgb(255, 140, 105)', 'Salmon'], ['rgb(252, 232, 32)', 'Cadium-yellow'], ['rgb(243, 253, 37)', 'Lemon yellow'], ['rgb(121, 5, 35)', 'Dark crimson'], ['rgb(169, 32, 62)', 'Deep carmine'], ['rgb(255, 140, 0)', 'Orange'], ['rgb(255, 168, 18)', 'Dark tangerine'], ['rgb(217, 144, 88)', 'Persian orange'], ['rgb(194, 178, 128)', 'Sand'], ['rgb(255, 229, 180)', 'Peach'], ['rgb(100, 54, 46)', 'Bole'], ['rgb(108, 41, 52)', 'Dark cordovan'], ['rgb(163, 65, 44)', 'Chestnut'], ['rgb(228, 136, 100)', 'Dark salmon'], ['rgb(255, 195, 143)', 'Apricot'], ['rgb(255, 219, 188)', 'Unbleached silk'], ['rgb(242, 227, 198)', 'Straw'], ['rgb( 53, 19, 13)', 'Bistre'], ['rgb( 84, 42, 14)', 'Dark chocolate'], ['rgb(102, 51, 43)', 'Burnt sienna'], ['rgb(184, 66, 0)', 'Sienna'], ['rgb(216, 153, 12)', 'Yellow ochre'], ['rgb(210, 180, 140)', 'Tan'], ['rgb(232, 204, 144)', 'Dark wheat'], ['rgb( 0, 49, 83)', 'Prussian blue'], ['rgb( 48, 69, 119)', 'Dark grey blue'], ['rgb( 0, 71, 171)', 'Cobalt blue'], ['rgb( 31, 117, 254)', 'Blue'], ['rgb(120, 180, 255)', 'Bright french blue'], ['rgb(171, 200, 255)', 'Bright steel blue'], ['rgb(208, 231, 255)', 'Ice blue'], ['rgb( 30, 51, 58)', 'Medium jungle green'], ['rgb( 47, 79, 79)', 'Dark slate grey'], ['rgb( 74, 104, 93)', 'Dark grullo green'], ['rgb( 0, 128, 128)', 'Teal'], ['rgb( 67, 170, 176)', 'Turquoise'], ['rgb(109, 174, 199)', 'Cerulean frost'], ['rgb(173, 217, 186)', 'Tiffany green'], ['rgb( 22, 34, 29)', 'Gray-asparagus'], ['rgb( 36, 48, 45)', 'Medium dark teal'], ['rgb( 74, 104, 93)', 'Xanadu'], ['rgb(119, 198, 121)', 'Mint'], ['rgb(175, 205, 182)', 'Timberwolf'], ['rgb(185, 245, 246)', 'Celeste'], ['rgb(193, 255, 234)', 'Aquamarine'], ['rgb( 29, 52, 35)', 'Cal Poly Pomona'], ['rgb( 1, 68, 33)', 'Forest green'], ['rgb( 42, 128, 0)', 'Napier green'], ['rgb(128, 128, 0)', 'Olive'], ['rgb( 65, 156, 105)', 'Sea green'], ['rgb(189, 246, 29)', 'Green-yellow'], ['rgb(231, 244, 134)', 'Bright chartreuse'], ['rgb(138, 23, 137)', 'Purple'], ['rgb( 78, 39, 138)', 'Violet'], ['rgb(193, 75, 110)', 'Dark thulian pink'], ['rgb(222, 49, 99)', 'Cerise'], ['rgb(255, 20, 147)', 'Deep pink'], ['rgb(255, 102, 204)', 'Rose pink'], ['rgb(255, 203, 219)', 'Pink'], ['rgb(255, 255, 255)', 'White'], ['rgb(229, 17, 1)', 'RGB Red'], ['rgb( 0, 255, 0)', 'RGB Green'], ['rgb( 0, 0, 255)', 'RGB Blue'], ['rgb( 0, 255, 255)', 'CMYK Cyan'], ['rgb(255, 0, 255)', 'CMYK Magenta'], ['rgb(255, 255, 0)', 'CMYK Yellow'], ]; // re-arrange to the right order for display let palReordered = []; for (let row = 0; row < 7; row++) { for (let col = 0; col < 11; col++) { palReordered.push(palette[col * 7 + row]); } palReordered.push(null); // null indicates a <br /> } // Utility for converting base64 image to binary for upload // https://stackoverflow.com/questions/35940290/how-to-convert-base64-string-to-javascript-file-object-like-as-from-file-input-f function dataURLtoFile(dataurl, filename) { let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while(n--){ u8arr[n] = bstr.charCodeAt(n); } return new File([u8arr], filename, { type: mime }); } const DOODLE_SIZES = { normal: [500, 500, 'Square 500'], tootbanner: [702, 330, 'Tootbanner'], s640x480: [640, 480, '640×480 - 480p'], s800x600: [800, 600, '800×600 - SVGA'], s720x480: [720, 405, '720x405 - 16:9'], }; const mapStateToProps = state => ({ options: state.getIn(['compose', 'doodle']), }); const mapDispatchToProps = dispatch => ({ /** Set options in the redux store */ setOpt: (opts) => dispatch(doodleSet(opts)), /** Submit doodle for upload */ submit: (file) => dispatch(uploadCompose([file])), }); /** * Doodling dialog with drawing canvas * * Keyboard shortcuts: * - Delete: Clear screen, fill with background color * - Backspace, Ctrl+Z: Undo one step * - Ctrl held while drawing: Use background color * - Shift held while clicking screen: Use fill tool * * Palette: * - Left mouse button: pick foreground * - Ctrl + left mouse button: pick background * - Right mouse button: pick background */ @connect(mapStateToProps, mapDispatchToProps) export default class DoodleModal extends ImmutablePureComponent { static propTypes = { options: ImmutablePropTypes.map, onClose: PropTypes.func.isRequired, setOpt: PropTypes.func.isRequired, submit: PropTypes.func.isRequired, }; //region Option getters/setters /** Foreground color */ get fg () { return this.props.options.get('fg'); } set fg (value) { this.props.setOpt({ fg: value }); } /** Background color */ get bg () { return this.props.options.get('bg'); } set bg (value) { this.props.setOpt({ bg: value }); } /** Swap Fg and Bg for drawing */ get swapped () { return this.props.options.get('swapped'); } set swapped (value) { this.props.setOpt({ swapped: value }); } /** Mode - 'draw' or 'fill' */ get mode () { return this.props.options.get('mode'); } set mode (value) { this.props.setOpt({ mode: value }); } /** Base line weight */ get weight () { return this.props.options.get('weight'); } set weight (value) { this.props.setOpt({ weight: value }); } /** Drawing opacity */ get opacity () { return this.props.options.get('opacity'); } set opacity (value) { this.props.setOpt({ opacity: value }); } /** Adaptive stroke - change width with speed */ get adaptiveStroke () { return this.props.options.get('adaptiveStroke'); } set adaptiveStroke (value) { this.props.setOpt({ adaptiveStroke: value }); } /** Smoothing (for mouse drawing) */ get smoothing () { return this.props.options.get('smoothing'); } set smoothing (value) { this.props.setOpt({ smoothing: value }); } /** Size preset */ get size () { return this.props.options.get('size'); } set size (value) { this.props.setOpt({ size: value }); } //endregion /** Key up handler */ handleKeyUp = (e) => { if (e.target.nodeName === 'INPUT') return; if (e.key === 'Delete') { e.preventDefault(); this.handleClearBtn(); return; } if (e.key === 'Backspace' || (e.key === 'z' && (e.ctrlKey || e.metaKey))) { e.preventDefault(); this.undo(); } if (e.key === 'Control' || e.key === 'Meta') { this.controlHeld = false; this.swapped = false; } if (e.key === 'Shift') { this.shiftHeld = false; this.mode = 'draw'; } }; /** Key down handler */ handleKeyDown = (e) => { if (e.key === 'Control' || e.key === 'Meta') { this.controlHeld = true; this.swapped = true; } if (e.key === 'Shift') { this.shiftHeld = true; this.mode = 'fill'; } }; /** * Component installed in the DOM, do some initial set-up */ componentDidMount () { this.controlHeld = false; this.shiftHeld = false; this.swapped = false; window.addEventListener('keyup', this.handleKeyUp, false); window.addEventListener('keydown', this.handleKeyDown, false); }; /** * Tear component down */ componentWillUnmount () { window.removeEventListener('keyup', this.handleKeyUp, false); window.removeEventListener('keydown', this.handleKeyDown, false); if (this.sketcher) this.sketcher.destroy(); } /** * Set reference to the canvas element. * This is called during component init * * @param elem - canvas element */ setCanvasRef = (elem) => { this.canvas = elem; if (elem) { elem.addEventListener('dirty', () => { this.saveUndo(); this.sketcher._dirty = false; }); elem.addEventListener('click', () => { // sketcher bug - does not fire dirty on fill if (this.mode === 'fill') { this.saveUndo(); } }); // prevent context menu elem.addEventListener('contextmenu', (e) => { e.preventDefault(); }); elem.addEventListener('mousedown', (e) => { if (e.button === 2) { this.swapped = true; } }); elem.addEventListener('mouseup', (e) => { if (e.button === 2) { this.swapped = this.controlHeld; } }); this.initSketcher(elem); this.mode = 'draw'; // Reset mode - it's confusing if left at 'fill' } }; /** * Set up the sketcher instance * * @param canvas - canvas element. Null if we're just resizing */ initSketcher (canvas = null) { const sizepreset = DOODLE_SIZES[this.size]; if (this.sketcher) this.sketcher.destroy(); this.sketcher = new Atrament(canvas || this.canvas, sizepreset[0], sizepreset[1]); if (canvas) { this.ctx = this.sketcher.context; this.updateSketcherSettings(); } this.clearScreen(); } /** * Done button handler */ onDoneButton = () => { const dataUrl = this.sketcher.toImage(); const file = dataURLtoFile(dataUrl, 'doodle.png'); this.props.submit(file); this.props.onClose(); // close dialog }; /** * Cancel button handler */ onCancelButton = () => { if (this.undos.length > 1 && !confirm('Discard doodle? All changes will be lost!')) { return; } this.props.onClose(); // close dialog }; /** * Update sketcher options based on state */ updateSketcherSettings () { if (!this.sketcher) return; if (this.oldSize !== this.size) this.initSketcher(); this.sketcher.color = (this.swapped ? this.bg : this.fg); this.sketcher.opacity = this.opacity; this.sketcher.weight = this.weight; this.sketcher.mode = this.mode; this.sketcher.smoothing = this.smoothing; this.sketcher.adaptiveStroke = this.adaptiveStroke; this.oldSize = this.size; } /** * Fill screen with background color */ clearScreen = () => { this.ctx.fillStyle = this.bg; this.ctx.fillRect(-1, -1, this.canvas.width+2, this.canvas.height+2); this.undos = []; this.doSaveUndo(); }; /** * Undo one step */ undo = () => { if (this.undos.length > 1) { this.undos.pop(); const buf = this.undos.pop(); this.sketcher.clear(); this.ctx.putImageData(buf, 0, 0); this.doSaveUndo(); } }; /** * Save canvas content into the undo buffer immediately */ doSaveUndo = () => { this.undos.push(this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height)); }; /** * Called on each canvas change. * Saves canvas content to the undo buffer after some period of inactivity. */ saveUndo = debounce(() => { this.doSaveUndo(); }, 100); /** * Palette left click. * Selects Fg color (or Bg, if Control/Meta is held) * * @param e - event */ onPaletteClick = (e) => { const c = e.target.dataset.color; if (this.controlHeld) { this.bg = c; } else { this.fg = c; } e.target.blur(); e.preventDefault(); }; /** * Palette right click. * Selects Bg color * * @param e - event */ onPaletteRClick = (e) => { this.bg = e.target.dataset.color; e.target.blur(); e.preventDefault(); }; /** * Handle click on the Draw mode button * * @param e - event */ setModeDraw = (e) => { this.mode = 'draw'; e.target.blur(); }; /** * Handle click on the Fill mode button * * @param e - event */ setModeFill = (e) => { this.mode = 'fill'; e.target.blur(); }; /** * Handle click on Smooth checkbox * * @param e - event */ tglSmooth = (e) => { this.smoothing = !this.smoothing; e.target.blur(); }; /** * Handle click on Adaptive checkbox * * @param e - event */ tglAdaptive = (e) => { this.adaptiveStroke = !this.adaptiveStroke; e.target.blur(); }; /** * Handle change of the Weight input field * * @param e - event */ setWeight = (e) => { this.weight = +e.target.value || 1; }; /** * Set size - clalback from the select box * * @param e - event */ changeSize = (e) => { let newSize = e.target.value; if (newSize === this.oldSize) return; if (this.undos.length > 1 && !confirm('Change size? This will erase your drawing!')) { return; } this.size = newSize; }; handleClearBtn = () => { if (this.undos.length > 1 && !confirm('Clear screen? This will erase your drawing!')) { return; } this.clearScreen(); }; /** * Render the component */ render () { this.updateSketcherSettings(); return ( <div className='modal-root__modal doodle-modal'> <div className='doodle-modal__container'> <canvas ref={this.setCanvasRef} /> </div> <div className='doodle-modal__action-bar'> <div className='doodle-toolbar'> <Button text='Done' onClick={this.onDoneButton} /> <Button text='Cancel' onClick={this.onCancelButton} /> </div> <div className='filler' /> <div className='doodle-toolbar with-inputs'> <div> <label htmlFor='dd_smoothing'>Smoothing</label> <span className='val'> <input type='checkbox' id='dd_smoothing' onChange={this.tglSmooth} checked={this.smoothing} /> </span> </div> <div> <label htmlFor='dd_adaptive'>Adaptive</label> <span className='val'> <input type='checkbox' id='dd_adaptive' onChange={this.tglAdaptive} checked={this.adaptiveStroke} /> </span> </div> <div> <label htmlFor='dd_weight'>Weight</label> <span className='val'> <input type='number' min={1} id='dd_weight' value={this.weight} onChange={this.setWeight} /> </span> </div> <div> <select aria-label='Canvas size' onInput={this.changeSize} defaultValue={this.size}> { Object.values(mapValues(DOODLE_SIZES, (val, k) => <option key={k} value={k}>{val[2]}</option> )) } </select> </div> </div> <div className='doodle-toolbar'> <IconButton icon='pencil' title='Draw' label='Draw' onClick={this.setModeDraw} size={18} active={this.mode === 'draw'} inverted /> <IconButton icon='bath' title='Fill' label='Fill' onClick={this.setModeFill} size={18} active={this.mode === 'fill'} inverted /> <IconButton icon='undo' title='Undo' label='Undo' onClick={this.undo} size={18} inverted /> <IconButton icon='trash' title='Clear' label='Clear' onClick={this.handleClearBtn} size={18} inverted /> </div> <div className='doodle-palette'> { palReordered.map((c, i) => c === null ? <br key={i} /> : <button key={i} style={{ backgroundColor: c[0] }} onClick={this.onPaletteClick} onContextMenu={this.onPaletteRClick} data-color={c[0]} title={c[1]} className={classNames({ 'foreground': this.fg === c[0], 'background': this.bg === c[0], })} /> ) } </div> </div> </div> ); } }
lib/index.js
sgleung/autumn
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import store from './store' import AppContainer from './containers/AppContainer' import './styles/main.css' ReactDOM.render( <Provider store={store}> <AppContainer /> </Provider>, document.getElementById('root') )
admin/client/App/shared/CreateForm.js
xyzteam2016/keystone
/** * The form that's visible when "Create <ItemName>" is clicked on either the * List screen or the Item screen */ import React from 'react'; import { findDOMNode } from 'react-dom'; import assign from 'object-assign'; import AlertMessages from './AlertMessages'; import { Fields } from 'FieldTypes'; import InvalidFieldType from './InvalidFieldType'; import { Button, Form, Modal } from 'elemental'; const CreateForm = React.createClass({ displayName: 'CreateForm', propTypes: { err: React.PropTypes.object, isOpen: React.PropTypes.bool, list: React.PropTypes.object, onCancel: React.PropTypes.func, onCreate: React.PropTypes.func, }, getDefaultProps () { return { err: null, isOpen: false, }; }, getInitialState () { // Set the field values to their default values when first rendering the // form. (If they have a default value, that is) var values = {}; Object.keys(this.props.list.fields).forEach(key => { var field = this.props.list.fields[key]; if (field.defaultValue) { values[field.path] = field.defaultValue; } }); return { values: values, alerts: {}, }; }, componentDidMount () { this.focusTarget(); }, componentDidUpdate (prevProps) { // If we just opened the modal an animation is playing if (this.props.isOpen !== prevProps.isOpen) { // focus the focusTarget after the animation has started setTimeout(() => { this.focusTarget(); }, 0); } }, // Focus the first input field focusTarget () { if (this.refs.focusTarget) { findDOMNode(this.refs.focusTarget).focus(); } }, // Handle input change events handleChange (event) { var values = assign({}, this.state.values); values[event.path] = event.value; this.setState({ values: values, }); }, // Set the props of a field getFieldProps (field) { var props = assign({}, field); props.value = this.state.values[field.path]; props.values = this.state.values; props.onChange = this.handleChange; props.mode = 'create'; props.key = field.path; return props; }, // Create a new item when the form is submitted submitForm (event) { event.preventDefault(); const createForm = event.target; const formData = new FormData(createForm); this.props.list.createItem(formData, (err, data) => { if (data) { if (this.props.onCreate) { this.props.onCreate(data); } else { // Clear form this.setState({ values: {}, alerts: { success: { success: 'Item created', }, }, }); } } else { if (!err) { err = { error: 'connection error', }; } // If we get a database error, show the database error message // instead of only saying "Database error" if (err.error === 'database error') { err.error = err.detail.errmsg; } this.setState({ alerts: { error: err, }, }); } }); }, // Render the form itself renderForm () { if (!this.props.isOpen) return; var form = []; var list = this.props.list; var nameField = this.props.list.nameField; var focusRef; // If the name field is an initial one, we need to render a proper // input for it if (list.nameIsInitial) { var nameFieldProps = this.getFieldProps(nameField); nameFieldProps.ref = focusRef = 'focusTarget'; if (nameField.type === 'text') { nameFieldProps.className = 'item-name-field'; nameFieldProps.placeholder = nameField.label; nameFieldProps.label = false; } form.push(React.createElement(Fields[nameField.type], nameFieldProps)); } // Render inputs for all initial fields Object.keys(list.initialFields).forEach(key => { var field = list.fields[list.initialFields[key]]; // If there's something weird passed in as field type, render the // invalid field type component if (typeof Fields[field.type] !== 'function') { form.push(React.createElement(InvalidFieldType, { type: field.type, path: field.path, key: field.path })); return; } // Get the props for the input field var fieldProps = this.getFieldProps(field); // If there was no focusRef set previously, set the current field to // be the one to be focussed. Generally the first input field, if // there's an initial name field that takes precedence. if (!focusRef) { fieldProps.ref = focusRef = 'focusTarget'; } form.push(React.createElement(Fields[field.type], fieldProps)); }); return ( <Form type="horizontal" onSubmit={this.submitForm} className="create-form" > <Modal.Header text={'Create a new ' + list.singular} onClose={this.props.onCancel} showCloseButton /> <Modal.Body> <AlertMessages alerts={this.state.alerts} /> {form} </Modal.Body> <Modal.Footer> <Button type="success" submit>Create</Button> <Button type="link-cancel" onClick={this.props.onCancel} > Cancel </Button> </Modal.Footer> </Form> ); }, render () { return ( <Modal isOpen={this.props.isOpen} onCancel={this.props.onCancel} backdropClosesModal > {this.renderForm()} </Modal> ); }, }); module.exports = CreateForm;
node_modules/react-bootstrap/es/Tooltip.js
lucketta/got-quote-generator
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import isRequiredForA11y from 'prop-types-extra/lib/isRequiredForA11y'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * An html id attribute, necessary for accessibility * @type {string|number} * @required */ id: isRequiredForA11y(PropTypes.oneOfType([PropTypes.string, PropTypes.number])), /** * Sets the direction the Tooltip is positioned towards. */ placement: PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Tooltip. */ positionTop: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * The "left" position value for the Tooltip. */ positionLeft: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * The "top" position value for the Tooltip arrow. */ arrowOffsetTop: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * The "left" position value for the Tooltip arrow. */ arrowOffsetLeft: PropTypes.oneOfType([PropTypes.number, PropTypes.string]) }; var defaultProps = { placement: 'right' }; var Tooltip = function (_React$Component) { _inherits(Tooltip, _React$Component); function Tooltip() { _classCallCheck(this, Tooltip); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Tooltip.prototype.render = function render() { var _extends2; var _props = this.props, placement = _props.placement, positionTop = _props.positionTop, positionLeft = _props.positionLeft, arrowOffsetTop = _props.arrowOffsetTop, arrowOffsetLeft = _props.arrowOffsetLeft, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2)); var outerStyle = _extends({ top: positionTop, left: positionLeft }, style); var arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft }; return React.createElement( 'div', _extends({}, elementProps, { role: 'tooltip', className: classNames(className, classes), style: outerStyle }), React.createElement('div', { className: prefix(bsProps, 'arrow'), style: arrowStyle }), React.createElement( 'div', { className: prefix(bsProps, 'inner') }, children ) ); }; return Tooltip; }(React.Component); Tooltip.propTypes = propTypes; Tooltip.defaultProps = defaultProps; export default bsClass('tooltip', Tooltip);
admin/client/App/shared/Popout/index.js
everisARQ/keystone
/** * A Popout component. * One can also add a Header (Popout/Header), a Footer * (Popout/Footer), a Body (Popout/Body) and a Pan (Popout/Pane). */ import React from 'react'; import Portal from '../Portal'; import Transition from 'react-addons-css-transition-group'; const sizes = { arrowHeight: 12, }; var Popout = React.createClass({ displayName: 'Popout', propTypes: { isOpen: React.PropTypes.bool, onCancel: React.PropTypes.func, onSubmit: React.PropTypes.func, relativeToID: React.PropTypes.string.isRequired, width: React.PropTypes.number, }, getDefaultProps () { return { width: 320, }; }, getInitialState () { return {}; }, // If we mounted open, calculate the position componentDidMount () { if (this.props.isOpen) this.calculatePosition(); }, // If we change to being open from not being open, calculate the position componentWillReceiveProps (nextProps) { if (!this.props.isOpen && nextProps.isOpen) this.calculatePosition(); }, getPortalDOMNode () { return this.refs.portal.getPortalDOMNode(); }, // Calculate the position of the popout calculatePosition () { let posNode = document.getElementById(this.props.relativeToID); const pos = { top: 0, left: 0, width: posNode.offsetWidth, height: posNode.offsetHeight, }; while (posNode.offsetParent) { pos.top += posNode.offsetTop; pos.left += posNode.offsetLeft; posNode = posNode.offsetParent; } const leftOffset = pos.left + (pos.width / 2) - (this.props.width / 2); const topOffset = pos.top + pos.height + sizes.arrowHeight; this.setState({ leftOffset: leftOffset, topOffset: topOffset, }); }, // Render the popout renderPopout () { if (!this.props.isOpen) return; return ( <div className="Popout" style={{ left: this.state.leftOffset, top: this.state.topOffset, width: this.props.width, }} > <span className="Popout__arrow" /> <div className="Popout__inner"> {this.props.children} </div> </div> ); }, // Render a blockout renderBlockout () { if (!this.props.isOpen) return; return <div className="blockout" onClick={this.props.onCancel} />; }, render () { return ( <Portal className="Popout-wrapper" ref="portal"> <Transition className="Popout-animation" transitionEnterTimeout={200} transitionLeaveTimeout={200} transitionName="Popout" component="div" > {this.renderPopout()} </Transition> {this.renderBlockout()} </Portal> ); }, }); module.exports = Popout; // expose the child to the top level export module.exports.Header = require('./PopoutHeader'); module.exports.Body = require('./PopoutBody'); module.exports.Footer = require('./PopoutFooter'); module.exports.Pane = require('./PopoutPane');
ajax/libs/clappr/0.0.13/clappr.js
r3x/cdnjs
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); } // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],2:[function(require,module,exports){ (function (process,global){ (function(global) { 'use strict'; if (global.$traceurRuntime) { return; } var $Object = Object; var $TypeError = TypeError; var $create = $Object.create; var $defineProperties = $Object.defineProperties; var $defineProperty = $Object.defineProperty; var $freeze = $Object.freeze; var $getOwnPropertyDescriptor = $Object.getOwnPropertyDescriptor; var $getOwnPropertyNames = $Object.getOwnPropertyNames; var $keys = $Object.keys; var $hasOwnProperty = $Object.prototype.hasOwnProperty; var $toString = $Object.prototype.toString; var $preventExtensions = Object.preventExtensions; var $seal = Object.seal; var $isExtensible = Object.isExtensible; function nonEnum(value) { return { configurable: true, enumerable: false, value: value, writable: true }; } var types = { void: function voidType() {}, any: function any() {}, string: function string() {}, number: function number() {}, boolean: function boolean() {} }; var method = nonEnum; var counter = 0; function newUniqueString() { return '__$' + Math.floor(Math.random() * 1e9) + '$' + ++counter + '$__'; } var symbolInternalProperty = newUniqueString(); var symbolDescriptionProperty = newUniqueString(); var symbolDataProperty = newUniqueString(); var symbolValues = $create(null); var privateNames = $create(null); function createPrivateName() { var s = newUniqueString(); privateNames[s] = true; return s; } function isSymbol(symbol) { return typeof symbol === 'object' && symbol instanceof SymbolValue; } function typeOf(v) { if (isSymbol(v)) return 'symbol'; return typeof v; } function Symbol(description) { var value = new SymbolValue(description); if (!(this instanceof Symbol)) return value; throw new TypeError('Symbol cannot be new\'ed'); } $defineProperty(Symbol.prototype, 'constructor', nonEnum(Symbol)); $defineProperty(Symbol.prototype, 'toString', method(function() { var symbolValue = this[symbolDataProperty]; if (!getOption('symbols')) return symbolValue[symbolInternalProperty]; if (!symbolValue) throw TypeError('Conversion from symbol to string'); var desc = symbolValue[symbolDescriptionProperty]; if (desc === undefined) desc = ''; return 'Symbol(' + desc + ')'; })); $defineProperty(Symbol.prototype, 'valueOf', method(function() { var symbolValue = this[symbolDataProperty]; if (!symbolValue) throw TypeError('Conversion from symbol to string'); if (!getOption('symbols')) return symbolValue[symbolInternalProperty]; return symbolValue; })); function SymbolValue(description) { var key = newUniqueString(); $defineProperty(this, symbolDataProperty, {value: this}); $defineProperty(this, symbolInternalProperty, {value: key}); $defineProperty(this, symbolDescriptionProperty, {value: description}); freeze(this); symbolValues[key] = this; } $defineProperty(SymbolValue.prototype, 'constructor', nonEnum(Symbol)); $defineProperty(SymbolValue.prototype, 'toString', { value: Symbol.prototype.toString, enumerable: false }); $defineProperty(SymbolValue.prototype, 'valueOf', { value: Symbol.prototype.valueOf, enumerable: false }); var hashProperty = createPrivateName(); var hashPropertyDescriptor = {value: undefined}; var hashObjectProperties = { hash: {value: undefined}, self: {value: undefined} }; var hashCounter = 0; function getOwnHashObject(object) { var hashObject = object[hashProperty]; if (hashObject && hashObject.self === object) return hashObject; if ($isExtensible(object)) { hashObjectProperties.hash.value = hashCounter++; hashObjectProperties.self.value = object; hashPropertyDescriptor.value = $create(null, hashObjectProperties); $defineProperty(object, hashProperty, hashPropertyDescriptor); return hashPropertyDescriptor.value; } return undefined; } function freeze(object) { getOwnHashObject(object); return $freeze.apply(this, arguments); } function preventExtensions(object) { getOwnHashObject(object); return $preventExtensions.apply(this, arguments); } function seal(object) { getOwnHashObject(object); return $seal.apply(this, arguments); } Symbol.iterator = Symbol(); freeze(SymbolValue.prototype); function toProperty(name) { if (isSymbol(name)) return name[symbolInternalProperty]; return name; } function getOwnPropertyNames(object) { var rv = []; var names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var name = names[i]; if (!symbolValues[name] && !privateNames[name]) rv.push(name); } return rv; } function getOwnPropertyDescriptor(object, name) { return $getOwnPropertyDescriptor(object, toProperty(name)); } function getOwnPropertySymbols(object) { var rv = []; var names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var symbol = symbolValues[names[i]]; if (symbol) rv.push(symbol); } return rv; } function hasOwnProperty(name) { return $hasOwnProperty.call(this, toProperty(name)); } function getOption(name) { return global.traceur && global.traceur.options[name]; } function setProperty(object, name, value) { var sym, desc; if (isSymbol(name)) { sym = name; name = name[symbolInternalProperty]; } object[name] = value; if (sym && (desc = $getOwnPropertyDescriptor(object, name))) $defineProperty(object, name, {enumerable: false}); return value; } function defineProperty(object, name, descriptor) { if (isSymbol(name)) { if (descriptor.enumerable) { descriptor = $create(descriptor, {enumerable: {value: false}}); } name = name[symbolInternalProperty]; } $defineProperty(object, name, descriptor); return object; } function polyfillObject(Object) { $defineProperty(Object, 'defineProperty', {value: defineProperty}); $defineProperty(Object, 'getOwnPropertyNames', {value: getOwnPropertyNames}); $defineProperty(Object, 'getOwnPropertyDescriptor', {value: getOwnPropertyDescriptor}); $defineProperty(Object.prototype, 'hasOwnProperty', {value: hasOwnProperty}); $defineProperty(Object, 'freeze', {value: freeze}); $defineProperty(Object, 'preventExtensions', {value: preventExtensions}); $defineProperty(Object, 'seal', {value: seal}); Object.getOwnPropertySymbols = getOwnPropertySymbols; } function exportStar(object) { for (var i = 1; i < arguments.length; i++) { var names = $getOwnPropertyNames(arguments[i]); for (var j = 0; j < names.length; j++) { var name = names[j]; if (privateNames[name]) continue; (function(mod, name) { $defineProperty(object, name, { get: function() { return mod[name]; }, enumerable: true }); })(arguments[i], names[j]); } } return object; } function isObject(x) { return x != null && (typeof x === 'object' || typeof x === 'function'); } function toObject(x) { if (x == null) throw $TypeError(); return $Object(x); } function assertObject(x) { if (!isObject(x)) throw $TypeError(x + ' is not an Object'); return x; } function setupGlobals(global) { global.Symbol = Symbol; polyfillObject(global.Object); } setupGlobals(global); global.$traceurRuntime = { assertObject: assertObject, createPrivateName: createPrivateName, exportStar: exportStar, getOwnHashObject: getOwnHashObject, privateNames: privateNames, setProperty: setProperty, setupGlobals: setupGlobals, toObject: toObject, toProperty: toProperty, type: types, typeof: typeOf, defineProperties: $defineProperties, defineProperty: $defineProperty, getOwnPropertyDescriptor: $getOwnPropertyDescriptor, getOwnPropertyNames: $getOwnPropertyNames, keys: $keys }; })(typeof global !== 'undefined' ? global : this); (function() { 'use strict'; var toObject = $traceurRuntime.toObject; function spread() { var rv = [], k = 0; for (var i = 0; i < arguments.length; i++) { var valueToSpread = toObject(arguments[i]); for (var j = 0; j < valueToSpread.length; j++) { rv[k++] = valueToSpread[j]; } } return rv; } $traceurRuntime.spread = spread; })(); (function() { 'use strict'; var $Object = Object; var $TypeError = TypeError; var $create = $Object.create; var $defineProperties = $traceurRuntime.defineProperties; var $defineProperty = $traceurRuntime.defineProperty; var $getOwnPropertyDescriptor = $traceurRuntime.getOwnPropertyDescriptor; var $getOwnPropertyNames = $traceurRuntime.getOwnPropertyNames; var $getPrototypeOf = Object.getPrototypeOf; function superDescriptor(homeObject, name) { var proto = $getPrototypeOf(homeObject); do { var result = $getOwnPropertyDescriptor(proto, name); if (result) return result; proto = $getPrototypeOf(proto); } while (proto); return undefined; } function superCall(self, homeObject, name, args) { return superGet(self, homeObject, name).apply(self, args); } function superGet(self, homeObject, name) { var descriptor = superDescriptor(homeObject, name); if (descriptor) { if (!descriptor.get) return descriptor.value; return descriptor.get.call(self); } return undefined; } function superSet(self, homeObject, name, value) { var descriptor = superDescriptor(homeObject, name); if (descriptor && descriptor.set) { descriptor.set.call(self, value); return value; } throw $TypeError("super has no setter '" + name + "'."); } function getDescriptors(object) { var descriptors = {}, name, names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var name = names[i]; descriptors[name] = $getOwnPropertyDescriptor(object, name); } return descriptors; } function createClass(ctor, object, staticObject, superClass) { $defineProperty(object, 'constructor', { value: ctor, configurable: true, enumerable: false, writable: true }); if (arguments.length > 3) { if (typeof superClass === 'function') ctor.__proto__ = superClass; ctor.prototype = $create(getProtoParent(superClass), getDescriptors(object)); } else { ctor.prototype = object; } $defineProperty(ctor, 'prototype', { configurable: false, writable: false }); return $defineProperties(ctor, getDescriptors(staticObject)); } function getProtoParent(superClass) { if (typeof superClass === 'function') { var prototype = superClass.prototype; if ($Object(prototype) === prototype || prototype === null) return superClass.prototype; } if (superClass === null) return null; throw new $TypeError(); } function defaultSuperCall(self, homeObject, args) { if ($getPrototypeOf(homeObject) !== null) superCall(self, homeObject, 'constructor', args); } $traceurRuntime.createClass = createClass; $traceurRuntime.defaultSuperCall = defaultSuperCall; $traceurRuntime.superCall = superCall; $traceurRuntime.superGet = superGet; $traceurRuntime.superSet = superSet; })(); (function() { 'use strict'; var createPrivateName = $traceurRuntime.createPrivateName; var $defineProperties = $traceurRuntime.defineProperties; var $defineProperty = $traceurRuntime.defineProperty; var $create = Object.create; var $TypeError = TypeError; function nonEnum(value) { return { configurable: true, enumerable: false, value: value, writable: true }; } var ST_NEWBORN = 0; var ST_EXECUTING = 1; var ST_SUSPENDED = 2; var ST_CLOSED = 3; var END_STATE = -2; var RETHROW_STATE = -3; function getInternalError(state) { return new Error('Traceur compiler bug: invalid state in state machine: ' + state); } function GeneratorContext() { this.state = 0; this.GState = ST_NEWBORN; this.storedException = undefined; this.finallyFallThrough = undefined; this.sent_ = undefined; this.returnValue = undefined; this.tryStack_ = []; } GeneratorContext.prototype = { pushTry: function(catchState, finallyState) { if (finallyState !== null) { var finallyFallThrough = null; for (var i = this.tryStack_.length - 1; i >= 0; i--) { if (this.tryStack_[i].catch !== undefined) { finallyFallThrough = this.tryStack_[i].catch; break; } } if (finallyFallThrough === null) finallyFallThrough = RETHROW_STATE; this.tryStack_.push({ finally: finallyState, finallyFallThrough: finallyFallThrough }); } if (catchState !== null) { this.tryStack_.push({catch: catchState}); } }, popTry: function() { this.tryStack_.pop(); }, get sent() { this.maybeThrow(); return this.sent_; }, set sent(v) { this.sent_ = v; }, get sentIgnoreThrow() { return this.sent_; }, maybeThrow: function() { if (this.action === 'throw') { this.action = 'next'; throw this.sent_; } }, end: function() { switch (this.state) { case END_STATE: return this; case RETHROW_STATE: throw this.storedException; default: throw getInternalError(this.state); } }, handleException: function(ex) { this.GState = ST_CLOSED; this.state = END_STATE; throw ex; } }; function nextOrThrow(ctx, moveNext, action, x) { switch (ctx.GState) { case ST_EXECUTING: throw new Error(("\"" + action + "\" on executing generator")); case ST_CLOSED: if (action == 'next') { return { value: undefined, done: true }; } throw new Error(("\"" + action + "\" on closed generator")); case ST_NEWBORN: if (action === 'throw') { ctx.GState = ST_CLOSED; throw x; } if (x !== undefined) throw $TypeError('Sent value to newborn generator'); case ST_SUSPENDED: ctx.GState = ST_EXECUTING; ctx.action = action; ctx.sent = x; var value = moveNext(ctx); var done = value === ctx; if (done) value = ctx.returnValue; ctx.GState = done ? ST_CLOSED : ST_SUSPENDED; return { value: value, done: done }; } } var ctxName = createPrivateName(); var moveNextName = createPrivateName(); function GeneratorFunction() {} function GeneratorFunctionPrototype() {} GeneratorFunction.prototype = GeneratorFunctionPrototype; $defineProperty(GeneratorFunctionPrototype, 'constructor', nonEnum(GeneratorFunction)); GeneratorFunctionPrototype.prototype = { constructor: GeneratorFunctionPrototype, next: function(v) { return nextOrThrow(this[ctxName], this[moveNextName], 'next', v); }, throw: function(v) { return nextOrThrow(this[ctxName], this[moveNextName], 'throw', v); } }; $defineProperties(GeneratorFunctionPrototype.prototype, { constructor: {enumerable: false}, next: {enumerable: false}, throw: {enumerable: false} }); Object.defineProperty(GeneratorFunctionPrototype.prototype, Symbol.iterator, nonEnum(function() { return this; })); function createGeneratorInstance(innerFunction, functionObject, self) { var moveNext = getMoveNext(innerFunction, self); var ctx = new GeneratorContext(); var object = $create(functionObject.prototype); object[ctxName] = ctx; object[moveNextName] = moveNext; return object; } function initGeneratorFunction(functionObject) { functionObject.prototype = $create(GeneratorFunctionPrototype.prototype); functionObject.__proto__ = GeneratorFunctionPrototype; return functionObject; } function AsyncFunctionContext() { GeneratorContext.call(this); this.err = undefined; var ctx = this; ctx.result = new Promise(function(resolve, reject) { ctx.resolve = resolve; ctx.reject = reject; }); } AsyncFunctionContext.prototype = $create(GeneratorContext.prototype); AsyncFunctionContext.prototype.end = function() { switch (this.state) { case END_STATE: this.resolve(this.returnValue); break; case RETHROW_STATE: this.reject(this.storedException); break; default: this.reject(getInternalError(this.state)); } }; AsyncFunctionContext.prototype.handleException = function() { this.state = RETHROW_STATE; }; function asyncWrap(innerFunction, self) { var moveNext = getMoveNext(innerFunction, self); var ctx = new AsyncFunctionContext(); ctx.createCallback = function(newState) { return function(value) { ctx.state = newState; ctx.value = value; moveNext(ctx); }; }; ctx.errback = function(err) { handleCatch(ctx, err); moveNext(ctx); }; moveNext(ctx); return ctx.result; } function getMoveNext(innerFunction, self) { return function(ctx) { while (true) { try { return innerFunction.call(self, ctx); } catch (ex) { handleCatch(ctx, ex); } } }; } function handleCatch(ctx, ex) { ctx.storedException = ex; var last = ctx.tryStack_[ctx.tryStack_.length - 1]; if (!last) { ctx.handleException(ex); return; } ctx.state = last.catch !== undefined ? last.catch : last.finally; if (last.finallyFallThrough !== undefined) ctx.finallyFallThrough = last.finallyFallThrough; } $traceurRuntime.asyncWrap = asyncWrap; $traceurRuntime.initGeneratorFunction = initGeneratorFunction; $traceurRuntime.createGeneratorInstance = createGeneratorInstance; })(); (function() { function buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) { var out = []; if (opt_scheme) { out.push(opt_scheme, ':'); } if (opt_domain) { out.push('//'); if (opt_userInfo) { out.push(opt_userInfo, '@'); } out.push(opt_domain); if (opt_port) { out.push(':', opt_port); } } if (opt_path) { out.push(opt_path); } if (opt_queryData) { out.push('?', opt_queryData); } if (opt_fragment) { out.push('#', opt_fragment); } return out.join(''); } ; var splitRe = new RegExp('^' + '(?:' + '([^:/?#.]+)' + ':)?' + '(?://' + '(?:([^/?#]*)@)?' + '([\\w\\d\\-\\u0100-\\uffff.%]*)' + '(?::([0-9]+))?' + ')?' + '([^?#]+)?' + '(?:\\?([^#]*))?' + '(?:#(.*))?' + '$'); var ComponentIndex = { SCHEME: 1, USER_INFO: 2, DOMAIN: 3, PORT: 4, PATH: 5, QUERY_DATA: 6, FRAGMENT: 7 }; function split(uri) { return (uri.match(splitRe)); } function removeDotSegments(path) { if (path === '/') return '/'; var leadingSlash = path[0] === '/' ? '/' : ''; var trailingSlash = path.slice(-1) === '/' ? '/' : ''; var segments = path.split('/'); var out = []; var up = 0; for (var pos = 0; pos < segments.length; pos++) { var segment = segments[pos]; switch (segment) { case '': case '.': break; case '..': if (out.length) out.pop(); else up++; break; default: out.push(segment); } } if (!leadingSlash) { while (up-- > 0) { out.unshift('..'); } if (out.length === 0) out.push('.'); } return leadingSlash + out.join('/') + trailingSlash; } function joinAndCanonicalizePath(parts) { var path = parts[ComponentIndex.PATH] || ''; path = removeDotSegments(path); parts[ComponentIndex.PATH] = path; return buildFromEncodedParts(parts[ComponentIndex.SCHEME], parts[ComponentIndex.USER_INFO], parts[ComponentIndex.DOMAIN], parts[ComponentIndex.PORT], parts[ComponentIndex.PATH], parts[ComponentIndex.QUERY_DATA], parts[ComponentIndex.FRAGMENT]); } function canonicalizeUrl(url) { var parts = split(url); return joinAndCanonicalizePath(parts); } function resolveUrl(base, url) { var parts = split(url); var baseParts = split(base); if (parts[ComponentIndex.SCHEME]) { return joinAndCanonicalizePath(parts); } else { parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME]; } for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) { if (!parts[i]) { parts[i] = baseParts[i]; } } if (parts[ComponentIndex.PATH][0] == '/') { return joinAndCanonicalizePath(parts); } var path = baseParts[ComponentIndex.PATH]; var index = path.lastIndexOf('/'); path = path.slice(0, index + 1) + parts[ComponentIndex.PATH]; parts[ComponentIndex.PATH] = path; return joinAndCanonicalizePath(parts); } function isAbsolute(name) { if (!name) return false; if (name[0] === '/') return true; var parts = split(name); if (parts[ComponentIndex.SCHEME]) return true; return false; } $traceurRuntime.canonicalizeUrl = canonicalizeUrl; $traceurRuntime.isAbsolute = isAbsolute; $traceurRuntime.removeDotSegments = removeDotSegments; $traceurRuntime.resolveUrl = resolveUrl; })(); (function(global) { 'use strict'; var $__2 = $traceurRuntime.assertObject($traceurRuntime), canonicalizeUrl = $__2.canonicalizeUrl, resolveUrl = $__2.resolveUrl, isAbsolute = $__2.isAbsolute; var moduleInstantiators = Object.create(null); var baseURL; if (global.location && global.location.href) baseURL = resolveUrl(global.location.href, './'); else baseURL = ''; var UncoatedModuleEntry = function UncoatedModuleEntry(url, uncoatedModule) { this.url = url; this.value_ = uncoatedModule; }; ($traceurRuntime.createClass)(UncoatedModuleEntry, {}, {}); var UncoatedModuleInstantiator = function UncoatedModuleInstantiator(url, func) { $traceurRuntime.superCall(this, $UncoatedModuleInstantiator.prototype, "constructor", [url, null]); this.func = func; }; var $UncoatedModuleInstantiator = UncoatedModuleInstantiator; ($traceurRuntime.createClass)(UncoatedModuleInstantiator, {getUncoatedModule: function() { if (this.value_) return this.value_; return this.value_ = this.func.call(global); }}, {}, UncoatedModuleEntry); function getUncoatedModuleInstantiator(name) { if (!name) return; var url = ModuleStore.normalize(name); return moduleInstantiators[url]; } ; var moduleInstances = Object.create(null); var liveModuleSentinel = {}; function Module(uncoatedModule) { var isLive = arguments[1]; var coatedModule = Object.create(null); Object.getOwnPropertyNames(uncoatedModule).forEach((function(name) { var getter, value; if (isLive === liveModuleSentinel) { var descr = Object.getOwnPropertyDescriptor(uncoatedModule, name); if (descr.get) getter = descr.get; } if (!getter) { value = uncoatedModule[name]; getter = function() { return value; }; } Object.defineProperty(coatedModule, name, { get: getter, enumerable: true }); })); Object.preventExtensions(coatedModule); return coatedModule; } var ModuleStore = { normalize: function(name, refererName, refererAddress) { if (typeof name !== "string") throw new TypeError("module name must be a string, not " + typeof name); if (isAbsolute(name)) return canonicalizeUrl(name); if (/[^\.]\/\.\.\//.test(name)) { throw new Error('module name embeds /../: ' + name); } if (name[0] === '.' && refererName) return resolveUrl(refererName, name); return canonicalizeUrl(name); }, get: function(normalizedName) { var m = getUncoatedModuleInstantiator(normalizedName); if (!m) return undefined; var moduleInstance = moduleInstances[m.url]; if (moduleInstance) return moduleInstance; moduleInstance = Module(m.getUncoatedModule(), liveModuleSentinel); return moduleInstances[m.url] = moduleInstance; }, set: function(normalizedName, module) { normalizedName = String(normalizedName); moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, (function() { return module; })); moduleInstances[normalizedName] = module; }, get baseURL() { return baseURL; }, set baseURL(v) { baseURL = String(v); }, registerModule: function(name, func) { var normalizedName = ModuleStore.normalize(name); if (moduleInstantiators[normalizedName]) throw new Error('duplicate module named ' + normalizedName); moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, func); }, bundleStore: Object.create(null), register: function(name, deps, func) { if (!deps || !deps.length && !func.length) { this.registerModule(name, func); } else { this.bundleStore[name] = { deps: deps, execute: function() { var $__0 = arguments; var depMap = {}; deps.forEach((function(dep, index) { return depMap[dep] = $__0[index]; })); var registryEntry = func.call(this, depMap); registryEntry.execute.call(this); return registryEntry.exports; } }; } }, getAnonymousModule: function(func) { return new Module(func.call(global), liveModuleSentinel); }, getForTesting: function(name) { var $__0 = this; if (!this.testingPrefix_) { Object.keys(moduleInstances).some((function(key) { var m = /(traceur@[^\/]*\/)/.exec(key); if (m) { $__0.testingPrefix_ = m[1]; return true; } })); } return this.get(this.testingPrefix_ + name); } }; ModuleStore.set('@traceur/src/runtime/ModuleStore', new Module({ModuleStore: ModuleStore})); var setupGlobals = $traceurRuntime.setupGlobals; $traceurRuntime.setupGlobals = function(global) { setupGlobals(global); }; $traceurRuntime.ModuleStore = ModuleStore; global.System = { register: ModuleStore.register.bind(ModuleStore), get: ModuleStore.get, set: ModuleStore.set, normalize: ModuleStore.normalize }; $traceurRuntime.getModuleImpl = function(name) { var instantiator = getUncoatedModuleInstantiator(name); return instantiator && instantiator.getUncoatedModule(); }; })(typeof global !== 'undefined' ? global : this); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/utils", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/utils"; var toObject = $traceurRuntime.toObject; function toUint32(x) { return x | 0; } function isObject(x) { return x && (typeof x === 'object' || typeof x === 'function'); } function isCallable(x) { return typeof x === 'function'; } function toInteger(x) { x = +x; if (isNaN(x)) return 0; if (!isFinite(x) || x === 0) return x; return x > 0 ? Math.floor(x) : Math.ceil(x); } var MAX_SAFE_LENGTH = Math.pow(2, 53) - 1; function toLength(x) { var len = toInteger(x); return len < 0 ? 0 : Math.min(len, MAX_SAFE_LENGTH); } return { get toObject() { return toObject; }, get toUint32() { return toUint32; }, get isObject() { return isObject; }, get isCallable() { return isCallable; }, get toInteger() { return toInteger; }, get toLength() { return toLength; } }; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Array", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Array"; var $__3 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")), toInteger = $__3.toInteger, toLength = $__3.toLength, toObject = $__3.toObject, isCallable = $__3.isCallable; function fill(value) { var start = arguments[1] !== (void 0) ? arguments[1] : 0; var end = arguments[2]; var object = toObject(this); var len = toLength(object.length); var fillStart = toInteger(start); var fillEnd = end !== undefined ? toInteger(end) : len; fillStart = fillStart < 0 ? Math.max(len + fillStart, 0) : Math.min(fillStart, len); fillEnd = fillEnd < 0 ? Math.max(len + fillEnd, 0) : Math.min(fillEnd, len); while (fillStart < fillEnd) { object[fillStart] = value; fillStart++; } return object; } function find(predicate) { var thisArg = arguments[1]; return findHelper(this, predicate, thisArg); } function findIndex(predicate) { var thisArg = arguments[1]; return findHelper(this, predicate, thisArg, true); } function findHelper(self, predicate) { var thisArg = arguments[2]; var returnIndex = arguments[3] !== (void 0) ? arguments[3] : false; var object = toObject(self); var len = toLength(object.length); if (!isCallable(predicate)) { throw TypeError(); } for (var i = 0; i < len; i++) { if (i in object) { var value = object[i]; if (predicate.call(thisArg, value, i, object)) { return returnIndex ? i : value; } } } return returnIndex ? -1 : undefined; } return { get fill() { return fill; }, get find() { return find; }, get findIndex() { return findIndex; } }; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator", [], function() { "use strict"; var $__5; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator"; var $__6 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")), toObject = $__6.toObject, toUint32 = $__6.toUint32; var ARRAY_ITERATOR_KIND_KEYS = 1; var ARRAY_ITERATOR_KIND_VALUES = 2; var ARRAY_ITERATOR_KIND_ENTRIES = 3; var ArrayIterator = function ArrayIterator() {}; ($traceurRuntime.createClass)(ArrayIterator, ($__5 = {}, Object.defineProperty($__5, "next", { value: function() { var iterator = toObject(this); var array = iterator.iteratorObject_; if (!array) { throw new TypeError('Object is not an ArrayIterator'); } var index = iterator.arrayIteratorNextIndex_; var itemKind = iterator.arrayIterationKind_; var length = toUint32(array.length); if (index >= length) { iterator.arrayIteratorNextIndex_ = Infinity; return createIteratorResultObject(undefined, true); } iterator.arrayIteratorNextIndex_ = index + 1; if (itemKind == ARRAY_ITERATOR_KIND_VALUES) return createIteratorResultObject(array[index], false); if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES) return createIteratorResultObject([index, array[index]], false); return createIteratorResultObject(index, false); }, configurable: true, enumerable: true, writable: true }), Object.defineProperty($__5, Symbol.iterator, { value: function() { return this; }, configurable: true, enumerable: true, writable: true }), $__5), {}); function createArrayIterator(array, kind) { var object = toObject(array); var iterator = new ArrayIterator; iterator.iteratorObject_ = object; iterator.arrayIteratorNextIndex_ = 0; iterator.arrayIterationKind_ = kind; return iterator; } function createIteratorResultObject(value, done) { return { value: value, done: done }; } function entries() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES); } function keys() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS); } function values() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES); } return { get entries() { return entries; }, get keys() { return keys; }, get values() { return values; } }; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Map", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Map"; var isObject = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")).isObject; var getOwnHashObject = $traceurRuntime.getOwnHashObject; var $hasOwnProperty = Object.prototype.hasOwnProperty; var deletedSentinel = {}; function lookupIndex(map, key) { if (isObject(key)) { var hashObject = getOwnHashObject(key); return hashObject && map.objectIndex_[hashObject.hash]; } if (typeof key === 'string') return map.stringIndex_[key]; return map.primitiveIndex_[key]; } function initMap(map) { map.entries_ = []; map.objectIndex_ = Object.create(null); map.stringIndex_ = Object.create(null); map.primitiveIndex_ = Object.create(null); map.deletedCount_ = 0; } var Map = function Map() { var iterable = arguments[0]; if (!isObject(this)) throw new TypeError("Constructor Map requires 'new'"); if ($hasOwnProperty.call(this, 'entries_')) { throw new TypeError("Map can not be reentrantly initialised"); } initMap(this); if (iterable !== null && iterable !== undefined) { var iter = iterable[Symbol.iterator]; if (iter !== undefined) { for (var $__8 = iterable[Symbol.iterator](), $__9; !($__9 = $__8.next()).done; ) { var $__10 = $traceurRuntime.assertObject($__9.value), key = $__10[0], value = $__10[1]; { this.set(key, value); } } } } }; ($traceurRuntime.createClass)(Map, { get size() { return this.entries_.length / 2 - this.deletedCount_; }, get: function(key) { var index = lookupIndex(this, key); if (index !== undefined) return this.entries_[index + 1]; }, set: function(key, value) { var objectMode = isObject(key); var stringMode = typeof key === 'string'; var index = lookupIndex(this, key); if (index !== undefined) { this.entries_[index + 1] = value; } else { index = this.entries_.length; this.entries_[index] = key; this.entries_[index + 1] = value; if (objectMode) { var hashObject = getOwnHashObject(key); var hash = hashObject.hash; this.objectIndex_[hash] = index; } else if (stringMode) { this.stringIndex_[key] = index; } else { this.primitiveIndex_[key] = index; } } return this; }, has: function(key) { return lookupIndex(this, key) !== undefined; }, delete: function(key) { var objectMode = isObject(key); var stringMode = typeof key === 'string'; var index; var hash; if (objectMode) { var hashObject = getOwnHashObject(key); if (hashObject) { index = this.objectIndex_[hash = hashObject.hash]; delete this.objectIndex_[hash]; } } else if (stringMode) { index = this.stringIndex_[key]; delete this.stringIndex_[key]; } else { index = this.primitiveIndex_[key]; delete this.primitiveIndex_[key]; } if (index !== undefined) { this.entries_[index] = deletedSentinel; this.entries_[index + 1] = undefined; this.deletedCount_++; } }, clear: function() { initMap(this); }, forEach: function(callbackFn) { var thisArg = arguments[1]; for (var i = 0, len = this.entries_.length; i < len; i += 2) { var key = this.entries_[i]; var value = this.entries_[i + 1]; if (key === deletedSentinel) continue; callbackFn.call(thisArg, value, key, this); } } }, {}); return {get Map() { return Map; }}; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Object", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Object"; var $__11 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")), toInteger = $__11.toInteger, toLength = $__11.toLength, toObject = $__11.toObject, isCallable = $__11.isCallable; var $__11 = $traceurRuntime.assertObject($traceurRuntime), defineProperty = $__11.defineProperty, getOwnPropertyDescriptor = $__11.getOwnPropertyDescriptor, getOwnPropertyNames = $__11.getOwnPropertyNames, keys = $__11.keys, privateNames = $__11.privateNames; function is(left, right) { if (left === right) return left !== 0 || 1 / left === 1 / right; return left !== left && right !== right; } function assign(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; var props = keys(source); var p, length = props.length; for (p = 0; p < length; p++) { var name = props[p]; if (privateNames[name]) continue; target[name] = source[name]; } } return target; } function mixin(target, source) { var props = getOwnPropertyNames(source); var p, descriptor, length = props.length; for (p = 0; p < length; p++) { var name = props[p]; if (privateNames[name]) continue; descriptor = getOwnPropertyDescriptor(source, props[p]); defineProperty(target, props[p], descriptor); } return target; } return { get is() { return is; }, get assign() { return assign; }, get mixin() { return mixin; } }; }); System.register("traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap"; var $__default = function asap(callback, arg) { var length = queue.push([callback, arg]); if (length === 1) { scheduleFlush(); } }; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; function useNextTick() { return function() { process.nextTick(flush); }; } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, {characterData: true}); return function() { node.data = (iterations = ++iterations % 2); }; } function useSetTimeout() { return function() { setTimeout(flush, 1); }; } var queue = []; function flush() { for (var i = 0; i < queue.length; i++) { var tuple = queue[i]; var callback = tuple[0], arg = tuple[1]; callback(arg); } queue = []; } var scheduleFlush; if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else { scheduleFlush = useSetTimeout(); } return {get default() { return $__default; }}; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Promise", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Promise"; var async = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap")).default; var promiseRaw = {}; function isPromise(x) { return x && typeof x === 'object' && x.status_ !== undefined; } function idResolveHandler(x) { return x; } function idRejectHandler(x) { throw x; } function chain(promise) { var onResolve = arguments[1] !== (void 0) ? arguments[1] : idResolveHandler; var onReject = arguments[2] !== (void 0) ? arguments[2] : idRejectHandler; var deferred = getDeferred(promise.constructor); switch (promise.status_) { case undefined: throw TypeError; case 0: promise.onResolve_.push(onResolve, deferred); promise.onReject_.push(onReject, deferred); break; case +1: promiseEnqueue(promise.value_, [onResolve, deferred]); break; case -1: promiseEnqueue(promise.value_, [onReject, deferred]); break; } return deferred.promise; } function getDeferred(C) { if (this === $Promise) { var promise = promiseInit(new $Promise(promiseRaw)); return { promise: promise, resolve: (function(x) { promiseResolve(promise, x); }), reject: (function(r) { promiseReject(promise, r); }) }; } else { var result = {}; result.promise = new C((function(resolve, reject) { result.resolve = resolve; result.reject = reject; })); return result; } } function promiseSet(promise, status, value, onResolve, onReject) { promise.status_ = status; promise.value_ = value; promise.onResolve_ = onResolve; promise.onReject_ = onReject; return promise; } function promiseInit(promise) { return promiseSet(promise, 0, undefined, [], []); } var Promise = function Promise(resolver) { if (resolver === promiseRaw) return; if (typeof resolver !== 'function') throw new TypeError; var promise = promiseInit(this); try { resolver((function(x) { promiseResolve(promise, x); }), (function(r) { promiseReject(promise, r); })); } catch (e) { promiseReject(promise, e); } }; ($traceurRuntime.createClass)(Promise, { catch: function(onReject) { return this.then(undefined, onReject); }, then: function(onResolve, onReject) { if (typeof onResolve !== 'function') onResolve = idResolveHandler; if (typeof onReject !== 'function') onReject = idRejectHandler; var that = this; var constructor = this.constructor; return chain(this, function(x) { x = promiseCoerce(constructor, x); return x === that ? onReject(new TypeError) : isPromise(x) ? x.then(onResolve, onReject) : onResolve(x); }, onReject); } }, { resolve: function(x) { if (this === $Promise) { return promiseSet(new $Promise(promiseRaw), +1, x); } else { return new this(function(resolve, reject) { resolve(x); }); } }, reject: function(r) { if (this === $Promise) { return promiseSet(new $Promise(promiseRaw), -1, r); } else { return new this((function(resolve, reject) { reject(r); })); } }, cast: function(x) { if (x instanceof this) return x; if (isPromise(x)) { var result = getDeferred(this); chain(x, result.resolve, result.reject); return result.promise; } return this.resolve(x); }, all: function(values) { var deferred = getDeferred(this); var resolutions = []; try { var count = values.length; if (count === 0) { deferred.resolve(resolutions); } else { for (var i = 0; i < values.length; i++) { this.resolve(values[i]).then(function(i, x) { resolutions[i] = x; if (--count === 0) deferred.resolve(resolutions); }.bind(undefined, i), (function(r) { deferred.reject(r); })); } } } catch (e) { deferred.reject(e); } return deferred.promise; }, race: function(values) { var deferred = getDeferred(this); try { for (var i = 0; i < values.length; i++) { this.resolve(values[i]).then((function(x) { deferred.resolve(x); }), (function(r) { deferred.reject(r); })); } } catch (e) { deferred.reject(e); } return deferred.promise; } }); var $Promise = Promise; var $PromiseReject = $Promise.reject; function promiseResolve(promise, x) { promiseDone(promise, +1, x, promise.onResolve_); } function promiseReject(promise, r) { promiseDone(promise, -1, r, promise.onReject_); } function promiseDone(promise, status, value, reactions) { if (promise.status_ !== 0) return; promiseEnqueue(value, reactions); promiseSet(promise, status, value); } function promiseEnqueue(value, tasks) { async((function() { for (var i = 0; i < tasks.length; i += 2) { promiseHandle(value, tasks[i], tasks[i + 1]); } })); } function promiseHandle(value, handler, deferred) { try { var result = handler(value); if (result === deferred.promise) throw new TypeError; else if (isPromise(result)) chain(result, deferred.resolve, deferred.reject); else deferred.resolve(result); } catch (e) { try { deferred.reject(e); } catch (e) {} } } var thenableSymbol = '@@thenable'; function isObject(x) { return x && (typeof x === 'object' || typeof x === 'function'); } function promiseCoerce(constructor, x) { if (!isPromise(x) && isObject(x)) { var then; try { then = x.then; } catch (r) { var promise = $PromiseReject.call(constructor, r); x[thenableSymbol] = promise; return promise; } if (typeof then === 'function') { var p = x[thenableSymbol]; if (p) { return p; } else { var deferred = getDeferred(constructor); x[thenableSymbol] = deferred.promise; try { then.call(x, deferred.resolve, deferred.reject); } catch (r) { deferred.reject(r); } return deferred.promise; } } } return x; } return {get Promise() { return Promise; }}; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/String", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/String"; var $toString = Object.prototype.toString; var $indexOf = String.prototype.indexOf; var $lastIndexOf = String.prototype.lastIndexOf; function startsWith(search) { var string = String(this); if (this == null || $toString.call(search) == '[object RegExp]') { throw TypeError(); } var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var position = arguments.length > 1 ? arguments[1] : undefined; var pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } var start = Math.min(Math.max(pos, 0), stringLength); return $indexOf.call(string, searchString, pos) == start; } function endsWith(search) { var string = String(this); if (this == null || $toString.call(search) == '[object RegExp]') { throw TypeError(); } var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var pos = stringLength; if (arguments.length > 1) { var position = arguments[1]; if (position !== undefined) { pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } } } var end = Math.min(Math.max(pos, 0), stringLength); var start = end - searchLength; if (start < 0) { return false; } return $lastIndexOf.call(string, searchString, start) == start; } function contains(search) { if (this == null) { throw TypeError(); } var string = String(this); var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var position = arguments.length > 1 ? arguments[1] : undefined; var pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } var start = Math.min(Math.max(pos, 0), stringLength); return $indexOf.call(string, searchString, pos) != -1; } function repeat(count) { if (this == null) { throw TypeError(); } var string = String(this); var n = count ? Number(count) : 0; if (isNaN(n)) { n = 0; } if (n < 0 || n == Infinity) { throw RangeError(); } if (n == 0) { return ''; } var result = ''; while (n--) { result += string; } return result; } function codePointAt(position) { if (this == null) { throw TypeError(); } var string = String(this); var size = string.length; var index = position ? Number(position) : 0; if (isNaN(index)) { index = 0; } if (index < 0 || index >= size) { return undefined; } var first = string.charCodeAt(index); var second; if (first >= 0xD800 && first <= 0xDBFF && size > index + 1) { second = string.charCodeAt(index + 1); if (second >= 0xDC00 && second <= 0xDFFF) { return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; } } return first; } function raw(callsite) { var raw = callsite.raw; var len = raw.length >>> 0; if (len === 0) return ''; var s = ''; var i = 0; while (true) { s += raw[i]; if (i + 1 === len) return s; s += arguments[++i]; } } function fromCodePoint() { var codeUnits = []; var floor = Math.floor; var highSurrogate; var lowSurrogate; var index = -1; var length = arguments.length; if (!length) { return ''; } while (++index < length) { var codePoint = Number(arguments[index]); if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || floor(codePoint) != codePoint) { throw RangeError('Invalid code point: ' + codePoint); } if (codePoint <= 0xFFFF) { codeUnits.push(codePoint); } else { codePoint -= 0x10000; highSurrogate = (codePoint >> 10) + 0xD800; lowSurrogate = (codePoint % 0x400) + 0xDC00; codeUnits.push(highSurrogate, lowSurrogate); } } return String.fromCharCode.apply(null, codeUnits); } return { get startsWith() { return startsWith; }, get endsWith() { return endsWith; }, get contains() { return contains; }, get repeat() { return repeat; }, get codePointAt() { return codePointAt; }, get raw() { return raw; }, get fromCodePoint() { return fromCodePoint; } }; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/polyfills", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/polyfills"; var Map = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Map")).Map; var Promise = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Promise")).Promise; var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/String")), codePointAt = $__14.codePointAt, contains = $__14.contains, endsWith = $__14.endsWith, fromCodePoint = $__14.fromCodePoint, repeat = $__14.repeat, raw = $__14.raw, startsWith = $__14.startsWith; var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Array")), fill = $__14.fill, find = $__14.find, findIndex = $__14.findIndex; var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator")), entries = $__14.entries, keys = $__14.keys, values = $__14.values; var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Object")), assign = $__14.assign, is = $__14.is, mixin = $__14.mixin; function maybeDefineMethod(object, name, value) { if (!(name in object)) { Object.defineProperty(object, name, { value: value, configurable: true, enumerable: false, writable: true }); } } function maybeAddFunctions(object, functions) { for (var i = 0; i < functions.length; i += 2) { var name = functions[i]; var value = functions[i + 1]; maybeDefineMethod(object, name, value); } } function polyfillPromise(global) { if (!global.Promise) global.Promise = Promise; } function polyfillCollections(global) { if (!global.Map) global.Map = Map; } function polyfillString(String) { maybeAddFunctions(String.prototype, ['codePointAt', codePointAt, 'contains', contains, 'endsWith', endsWith, 'startsWith', startsWith, 'repeat', repeat]); maybeAddFunctions(String, ['fromCodePoint', fromCodePoint, 'raw', raw]); } function polyfillArray(Array, Symbol) { maybeAddFunctions(Array.prototype, ['entries', entries, 'keys', keys, 'values', values, 'fill', fill, 'find', find, 'findIndex', findIndex]); if (Symbol && Symbol.iterator) { Object.defineProperty(Array.prototype, Symbol.iterator, { value: values, configurable: true, enumerable: false, writable: true }); } } function polyfillObject(Object) { maybeAddFunctions(Object, ['assign', assign, 'is', is, 'mixin', mixin]); } function polyfill(global) { polyfillPromise(global); polyfillCollections(global); polyfillString(global.String); polyfillArray(global.Array, global.Symbol); polyfillObject(global.Object); } polyfill(this); var setupGlobals = $traceurRuntime.setupGlobals; $traceurRuntime.setupGlobals = function(global) { setupGlobals(global); polyfill(global); }; return {}; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfill-import", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfill-import"; var $__16 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/polyfills")); return {}; }); System.get("traceur-runtime@0.0.42/src/runtime/polyfill-import" + ''); }).call(this,require("FWaASH"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"FWaASH":1}],3:[function(require,module,exports){ /*! * jQuery JavaScript Library v2.1.0 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-01-23T21:10Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ // var arr = []; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var trim = "".trim; var support = {}; var // Use the correct document accordingly with window argument (sandbox) document = window.document, version = "2.1.0", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return a 'clean' array ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return just the object slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN return obj - parseFloat( obj ) >= 0; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Support: Firefox <20 // The try/catch suppresses exceptions thrown when attempting to access // the "constructor" property of certain host objects, ie. |window.location| // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 try { if ( obj.constructor && !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } } catch ( e ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android < 4.0, iOS < 6 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, trim: function( text ) { return text == null ? "" : trim.call( text ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v1.10.16 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-01-13 */ (function( window ) { var i, support, Expr, getText, isXML, compile, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (jQuery #6963) if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== strundefined && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", function() { setDocument(); }, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", function() { setDocument(); }); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select t=''><option selected=''></option></select>"; // Support: IE8, Opera 10-12 // Nothing should be selected when empty strings follow ^= or $= or *= if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, len = this.length, ret = [], self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); jQuery.fn.extend({ has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } } }); /** * The ready event handler and self cleanup method */ function completed() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : len ? fn( elems[0], key ) : emptyGet; }; /** * Determines whether an object can have data */ jQuery.acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = jQuery.acceptData; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; var data_priv = new Data(); var data_user = new Data(); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ); // #11217 - WebKit loses check when the name is after the checked attribute div.innerHTML = "<input type='radio' checked='checked' name='t'/>"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE9-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; })(); var strundefined = typeof undefined; support.focusinBubbles = "onfocusin" in window; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || // Support: Android < 4.0 src.defaultPrevented === undefined && src.getPreventDefault && src.getPreventDefault() ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); data_priv.remove( doc, fix ); } else { data_priv.access( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, events, type, key, j, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( jQuery.acceptData( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { events = Object.keys( data.events || {} ); if ( events.length ) { for ( j = 0; (type = events[j]) !== undefined; j++ ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each(function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } }); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because push.apply(_, arraylike) throws push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF window.getDefaultComputedStyle( elem[ 0 ] ).display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = iframe[ 0 ].contentDocument; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); }; function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // Support: IE9 // getPropertyValue is only needed for .css('filter') in IE9, see #12537 if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; } if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: iOS < 6 // A tribute to the "awesome hack by Dean Edwards" // iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { var pixelPositionVal, boxSizingReliableVal, // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;" + "-moz-box-sizing:content-box;box-sizing:content-box", docElem = document.documentElement, container = document.createElement( "div" ), div = document.createElement( "div" ); div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;" + "margin-top:1px"; container.appendChild( div ); // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computePixelPositionAndBoxSizingReliable() { // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" + "box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;" + "position:absolute;top:1%"; docElem.appendChild( container ); var divStyle = window.getComputedStyle( div, null ); pixelPositionVal = divStyle.top !== "1%"; boxSizingReliableVal = divStyle.width === "4px"; docElem.removeChild( container ); } // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { jQuery.extend(support, { pixelPosition: function() { // This test is executed only once but we still do memoizing // since we can use the boxSizingReliable pre-computing. // No need to check if the test was already performed, though. computePixelPositionAndBoxSizingReliable(); return pixelPositionVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computePixelPositionAndBoxSizingReliable(); } return boxSizingReliableVal; }, reliableMarginRight: function() { // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // This support function is only executed once so no memoizing is needed. var ret, marginDiv = div.appendChild( document.createElement( "div" ) ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; docElem.appendChild( container ); ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight ); docElem.removeChild( container ); // Clean up the div for other support tests. div.innerHTML = ""; return ret; } }); } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name[0].toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = data_priv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css(elem, "display") ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set. See: #7116 if ( value == null || value !== value ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifying setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Support: Chrome, Safari // Setting style to blank string required to delete "style: x !important;" style[ name ] = ""; style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // Support: Android 2.3 jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; } }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = data_priv.get( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE9-10 do not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); // Get default display if display is currently "none" if ( display === "none" ) { display = defaultDisplay( elem.nodeName ); } if ( display === "inline" && jQuery.css( elem, "float" ) === "none" ) { style.display = "inline-block"; } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = data_priv.access( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; data_priv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || data_priv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = data_priv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = data_priv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }; (function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; })(); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName( elem, "input" ) ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; }; }); var rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = arguments.length === 0 || typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; } }); var rreturn = /\r/g; jQuery.fn.extend({ val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); // Return jQuery for attributes-only inclusion jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var nonce = jQuery.now(); var rquery = (/\?/); // Support: Android 2.3 // Workaround failure to string-cast null input jQuery.parseJSON = function( data ) { return JSON.parse( data + "" ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ) .replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; }); jQuery._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; jQuery.fn.extend({ wrapAll: function( html ) { var wrap; if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapAll( html.call(this, i) ); }); } if ( this[ 0 ] ) { // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map(function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function( i ) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrId = 0, xhrCallbacks = {}, xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE9 // Open requests must be manually aborted on unload (#5280) if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } }); } support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // Accessing binary-data responseText throws an exception // (#11426) typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[ id ] = callback("abort"); // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( options.hasContent && options.data || null ); }, abort: function() { if ( callback ) { callback(); } } }; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1; // Need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : window.pageXOffset, top ? val : window.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); }); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; })); },{}],4:[function(require,module,exports){ (function (global){ //! moment.js //! version : 2.8.1 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com (function (undefined) { /************************************ Constants ************************************/ var moment, VERSION = '2.8.1', // the global-scope this is NOT the global object in Node.js globalScope = typeof global !== 'undefined' ? global : this, oldGlobalMoment, round = Math.round, i, YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, // internal storage for locale config files locales = {}, // extra moment internal properties (plugins register props here) momentProperties = [], // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports), // ASP.NET json date format regex aspNetJsonRegex = /^\/?Date\((\-?\d+)/i, aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/, // format tokens formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g, // parsing token regexes parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99 parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999 parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999 parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999 parseTokenDigits = /\d+/, // nonzero number of digits parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z parseTokenT = /T/i, // T (ISO separator) parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 parseTokenOrdinal = /\d{1,2}/, //strict parsing regexes parseTokenOneDigit = /\d/, // 0 - 9 parseTokenTwoDigits = /\d\d/, // 00 - 99 parseTokenThreeDigits = /\d{3}/, // 000 - 999 parseTokenFourDigits = /\d{4}/, // 0000 - 9999 parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999 parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/, isoFormat = 'YYYY-MM-DDTHH:mm:ssZ', isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], ['GGGG-[W]WW', /\d{4}-W\d{2}/], ['YYYY-DDD', /\d{4}-\d{3}/] ], // iso time formats and regexes isoTimes = [ ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], ['HH:mm', /(T| )\d\d:\d\d/], ['HH', /(T| )\d\d/] ], // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"] parseTimezoneChunker = /([\+\-]|\d\d)/gi, // getter and setter names proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'), unitMillisecondFactors = { 'Milliseconds' : 1, 'Seconds' : 1e3, 'Minutes' : 6e4, 'Hours' : 36e5, 'Days' : 864e5, 'Months' : 2592e6, 'Years' : 31536e6 }, unitAliases = { ms : 'millisecond', s : 'second', m : 'minute', h : 'hour', d : 'day', D : 'date', w : 'week', W : 'isoWeek', M : 'month', Q : 'quarter', y : 'year', DDD : 'dayOfYear', e : 'weekday', E : 'isoWeekday', gg: 'weekYear', GG: 'isoWeekYear' }, camelFunctions = { dayofyear : 'dayOfYear', isoweekday : 'isoWeekday', isoweek : 'isoWeek', weekyear : 'weekYear', isoweekyear : 'isoWeekYear' }, // format function strings formatFunctions = {}, // default relative time thresholds relativeTimeThresholds = { s: 45, // seconds to minute m: 45, // minutes to hour h: 22, // hours to day d: 26, // days to month M: 11 // months to year }, // tokens to ordinalize and pad ordinalizeTokens = 'DDD w W M D d'.split(' '), paddedTokens = 'M D H h m s w W'.split(' '), formatTokenFunctions = { M : function () { return this.month() + 1; }, MMM : function (format) { return this.localeData().monthsShort(this, format); }, MMMM : function (format) { return this.localeData().months(this, format); }, D : function () { return this.date(); }, DDD : function () { return this.dayOfYear(); }, d : function () { return this.day(); }, dd : function (format) { return this.localeData().weekdaysMin(this, format); }, ddd : function (format) { return this.localeData().weekdaysShort(this, format); }, dddd : function (format) { return this.localeData().weekdays(this, format); }, w : function () { return this.week(); }, W : function () { return this.isoWeek(); }, YY : function () { return leftZeroFill(this.year() % 100, 2); }, YYYY : function () { return leftZeroFill(this.year(), 4); }, YYYYY : function () { return leftZeroFill(this.year(), 5); }, YYYYYY : function () { var y = this.year(), sign = y >= 0 ? '+' : '-'; return sign + leftZeroFill(Math.abs(y), 6); }, gg : function () { return leftZeroFill(this.weekYear() % 100, 2); }, gggg : function () { return leftZeroFill(this.weekYear(), 4); }, ggggg : function () { return leftZeroFill(this.weekYear(), 5); }, GG : function () { return leftZeroFill(this.isoWeekYear() % 100, 2); }, GGGG : function () { return leftZeroFill(this.isoWeekYear(), 4); }, GGGGG : function () { return leftZeroFill(this.isoWeekYear(), 5); }, e : function () { return this.weekday(); }, E : function () { return this.isoWeekday(); }, a : function () { return this.localeData().meridiem(this.hours(), this.minutes(), true); }, A : function () { return this.localeData().meridiem(this.hours(), this.minutes(), false); }, H : function () { return this.hours(); }, h : function () { return this.hours() % 12 || 12; }, m : function () { return this.minutes(); }, s : function () { return this.seconds(); }, S : function () { return toInt(this.milliseconds() / 100); }, SS : function () { return leftZeroFill(toInt(this.milliseconds() / 10), 2); }, SSS : function () { return leftZeroFill(this.milliseconds(), 3); }, SSSS : function () { return leftZeroFill(this.milliseconds(), 3); }, Z : function () { var a = -this.zone(), b = '+'; if (a < 0) { a = -a; b = '-'; } return b + leftZeroFill(toInt(a / 60), 2) + ':' + leftZeroFill(toInt(a) % 60, 2); }, ZZ : function () { var a = -this.zone(), b = '+'; if (a < 0) { a = -a; b = '-'; } return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2); }, z : function () { return this.zoneAbbr(); }, zz : function () { return this.zoneName(); }, X : function () { return this.unix(); }, Q : function () { return this.quarter(); } }, deprecations = {}, lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin']; // Pick the first defined of two or three arguments. dfl comes from // default. function dfl(a, b, c) { switch (arguments.length) { case 2: return a != null ? a : b; case 3: return a != null ? a : b != null ? b : c; default: throw new Error('Implement me'); } } function defaultParsingFlags() { // We need to deep clone this object, and es5 standard is not very // helpful. return { empty : false, unusedTokens : [], unusedInput : [], overflow : -2, charsLeftOver : 0, nullInput : false, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso: false }; } function printMsg(msg) { if (moment.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) { console.warn("Deprecation warning: " + msg); } } function deprecate(msg, fn) { var firstTime = true; return extend(function () { if (firstTime) { printMsg(msg); firstTime = false; } return fn.apply(this, arguments); }, fn); } function deprecateSimple(name, msg) { if (!deprecations[name]) { printMsg(msg); deprecations[name] = true; } } function padToken(func, count) { return function (a) { return leftZeroFill(func.call(this, a), count); }; } function ordinalizeToken(func, period) { return function (a) { return this.localeData().ordinal(func.call(this, a), period); }; } while (ordinalizeTokens.length) { i = ordinalizeTokens.pop(); formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i); } while (paddedTokens.length) { i = paddedTokens.pop(); formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2); } formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3); /************************************ Constructors ************************************/ function Locale() { } // Moment prototype object function Moment(config, skipOverflow) { if (skipOverflow !== false) { checkOverflow(config); } copyConfig(this, config); this._d = new Date(+config._d); } // Duration Constructor function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 36e5; // 1000 * 60 * 60 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + quarters * 3 + years * 12; this._data = {}; this._locale = moment.localeData(); this._bubble(); } /************************************ Helpers ************************************/ function extend(a, b) { for (var i in b) { if (b.hasOwnProperty(i)) { a[i] = b[i]; } } if (b.hasOwnProperty('toString')) { a.toString = b.toString; } if (b.hasOwnProperty('valueOf')) { a.valueOf = b.valueOf; } return a; } function copyConfig(to, from) { var i, prop, val; if (typeof from._isAMomentObject !== 'undefined') { to._isAMomentObject = from._isAMomentObject; } if (typeof from._i !== 'undefined') { to._i = from._i; } if (typeof from._f !== 'undefined') { to._f = from._f; } if (typeof from._l !== 'undefined') { to._l = from._l; } if (typeof from._strict !== 'undefined') { to._strict = from._strict; } if (typeof from._tzm !== 'undefined') { to._tzm = from._tzm; } if (typeof from._isUTC !== 'undefined') { to._isUTC = from._isUTC; } if (typeof from._offset !== 'undefined') { to._offset = from._offset; } if (typeof from._pf !== 'undefined') { to._pf = from._pf; } if (typeof from._locale !== 'undefined') { to._locale = from._locale; } if (momentProperties.length > 0) { for (i in momentProperties) { prop = momentProperties[i]; val = from[prop]; if (typeof val !== 'undefined') { to[prop] = val; } } } return to; } function absRound(number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } // left zero fill a number // see http://jsperf.com/left-zero-filling for performance comparison function leftZeroFill(number, targetLength, forceSign) { var output = '' + Math.abs(number), sign = number >= 0; while (output.length < targetLength) { output = '0' + output; } return (sign ? (forceSign ? '+' : '') : '-') + output; } function positiveMomentsDifference(base, other) { var res = {milliseconds: 0, months: 0}; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +(base.clone().add(res.months, 'M')); return res; } function momentsDifference(base, other) { var res; other = makeAs(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; } // TODO: remove 'name' arg after deprecation is removed function createAdder(direction, name) { return function (val, period) { var dur, tmp; //invert the arguments, but complain about it if (period !== null && !isNaN(+period)) { deprecateSimple(name, "moment()." + name + "(period, number) is deprecated. Please use moment()." + name + "(number, period)."); tmp = val; val = period; period = tmp; } val = typeof val === 'string' ? +val : val; dur = moment.duration(val, period); addOrSubtractDurationFromMoment(this, dur, direction); return this; }; } function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) { var milliseconds = duration._milliseconds, days = duration._days, months = duration._months; updateOffset = updateOffset == null ? true : updateOffset; if (milliseconds) { mom._d.setTime(+mom._d + milliseconds * isAdding); } if (days) { rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding); } if (months) { rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding); } if (updateOffset) { moment.updateOffset(mom, days || months); } } // check if is an array function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]'; } function isDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function normalizeUnits(units) { if (units) { var lowered = units.toLowerCase().replace(/(.)s$/, '$1'); units = unitAliases[units] || camelFunctions[lowered] || lowered; } return units; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (inputObject.hasOwnProperty(prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } function makeList(field) { var count, setter; if (field.indexOf('week') === 0) { count = 7; setter = 'day'; } else if (field.indexOf('month') === 0) { count = 12; setter = 'month'; } else { return; } moment[field] = function (format, index) { var i, getter, method = moment._locale[field], results = []; if (typeof format === 'number') { index = format; format = undefined; } getter = function (i) { var m = moment().utc().set(setter, i); return method.call(moment._locale, m, format || ''); }; if (index != null) { return getter(index); } else { for (i = 0; i < count; i++) { results.push(getter(i)); } return results; } }; } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { if (coercedNumber >= 0) { value = Math.floor(coercedNumber); } else { value = Math.ceil(coercedNumber); } } return value; } function daysInMonth(year, month) { return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } function weeksInYear(year, dow, doy) { return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week; } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function checkOverflow(m) { var overflow; if (m._a && m._pf.overflow === -2) { overflow = m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH : m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE : m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR : m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE : m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND : m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND : -1; if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } m._pf.overflow = overflow; } } function isValid(m) { if (m._isValid == null) { m._isValid = !isNaN(m._d.getTime()) && m._pf.overflow < 0 && !m._pf.empty && !m._pf.invalidMonth && !m._pf.nullInput && !m._pf.invalidFormat && !m._pf.userInvalidated; if (m._strict) { m._isValid = m._isValid && m._pf.charsLeftOver === 0 && m._pf.unusedTokens.length === 0; } } return m._isValid; } function normalizeLocale(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // pick the locale from the array // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root function chooseLocale(names) { var i = 0, j, next, locale, split; while (i < names.length) { split = normalizeLocale(names[i]).split('-'); j = split.length; next = normalizeLocale(names[i + 1]); next = next ? next.split('-') : null; while (j > 0) { locale = loadLocale(split.slice(0, j).join('-')); if (locale) { return locale; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return null; } function loadLocale(name) { var oldLocale = null; if (!locales[name] && hasModule) { try { oldLocale = moment.locale(); require('./locale/' + name); // because defineLocale currently also sets the global locale, we want to undo that for lazy loaded locales moment.locale(oldLocale); } catch (e) { } } return locales[name]; } // Return a moment from input, that is local/utc/zone equivalent to model. function makeAs(input, model) { return model._isUTC ? moment(input).zone(model._offset || 0) : moment(input).local(); } /************************************ Locale ************************************/ extend(Locale.prototype, { set : function (config) { var prop, i; for (i in config) { prop = config[i]; if (typeof prop === 'function') { this[i] = prop; } else { this['_' + i] = prop; } } }, _months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), months : function (m) { return this._months[m.month()]; }, _monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), monthsShort : function (m) { return this._monthsShort[m.month()]; }, monthsParse : function (monthName) { var i, mom, regex; if (!this._monthsParse) { this._monthsParse = []; } for (i = 0; i < 12; i++) { // make the regex if we don't have it already if (!this._monthsParse[i]) { mom = moment.utc([2000, i]); regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._monthsParse[i].test(monthName)) { return i; } } }, _weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdays : function (m) { return this._weekdays[m.day()]; }, _weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysShort : function (m) { return this._weekdaysShort[m.day()]; }, _weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), weekdaysMin : function (m) { return this._weekdaysMin[m.day()]; }, weekdaysParse : function (weekdayName) { var i, mom, regex; if (!this._weekdaysParse) { this._weekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already if (!this._weekdaysParse[i]) { mom = moment([2000, 1]).day(i); regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._weekdaysParse[i].test(weekdayName)) { return i; } } }, _longDateFormat : { LT : 'h:mm A', L : 'MM/DD/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY LT', LLLL : 'dddd, MMMM D, YYYY LT' }, longDateFormat : function (key) { var output = this._longDateFormat[key]; if (!output && this._longDateFormat[key.toUpperCase()]) { output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); this._longDateFormat[key] = output; } return output; }, isPM : function (input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); }, _meridiemParse : /[ap]\.?m?\.?/i, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } }, _calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendar[key]; return typeof output === 'function' ? output.apply(mom) : output; }, _relativeTime : { future : 'in %s', past : '%s ago', s : 'a few seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }, relativeTime : function (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (typeof output === 'function') ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); }, pastFuture : function (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); }, ordinal : function (number) { return this._ordinal.replace('%d', number); }, _ordinal : '%d', preparse : function (string) { return string; }, postformat : function (string) { return string; }, week : function (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; }, _week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. }, _invalidDate: 'Invalid date', invalidDate: function () { return this._invalidDate; } }); /************************************ Formatting ************************************/ function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ''); } return input.replace(/\\/g, ''); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = ''; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.localeData().invalidDate(); } format = expandFormat(format, m.localeData()); if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } function expandFormat(format, locale) { var i = 5; function replaceLongDateFormatTokens(input) { return locale.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } /************************************ Parsing ************************************/ // get the regex to find the next token function getParseRegexForToken(token, config) { var a, strict = config._strict; switch (token) { case 'Q': return parseTokenOneDigit; case 'DDDD': return parseTokenThreeDigits; case 'YYYY': case 'GGGG': case 'gggg': return strict ? parseTokenFourDigits : parseTokenOneToFourDigits; case 'Y': case 'G': case 'g': return parseTokenSignedNumber; case 'YYYYYY': case 'YYYYY': case 'GGGGG': case 'ggggg': return strict ? parseTokenSixDigits : parseTokenOneToSixDigits; case 'S': if (strict) { return parseTokenOneDigit; } /* falls through */ case 'SS': if (strict) { return parseTokenTwoDigits; } /* falls through */ case 'SSS': if (strict) { return parseTokenThreeDigits; } /* falls through */ case 'DDD': return parseTokenOneToThreeDigits; case 'MMM': case 'MMMM': case 'dd': case 'ddd': case 'dddd': return parseTokenWord; case 'a': case 'A': return config._locale._meridiemParse; case 'X': return parseTokenTimestampMs; case 'Z': case 'ZZ': return parseTokenTimezone; case 'T': return parseTokenT; case 'SSSS': return parseTokenDigits; case 'MM': case 'DD': case 'YY': case 'GG': case 'gg': case 'HH': case 'hh': case 'mm': case 'ss': case 'ww': case 'WW': return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits; case 'M': case 'D': case 'd': case 'H': case 'h': case 'm': case 's': case 'w': case 'W': case 'e': case 'E': return parseTokenOneOrTwoDigits; case 'Do': return parseTokenOrdinal; default : a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), 'i')); return a; } } function timezoneMinutesFromString(string) { string = string || ''; var possibleTzMatches = (string.match(parseTokenTimezone) || []), tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [], parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0], minutes = +(parts[1] * 60) + toInt(parts[2]); return parts[0] === '+' ? -minutes : minutes; } // function to convert string input to date function addTimeToArrayFromToken(token, input, config) { var a, datePartArray = config._a; switch (token) { // QUARTER case 'Q': if (input != null) { datePartArray[MONTH] = (toInt(input) - 1) * 3; } break; // MONTH case 'M' : // fall through to MM case 'MM' : if (input != null) { datePartArray[MONTH] = toInt(input) - 1; } break; case 'MMM' : // fall through to MMMM case 'MMMM' : a = config._locale.monthsParse(input); // if we didn't find a month name, mark the date as invalid. if (a != null) { datePartArray[MONTH] = a; } else { config._pf.invalidMonth = input; } break; // DAY OF MONTH case 'D' : // fall through to DD case 'DD' : if (input != null) { datePartArray[DATE] = toInt(input); } break; case 'Do' : if (input != null) { datePartArray[DATE] = toInt(parseInt(input, 10)); } break; // DAY OF YEAR case 'DDD' : // fall through to DDDD case 'DDDD' : if (input != null) { config._dayOfYear = toInt(input); } break; // YEAR case 'YY' : datePartArray[YEAR] = moment.parseTwoDigitYear(input); break; case 'YYYY' : case 'YYYYY' : case 'YYYYYY' : datePartArray[YEAR] = toInt(input); break; // AM / PM case 'a' : // fall through to A case 'A' : config._isPm = config._locale.isPM(input); break; // 24 HOUR case 'H' : // fall through to hh case 'HH' : // fall through to hh case 'h' : // fall through to hh case 'hh' : datePartArray[HOUR] = toInt(input); break; // MINUTE case 'm' : // fall through to mm case 'mm' : datePartArray[MINUTE] = toInt(input); break; // SECOND case 's' : // fall through to ss case 'ss' : datePartArray[SECOND] = toInt(input); break; // MILLISECOND case 'S' : case 'SS' : case 'SSS' : case 'SSSS' : datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000); break; // UNIX TIMESTAMP WITH MS case 'X': config._d = new Date(parseFloat(input) * 1000); break; // TIMEZONE case 'Z' : // fall through to ZZ case 'ZZ' : config._useUTC = true; config._tzm = timezoneMinutesFromString(input); break; // WEEKDAY - human case 'dd': case 'ddd': case 'dddd': a = config._locale.weekdaysParse(input); // if we didn't get a weekday name, mark the date as invalid if (a != null) { config._w = config._w || {}; config._w['d'] = a; } else { config._pf.invalidWeekday = input; } break; // WEEK, WEEK DAY - numeric case 'w': case 'ww': case 'W': case 'WW': case 'd': case 'e': case 'E': token = token.substr(0, 1); /* falls through */ case 'gggg': case 'GGGG': case 'GGGGG': token = token.substr(0, 2); if (input) { config._w = config._w || {}; config._w[token] = toInt(input); } break; case 'gg': case 'GG': config._w = config._w || {}; config._w[token] = moment.parseTwoDigitYear(input); } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on // how we interpret now (local, utc, fixed offset). So create // a now version of current config (take local/utc/offset flags, and // create now). weekYear = dfl(w.GG, config._a[YEAR], weekOfYear(moment(), 1, 4).year); week = dfl(w.W, 1); weekday = dfl(w.E, 1); } else { dow = config._locale._week.dow; doy = config._locale._week.doy; weekYear = dfl(w.gg, config._a[YEAR], weekOfYear(moment(), dow, doy).year); week = dfl(w.w, 1); if (w.d != null) { // weekday -- low day numbers are considered next week weekday = w.d; if (weekday < dow) { ++week; } } else if (w.e != null) { // local weekday -- counting starts from begining of week weekday = w.e + dow; } else { // default to begining of week weekday = dow; } } temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function dateFromConfig(config) { var i, date, input = [], currentDate, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } //if the day of the year is set, figure out what it is if (config._dayOfYear) { yearToUse = dfl(config._a[YEAR], currentDate[YEAR]); if (config._dayOfYear > daysInYear(yearToUse)) { config._pf._overflowDayOfYear = true; } date = makeUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input); // Apply timezone offset from input. The actual zone can be changed // with parseZone. if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() + config._tzm); } } function dateFromObject(config) { var normalizedInput; if (config._d) { return; } normalizedInput = normalizeObjectUnits(config._i); config._a = [ normalizedInput.year, normalizedInput.month, normalizedInput.day, normalizedInput.hour, normalizedInput.minute, normalizedInput.second, normalizedInput.millisecond ]; dateFromConfig(config); } function currentDateArray(config) { var now = new Date(); if (config._useUTC) { return [ now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() ]; } else { return [now.getFullYear(), now.getMonth(), now.getDate()]; } } // date from string and format string function makeDateFromStringAndFormat(config) { if (config._f === moment.ISO_8601) { parseISO(config); return; } config._a = []; config._pf.empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { config._pf.unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { config._pf.empty = false; } else { config._pf.unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { config._pf.unusedTokens.push(token); } } // add remaining unparsed input length to the string config._pf.charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { config._pf.unusedInput.push(string); } // handle am pm if (config._isPm && config._a[HOUR] < 12) { config._a[HOUR] += 12; } // if is 12 am, change hours to 0 if (config._isPm === false && config._a[HOUR] === 12) { config._a[HOUR] = 0; } dateFromConfig(config); checkOverflow(config); } function unescapeFormat(s) { return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; }); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function regexpEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } // date from string and array of format strings function makeDateFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { config._pf.invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = copyConfig({}, config); tempConfig._pf = defaultParsingFlags(); tempConfig._f = config._f[i]; makeDateFromStringAndFormat(tempConfig); if (!isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += tempConfig._pf.charsLeftOver; //or tokens currentScore += tempConfig._pf.unusedTokens.length * 10; tempConfig._pf.score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } // date from iso format function parseISO(config) { var i, l, string = config._i, match = isoRegex.exec(string); if (match) { config._pf.iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(string)) { // match[5] should be "T" or undefined config._f = isoDates[i][0] + (match[6] || ' '); break; } } for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(string)) { config._f += isoTimes[i][0]; break; } } if (string.match(parseTokenTimezone)) { config._f += 'Z'; } makeDateFromStringAndFormat(config); } else { config._isValid = false; } } // date from iso format or fallback function makeDateFromString(config) { parseISO(config); if (config._isValid === false) { delete config._isValid; moment.createFromInputFallback(config); } } function makeDateFromInput(config) { var input = config._i, matched; if (input === undefined) { config._d = new Date(); } else if (isDate(input)) { config._d = new Date(+input); } else if ((matched = aspNetJsonRegex.exec(input)) !== null) { config._d = new Date(+matched[1]); } else if (typeof input === 'string') { makeDateFromString(config); } else if (isArray(input)) { config._a = input.slice(0); dateFromConfig(config); } else if (typeof(input) === 'object') { dateFromObject(config); } else if (typeof(input) === 'number') { // from milliseconds config._d = new Date(input); } else { moment.createFromInputFallback(config); } } function makeDate(y, m, d, h, M, s, ms) { //can't just apply() to create a date: //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply var date = new Date(y, m, d, h, M, s, ms); //the date constructor doesn't accept years < 1970 if (y < 1970) { date.setFullYear(y); } return date; } function makeUTCDate(y) { var date = new Date(Date.UTC.apply(null, arguments)); if (y < 1970) { date.setUTCFullYear(y); } return date; } function parseWeekday(input, locale) { if (typeof input === 'string') { if (!isNaN(input)) { input = parseInt(input, 10); } else { input = locale.weekdaysParse(input); if (typeof input !== 'number') { return null; } } } return input; } /************************************ Relative Time ************************************/ // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime(posNegDuration, withoutSuffix, locale) { var duration = moment.duration(posNegDuration).abs(), seconds = round(duration.as('s')), minutes = round(duration.as('m')), hours = round(duration.as('h')), days = round(duration.as('d')), months = round(duration.as('M')), years = round(duration.as('y')), args = seconds < relativeTimeThresholds.s && ['s', seconds] || minutes === 1 && ['m'] || minutes < relativeTimeThresholds.m && ['mm', minutes] || hours === 1 && ['h'] || hours < relativeTimeThresholds.h && ['hh', hours] || days === 1 && ['d'] || days < relativeTimeThresholds.d && ['dd', days] || months === 1 && ['M'] || months < relativeTimeThresholds.M && ['MM', months] || years === 1 && ['y'] || ['yy', years]; args[2] = withoutSuffix; args[3] = +posNegDuration > 0; args[4] = locale; return substituteTimeAgo.apply({}, args); } /************************************ Week of Year ************************************/ // firstDayOfWeek 0 = sun, 6 = sat // the day of the week that starts the week // (usually sunday or monday) // firstDayOfWeekOfYear 0 = sun, 6 = sat // the first week is the week that contains the first // of this day of the week // (eg. ISO weeks use thursday (4)) function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { var end = firstDayOfWeekOfYear - firstDayOfWeek, daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), adjustedMoment; if (daysToDayOfWeek > end) { daysToDayOfWeek -= 7; } if (daysToDayOfWeek < end - 7) { daysToDayOfWeek += 7; } adjustedMoment = moment(mom).add(daysToDayOfWeek, 'd'); return { week: Math.ceil(adjustedMoment.dayOfYear() / 7), year: adjustedMoment.year() }; } //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear; d = d === 0 ? 7 : d; weekday = weekday != null ? weekday : firstDayOfWeek; daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; return { year: dayOfYear > 0 ? year : year - 1, dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear }; } /************************************ Top Level Functions ************************************/ function makeMoment(config) { var input = config._i, format = config._f; config._locale = config._locale || moment.localeData(config._l); if (input === null || (format === undefined && input === '')) { return moment.invalid({nullInput: true}); } if (typeof input === 'string') { config._i = input = config._locale.preparse(input); } if (moment.isMoment(input)) { return new Moment(input, true); } else if (format) { if (isArray(format)) { makeDateFromStringAndArray(config); } else { makeDateFromStringAndFormat(config); } } else { makeDateFromInput(config); } return new Moment(config); } moment = function (input, format, locale, strict) { var c; if (typeof(locale) === "boolean") { strict = locale; locale = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._i = input; c._f = format; c._l = locale; c._strict = strict; c._isUTC = false; c._pf = defaultParsingFlags(); return makeMoment(c); }; moment.suppressDeprecationWarnings = false; moment.createFromInputFallback = deprecate( 'moment construction falls back to js Date. This is ' + 'discouraged and will be removed in upcoming major ' + 'release. Please refer to ' + 'https://github.com/moment/moment/issues/1407 for more info.', function (config) { config._d = new Date(config._i); } ); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. // // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return moment(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (moments[i][fn](res)) { res = moments[i]; } } return res; } moment.min = function () { var args = [].slice.call(arguments, 0); return pickBy('isBefore', args); }; moment.max = function () { var args = [].slice.call(arguments, 0); return pickBy('isAfter', args); }; // creating with utc moment.utc = function (input, format, locale, strict) { var c; if (typeof(locale) === "boolean") { strict = locale; locale = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._useUTC = true; c._isUTC = true; c._l = locale; c._i = input; c._f = format; c._strict = strict; c._pf = defaultParsingFlags(); return makeMoment(c).utc(); }; // creating with unix timestamp (in seconds) moment.unix = function (input) { return moment(input * 1000); }; // duration moment.duration = function (input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, parseIso, diffRes; if (moment.isDuration(input)) { duration = { ms: input._milliseconds, d: input._days, M: input._months }; } else if (typeof input === 'number') { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y: 0, d: toInt(match[DATE]) * sign, h: toInt(match[HOUR]) * sign, m: toInt(match[MINUTE]) * sign, s: toInt(match[SECOND]) * sign, ms: toInt(match[MILLISECOND]) * sign }; } else if (!!(match = isoDurationRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; parseIso = function (inp) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; }; duration = { y: parseIso(match[2]), M: parseIso(match[3]), d: parseIso(match[4]), h: parseIso(match[5]), m: parseIso(match[6]), s: parseIso(match[7]), w: parseIso(match[8]) }; } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { diffRes = momentsDifference(moment(duration.from), moment(duration.to)); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (moment.isDuration(input) && input.hasOwnProperty('_locale')) { ret._locale = input._locale; } return ret; }; // version number moment.version = VERSION; // default format moment.defaultFormat = isoFormat; // constant that refers to the ISO standard moment.ISO_8601 = function () {}; // Plugins that add properties should also add the key here (null value), // so we can properly clone ourselves. moment.momentProperties = momentProperties; // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. moment.updateOffset = function () {}; // This function allows you to set a threshold for relative time strings moment.relativeTimeThreshold = function (threshold, limit) { if (relativeTimeThresholds[threshold] === undefined) { return false; } if (limit === undefined) { return relativeTimeThresholds[threshold]; } relativeTimeThresholds[threshold] = limit; return true; }; moment.lang = deprecate( "moment.lang is deprecated. Use moment.locale instead.", function (key, value) { return moment.locale(key, value); } ); // This function will load locale and then set the global locale. If // no arguments are passed in, it will simply return the current global // locale key. moment.locale = function (key, values) { var data; if (key) { if (typeof(values) !== "undefined") { data = moment.defineLocale(key, values); } else { data = moment.localeData(key); } if (data) { moment.duration._locale = moment._locale = data; } } return moment._locale._abbr; }; moment.defineLocale = function (name, values) { if (values !== null) { values.abbr = name; if (!locales[name]) { locales[name] = new Locale(); } locales[name].set(values); // backwards compat for now: also set the locale moment.locale(name); return locales[name]; } else { // useful for testing delete locales[name]; return null; } }; moment.langData = deprecate( "moment.langData is deprecated. Use moment.localeData instead.", function (key) { return moment.localeData(key); } ); // returns locale data moment.localeData = function (key) { var locale; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return moment._locale; } if (!isArray(key)) { //short-circuit everything else locale = loadLocale(key); if (locale) { return locale; } key = [key]; } return chooseLocale(key); }; // compare moment object moment.isMoment = function (obj) { return obj instanceof Moment || (obj != null && obj.hasOwnProperty('_isAMomentObject')); }; // for typechecking Duration objects moment.isDuration = function (obj) { return obj instanceof Duration; }; for (i = lists.length - 1; i >= 0; --i) { makeList(lists[i]); } moment.normalizeUnits = function (units) { return normalizeUnits(units); }; moment.invalid = function (flags) { var m = moment.utc(NaN); if (flags != null) { extend(m._pf, flags); } else { m._pf.userInvalidated = true; } return m; }; moment.parseZone = function () { return moment.apply(null, arguments).parseZone(); }; moment.parseTwoDigitYear = function (input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; /************************************ Moment Prototype ************************************/ extend(moment.fn = Moment.prototype, { clone : function () { return moment(this); }, valueOf : function () { return +this._d + ((this._offset || 0) * 60000); }, unix : function () { return Math.floor(+this / 1000); }, toString : function () { return this.clone().locale('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ"); }, toDate : function () { return this._offset ? new Date(+this) : this._d; }, toISOString : function () { var m = moment(this).utc(); if (0 < m.year() && m.year() <= 9999) { return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } else { return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } }, toArray : function () { var m = this; return [ m.year(), m.month(), m.date(), m.hours(), m.minutes(), m.seconds(), m.milliseconds() ]; }, isValid : function () { return isValid(this); }, isDSTShifted : function () { if (this._a) { return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0; } return false; }, parsingFlags : function () { return extend({}, this._pf); }, invalidAt: function () { return this._pf.overflow; }, utc : function (keepLocalTime) { return this.zone(0, keepLocalTime); }, local : function (keepLocalTime) { if (this._isUTC) { this.zone(0, keepLocalTime); this._isUTC = false; if (keepLocalTime) { this.add(this._d.getTimezoneOffset(), 'm'); } } return this; }, format : function (inputString) { var output = formatMoment(this, inputString || moment.defaultFormat); return this.localeData().postformat(output); }, add : createAdder(1, 'add'), subtract : createAdder(-1, 'subtract'), diff : function (input, units, asFloat) { var that = makeAs(input, this), zoneDiff = (this.zone() - that.zone()) * 6e4, diff, output; units = normalizeUnits(units); if (units === 'year' || units === 'month') { // average number of days in the months in the given dates diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2 // difference in months output = ((this.year() - that.year()) * 12) + (this.month() - that.month()); // adjust by taking difference in days, average number of days // and dst in the given months. output += ((this - moment(this).startOf('month')) - (that - moment(that).startOf('month'))) / diff; // same as above but with zones, to negate all dst output -= ((this.zone() - moment(this).startOf('month').zone()) - (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff; if (units === 'year') { output = output / 12; } } else { diff = (this - that); output = units === 'second' ? diff / 1e3 : // 1000 units === 'minute' ? diff / 6e4 : // 1000 * 60 units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60 units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst diff; } return asFloat ? output : absRound(output); }, from : function (time, withoutSuffix) { return moment.duration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); }, fromNow : function (withoutSuffix) { return this.from(moment(), withoutSuffix); }, calendar : function (time) { // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're zone'd or not. var now = time || moment(), sod = makeAs(now, this).startOf('day'), diff = this.diff(sod, 'days', true), format = diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; return this.format(this.localeData().calendar(format, this)); }, isLeapYear : function () { return isLeapYear(this.year()); }, isDST : function () { return (this.zone() < this.clone().month(0).zone() || this.zone() < this.clone().month(5).zone()); }, day : function (input) { var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, 'd'); } else { return day; } }, month : makeAccessor('Month', true), startOf : function (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'quarter': case 'month': this.date(1); /* falls through */ case 'week': case 'isoWeek': case 'day': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); /* falls through */ } // weeks are a special case if (units === 'week') { this.weekday(0); } else if (units === 'isoWeek') { this.isoWeekday(1); } // quarters are also special if (units === 'quarter') { this.month(Math.floor(this.month() / 3) * 3); } return this; }, endOf: function (units) { units = normalizeUnits(units); return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); }, isAfter: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) > +moment(input).startOf(units); }, isBefore: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) < +moment(input).startOf(units); }, isSame: function (input, units) { units = units || 'ms'; return +this.clone().startOf(units) === +makeAs(input, this).startOf(units); }, min: deprecate( 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548', function (other) { other = moment.apply(null, arguments); return other < this ? this : other; } ), max: deprecate( 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548', function (other) { other = moment.apply(null, arguments); return other > this ? this : other; } ), // keepLocalTime = true means only change the timezone, without // affecting the local hour. So 5:31:26 +0300 --[zone(2, true)]--> // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist int zone // +0200, so we adjust the time as needed, to be valid. // // Keeping the time actually adds/subtracts (one hour) // from the actual represented time. That is why we call updateOffset // a second time. In case it wants us to change the offset again // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. zone : function (input, keepLocalTime) { var offset = this._offset || 0, localAdjust; if (input != null) { if (typeof input === 'string') { input = timezoneMinutesFromString(input); } if (Math.abs(input) < 16) { input = input * 60; } if (!this._isUTC && keepLocalTime) { localAdjust = this._d.getTimezoneOffset(); } this._offset = input; this._isUTC = true; if (localAdjust != null) { this.subtract(localAdjust, 'm'); } if (offset !== input) { if (!keepLocalTime || this._changeInProgress) { addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, false); } else if (!this._changeInProgress) { this._changeInProgress = true; moment.updateOffset(this, true); this._changeInProgress = null; } } } else { return this._isUTC ? offset : this._d.getTimezoneOffset(); } return this; }, zoneAbbr : function () { return this._isUTC ? 'UTC' : ''; }, zoneName : function () { return this._isUTC ? 'Coordinated Universal Time' : ''; }, parseZone : function () { if (this._tzm) { this.zone(this._tzm); } else if (typeof this._i === 'string') { this.zone(this._i); } return this; }, hasAlignedHourOffset : function (input) { if (!input) { input = 0; } else { input = moment(input).zone(); } return (this.zone() - input) % 60 === 0; }, daysInMonth : function () { return daysInMonth(this.year(), this.month()); }, dayOfYear : function (input) { var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); }, quarter : function (input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); }, weekYear : function (input) { var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year; return input == null ? year : this.add((input - year), 'y'); }, isoWeekYear : function (input) { var year = weekOfYear(this, 1, 4).year; return input == null ? year : this.add((input - year), 'y'); }, week : function (input) { var week = this.localeData().week(this); return input == null ? week : this.add((input - week) * 7, 'd'); }, isoWeek : function (input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add((input - week) * 7, 'd'); }, weekday : function (input) { var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, 'd'); }, isoWeekday : function (input) { // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); }, isoWeeksInYear : function () { return weeksInYear(this.year(), 1, 4); }, weeksInYear : function () { var weekInfo = this.localeData()._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); }, get : function (units) { units = normalizeUnits(units); return this[units](); }, set : function (units, value) { units = normalizeUnits(units); if (typeof this[units] === 'function') { this[units](value); } return this; }, // If passed a locale key, it will set the locale for this // instance. Otherwise, it will return the locale configuration // variables for this instance. locale : function (key) { if (key === undefined) { return this._locale._abbr; } else { this._locale = moment.localeData(key); return this; } }, lang : deprecate( "moment().lang() is deprecated. Use moment().localeData() instead.", function (key) { if (key === undefined) { return this.localeData(); } else { this._locale = moment.localeData(key); return this; } } ), localeData : function () { return this._locale; } }); function rawMonthSetter(mom, value) { var dayOfMonth; // TODO: Move this out of here! if (typeof value === 'string') { value = mom.localeData().monthsParse(value); // TODO: Another silent failure? if (typeof value !== 'number') { return mom; } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); return mom; } function rawGetter(mom, unit) { return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit](); } function rawSetter(mom, unit, value) { if (unit === 'Month') { return rawMonthSetter(mom, value); } else { return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); } } function makeAccessor(unit, keepTime) { return function (value) { if (value != null) { rawSetter(this, unit, value); moment.updateOffset(this, keepTime); return this; } else { return rawGetter(this, unit); } }; } moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false); moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false); moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false); // Setting the hour should keep the time, because the user explicitly // specified which hour he wants. So trying to maintain the same hour (in // a new timezone) makes sense. Adding/subtracting hours does not follow // this rule. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true); // moment.fn.month is defined separately moment.fn.date = makeAccessor('Date', true); moment.fn.dates = deprecate('dates accessor is deprecated. Use date instead.', makeAccessor('Date', true)); moment.fn.year = makeAccessor('FullYear', true); moment.fn.years = deprecate('years accessor is deprecated. Use year instead.', makeAccessor('FullYear', true)); // add plural methods moment.fn.days = moment.fn.day; moment.fn.months = moment.fn.month; moment.fn.weeks = moment.fn.week; moment.fn.isoWeeks = moment.fn.isoWeek; moment.fn.quarters = moment.fn.quarter; // add aliased format methods moment.fn.toJSON = moment.fn.toISOString; /************************************ Duration Prototype ************************************/ function daysToYears (days) { // 400 years have 146097 days (taking into account leap year rules) return days * 400 / 146097; } function yearsToDays (years) { // years * 365 + absRound(years / 4) - // absRound(years / 100) + absRound(years / 400); return years * 146097 / 400; } extend(moment.duration.fn = Duration.prototype, { _bubble : function () { var milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data, seconds, minutes, hours, years = 0; // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absRound(milliseconds / 1000); data.seconds = seconds % 60; minutes = absRound(seconds / 60); data.minutes = minutes % 60; hours = absRound(minutes / 60); data.hours = hours % 24; days += absRound(hours / 24); // Accurately convert days to years, assume start from year 0. years = absRound(daysToYears(days)); days -= absRound(yearsToDays(years)); // 30 days to a month // TODO (iskren): Use anchor date (like 1st Jan) to compute this. months += absRound(days / 30); days %= 30; // 12 months -> 1 year years += absRound(months / 12); months %= 12; data.days = days; data.months = months; data.years = years; }, abs : function () { this._milliseconds = Math.abs(this._milliseconds); this._days = Math.abs(this._days); this._months = Math.abs(this._months); this._data.milliseconds = Math.abs(this._data.milliseconds); this._data.seconds = Math.abs(this._data.seconds); this._data.minutes = Math.abs(this._data.minutes); this._data.hours = Math.abs(this._data.hours); this._data.months = Math.abs(this._data.months); this._data.years = Math.abs(this._data.years); return this; }, weeks : function () { return absRound(this.days() / 7); }, valueOf : function () { return this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6; }, humanize : function (withSuffix) { var output = relativeTime(this, !withSuffix, this.localeData()); if (withSuffix) { output = this.localeData().pastFuture(+this, output); } return this.localeData().postformat(output); }, add : function (input, val) { // supports only 2.0-style add(1, 's') or add(moment) var dur = moment.duration(input, val); this._milliseconds += dur._milliseconds; this._days += dur._days; this._months += dur._months; this._bubble(); return this; }, subtract : function (input, val) { var dur = moment.duration(input, val); this._milliseconds -= dur._milliseconds; this._days -= dur._days; this._months -= dur._months; this._bubble(); return this; }, get : function (units) { units = normalizeUnits(units); return this[units.toLowerCase() + 's'](); }, as : function (units) { var days, months; units = normalizeUnits(units); days = this._days + this._milliseconds / 864e5; if (units === 'month' || units === 'year') { months = this._months + daysToYears(days) * 12; return units === 'month' ? months : months / 12; } else { days += yearsToDays(this._months / 12); switch (units) { case 'week': return days / 7; case 'day': return days; case 'hour': return days * 24; case 'minute': return days * 24 * 60; case 'second': return days * 24 * 60 * 60; case 'millisecond': return days * 24 * 60 * 60 * 1000; default: throw new Error('Unknown unit ' + units); } } }, lang : moment.fn.lang, locale : moment.fn.locale, toIsoString : deprecate( "toIsoString() is deprecated. Please use toISOString() instead " + "(notice the capitals)", function () { return this.toISOString(); } ), toISOString : function () { // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var years = Math.abs(this.years()), months = Math.abs(this.months()), days = Math.abs(this.days()), hours = Math.abs(this.hours()), minutes = Math.abs(this.minutes()), seconds = Math.abs(this.seconds() + this.milliseconds() / 1000); if (!this.asSeconds()) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } return (this.asSeconds() < 0 ? '-' : '') + 'P' + (years ? years + 'Y' : '') + (months ? months + 'M' : '') + (days ? days + 'D' : '') + ((hours || minutes || seconds) ? 'T' : '') + (hours ? hours + 'H' : '') + (minutes ? minutes + 'M' : '') + (seconds ? seconds + 'S' : ''); }, localeData : function () { return this._locale; } }); function makeDurationGetter(name) { moment.duration.fn[name] = function () { return this._data[name]; }; } for (i in unitMillisecondFactors) { if (unitMillisecondFactors.hasOwnProperty(i)) { makeDurationGetter(i.toLowerCase()); } } moment.duration.fn.asMilliseconds = function () { return this.as('ms'); }; moment.duration.fn.asSeconds = function () { return this.as('s'); }; moment.duration.fn.asMinutes = function () { return this.as('m'); }; moment.duration.fn.asHours = function () { return this.as('h'); }; moment.duration.fn.asDays = function () { return this.as('d'); }; moment.duration.fn.asWeeks = function () { return this.as('weeks'); }; moment.duration.fn.asMonths = function () { return this.as('M'); }; moment.duration.fn.asYears = function () { return this.as('y'); }; /************************************ Default Locale ************************************/ // Set default locale, other locale will inherit from English. moment.locale('en', { ordinal : function (number) { var b = number % 10, output = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); /* EMBED_LOCALES */ /************************************ Exposing Moment ************************************/ function makeGlobal(shouldDeprecate) { /*global ender:false */ if (typeof ender !== 'undefined') { return; } oldGlobalMoment = globalScope.moment; if (shouldDeprecate) { globalScope.moment = deprecate( 'Accessing Moment through the global scope is ' + 'deprecated, and will be removed in an upcoming ' + 'release.', moment); } else { globalScope.moment = moment; } } // CommonJS module is defined if (hasModule) { module.exports = moment; } else if (typeof define === 'function' && define.amd) { define('moment', function (require, exports, module) { if (module.config && module.config() && module.config().noGlobal === true) { // release the global variable globalScope.moment = oldGlobalMoment; } return moment; }); makeGlobal(true); } else { makeGlobal(); } }).call(this); }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],5:[function(require,module,exports){ /** * Copyright 2012 Craig Campbell * * 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. * * Mousetrap is a simple keyboard shortcut library for Javascript with * no external dependencies * * @version 1.1.2 * @url craig.is/killing/mice */ /** * mapping of special keycodes to their corresponding keys * * everything in this dictionary cannot use keypress events * so it has to be here to map to the correct keycodes for * keyup/keydown events * * @type {Object} */ var _MAP = { 8: 'backspace', 9: 'tab', 13: 'enter', 16: 'shift', 17: 'ctrl', 18: 'alt', 20: 'capslock', 27: 'esc', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 45: 'ins', 46: 'del', 91: 'meta', 93: 'meta', 224: 'meta' }, /** * mapping for special characters so they can support * * this dictionary is only used incase you want to bind a * keyup or keydown event to one of these keys * * @type {Object} */ _KEYCODE_MAP = { 106: '*', 107: '+', 109: '-', 110: '.', 111 : '/', 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\', 221: ']', 222: '\'' }, /** * this is a mapping of keys that require shift on a US keypad * back to the non shift equivelents * * this is so you can use keyup events with these keys * * note that this will only work reliably on US keyboards * * @type {Object} */ _SHIFT_MAP = { '~': '`', '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', '_': '-', '+': '=', ':': ';', '\"': '\'', '<': ',', '>': '.', '?': '/', '|': '\\' }, /** * this is a list of special strings you can use to map * to modifier keys when you specify your keyboard shortcuts * * @type {Object} */ _SPECIAL_ALIASES = { 'option': 'alt', 'command': 'meta', 'return': 'enter', 'escape': 'esc' }, /** * variable to store the flipped version of _MAP from above * needed to check if we should use keypress or not when no action * is specified * * @type {Object|undefined} */ _REVERSE_MAP, /** * a list of all the callbacks setup via Mousetrap.bind() * * @type {Object} */ _callbacks = {}, /** * direct map of string combinations to callbacks used for trigger() * * @type {Object} */ _direct_map = {}, /** * keeps track of what level each sequence is at since multiple * sequences can start out with the same sequence * * @type {Object} */ _sequence_levels = {}, /** * variable to store the setTimeout call * * @type {null|number} */ _reset_timer, /** * temporary state where we will ignore the next keyup * * @type {boolean|string} */ _ignore_next_keyup = false, /** * are we currently inside of a sequence? * type of action ("keyup" or "keydown" or "keypress") or false * * @type {boolean|string} */ _inside_sequence = false; /** * loop through the f keys, f1 to f19 and add them to the map * programatically */ for (var i = 1; i < 20; ++i) { _MAP[111 + i] = 'f' + i; } /** * loop through to map numbers on the numeric keypad */ for (i = 0; i <= 9; ++i) { _MAP[i + 96] = i; } /** * cross browser add event method * * @param {Element|HTMLDocument} object * @param {string} type * @param {Function} callback * @returns void */ function _addEvent(object, type, callback) { if (object.addEventListener) { return object.addEventListener(type, callback, false); } object.attachEvent('on' + type, callback); } /** * takes the event and returns the key character * * @param {Event} e * @return {string} */ function _characterFromEvent(e) { // for keypress events we should return the character as is if (e.type == 'keypress') { return String.fromCharCode(e.which); } // for non keypress events the special maps are needed if (_MAP[e.which]) { return _MAP[e.which]; } if (_KEYCODE_MAP[e.which]) { return _KEYCODE_MAP[e.which]; } // if it is not in the special map return String.fromCharCode(e.which).toLowerCase(); } /** * should we stop this event before firing off callbacks * * @param {Event} e * @return {boolean} */ function _stop(e) { var element = e.target || e.srcElement, tag_name = element.tagName; // if the element has the class "mousetrap" then no need to stop if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) { return false; } // stop for input, select, and textarea return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true'); } /** * checks if two arrays are equal * * @param {Array} modifiers1 * @param {Array} modifiers2 * @returns {boolean} */ function _modifiersMatch(modifiers1, modifiers2) { return modifiers1.sort().join(',') === modifiers2.sort().join(','); } /** * resets all sequence counters except for the ones passed in * * @param {Object} do_not_reset * @returns void */ function _resetSequences(do_not_reset) { do_not_reset = do_not_reset || {}; var active_sequences = false, key; for (key in _sequence_levels) { if (do_not_reset[key]) { active_sequences = true; continue; } _sequence_levels[key] = 0; } if (!active_sequences) { _inside_sequence = false; } } /** * finds all callbacks that match based on the keycode, modifiers, * and action * * @param {string} character * @param {Array} modifiers * @param {string} action * @param {boolean=} remove - should we remove any matches * @param {string=} combination * @returns {Array} */ function _getMatches(character, modifiers, action, remove, combination) { var i, callback, matches = []; // if there are no events related to this keycode if (!_callbacks[character]) { return []; } // if a modifier key is coming up on its own we should allow it if (action == 'keyup' && _isModifier(character)) { modifiers = [character]; } // loop through all callbacks for the key that was pressed // and see if any of them match for (i = 0; i < _callbacks[character].length; ++i) { callback = _callbacks[character][i]; // if this is a sequence but it is not at the right level // then move onto the next match if (callback.seq && _sequence_levels[callback.seq] != callback.level) { continue; } // if the action we are looking for doesn't match the action we got // then we should keep going if (action != callback.action) { continue; } // if this is a keypress event that means that we need to only // look at the character, otherwise check the modifiers as // well if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) { // remove is used so if you change your mind and call bind a // second time with a new function the first one is overwritten if (remove && callback.combo == combination) { _callbacks[character].splice(i, 1); } matches.push(callback); } } return matches; } /** * takes a key event and figures out what the modifiers are * * @param {Event} e * @returns {Array} */ function _eventModifiers(e) { var modifiers = []; if (e.shiftKey) { modifiers.push('shift'); } if (e.altKey) { modifiers.push('alt'); } if (e.ctrlKey) { modifiers.push('ctrl'); } if (e.metaKey) { modifiers.push('meta'); } return modifiers; } /** * actually calls the callback function * * if your callback function returns false this will use the jquery * convention - prevent default and stop propogation on the event * * @param {Function} callback * @param {Event} e * @returns void */ function _fireCallback(callback, e) { if (callback(e) === false) { if (e.preventDefault) { e.preventDefault(); } if (e.stopPropagation) { e.stopPropagation(); } e.returnValue = false; e.cancelBubble = true; } } /** * handles a character key event * * @param {string} character * @param {Event} e * @returns void */ function _handleCharacter(character, e) { // if this event should not happen stop here if (_stop(e)) { return; } var callbacks = _getMatches(character, _eventModifiers(e), e.type), i, do_not_reset = {}, processed_sequence_callback = false; // loop through matching callbacks for this key event for (i = 0; i < callbacks.length; ++i) { // fire for all sequence callbacks // this is because if for example you have multiple sequences // bound such as "g i" and "g t" they both need to fire the // callback for matching g cause otherwise you can only ever // match the first one if (callbacks[i].seq) { processed_sequence_callback = true; // keep a list of which sequences were matches for later do_not_reset[callbacks[i].seq] = 1; _fireCallback(callbacks[i].callback, e); continue; } // if there were no sequence matches but we are still here // that means this is a regular match so we should fire that if (!processed_sequence_callback && !_inside_sequence) { _fireCallback(callbacks[i].callback, e); } } // if you are inside of a sequence and the key you are pressing // is not a modifier key then we should reset all sequences // that were not matched by this key event if (e.type == _inside_sequence && !_isModifier(character)) { _resetSequences(do_not_reset); } } /** * handles a keydown event * * @param {Event} e * @returns void */ function _handleKey(e) { // normalize e.which for key events // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion e.which = typeof e.which == "number" ? e.which : e.keyCode; var character = _characterFromEvent(e); // no character found then stop if (!character) { return; } if (e.type == 'keyup' && _ignore_next_keyup == character) { _ignore_next_keyup = false; return; } _handleCharacter(character, e); } /** * determines if the keycode specified is a modifier key or not * * @param {string} key * @returns {boolean} */ function _isModifier(key) { return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta'; } /** * called to set a 1 second timeout on the specified sequence * * this is so after each key press in the sequence you have 1 second * to press the next key before you have to start over * * @returns void */ function _resetSequenceTimer() { clearTimeout(_reset_timer); _reset_timer = setTimeout(_resetSequences, 1000); } /** * reverses the map lookup so that we can look for specific keys * to see what can and can't use keypress * * @return {Object} */ function _getReverseMap() { if (!_REVERSE_MAP) { _REVERSE_MAP = {}; for (var key in _MAP) { // pull out the numeric keypad from here cause keypress should // be able to detect the keys from the character if (key > 95 && key < 112) { continue; } if (_MAP.hasOwnProperty(key)) { _REVERSE_MAP[_MAP[key]] = key; } } } return _REVERSE_MAP; } /** * picks the best action based on the key combination * * @param {string} key - character for key * @param {Array} modifiers * @param {string=} action passed in */ function _pickBestAction(key, modifiers, action) { // if no action was picked in we should try to pick the one // that we think would work best for this key if (!action) { action = _getReverseMap()[key] ? 'keydown' : 'keypress'; } // modifier keys don't work as expected with keypress, // switch to keydown if (action == 'keypress' && modifiers.length) { action = 'keydown'; } return action; } /** * binds a key sequence to an event * * @param {string} combo - combo specified in bind call * @param {Array} keys * @param {Function} callback * @param {string=} action * @returns void */ function _bindSequence(combo, keys, callback, action) { // start off by adding a sequence level record for this combination // and setting the level to 0 _sequence_levels[combo] = 0; // if there is no action pick the best one for the first key // in the sequence if (!action) { action = _pickBestAction(keys[0], []); } /** * callback to increase the sequence level for this sequence and reset * all other sequences that were active * * @param {Event} e * @returns void */ var _increaseSequence = function(e) { _inside_sequence = action; ++_sequence_levels[combo]; _resetSequenceTimer(); }, /** * wraps the specified callback inside of another function in order * to reset all sequence counters as soon as this sequence is done * * @param {Event} e * @returns void */ _callbackAndReset = function(e) { _fireCallback(callback, e); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { _ignore_next_keyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences, 10); }, i; // loop through keys one at a time and bind the appropriate callback // function. for any key leading up to the final one it should // increase the sequence. after the final, it should reset all sequences for (i = 0; i < keys.length; ++i) { _bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i); } } /** * binds a single keyboard combination * * @param {string} combination * @param {Function} callback * @param {string=} action * @param {string=} sequence_name - name of sequence if part of sequence * @param {number=} level - what part of the sequence the command is * @returns void */ function _bindSingle(combination, callback, action, sequence_name, level) { // make sure multiple spaces in a row become a single space combination = combination.replace(/\s+/g, ' '); var sequence = combination.split(' '), i, key, keys, modifiers = []; // if this pattern is a sequence of keys then run through this method // to reprocess each pattern one key at a time if (sequence.length > 1) { return _bindSequence(combination, sequence, callback, action); } // take the keys from this pattern and figure out what the actual // pattern is all about keys = combination === '+' ? ['+'] : combination.split('+'); for (i = 0; i < keys.length; ++i) { key = keys[i]; // normalize key names if (_SPECIAL_ALIASES[key]) { key = _SPECIAL_ALIASES[key]; } // if this is not a keypress event then we should // be smart about using shift keys // this will only work for US keyboards however if (action && action != 'keypress' && _SHIFT_MAP[key]) { key = _SHIFT_MAP[key]; modifiers.push('shift'); } // if this key is a modifier then add it to the list of modifiers if (_isModifier(key)) { modifiers.push(key); } } // depending on what the key combination is // we will try to pick the best event for it action = _pickBestAction(key, modifiers, action); // make sure to initialize array if this is the first time // a callback is added for this key if (!_callbacks[key]) { _callbacks[key] = []; } // remove an existing match if there is one _getMatches(key, modifiers, action, !sequence_name, combination); // add this call back to the array // if it is a sequence put it at the beginning // if not put it at the end // // this is important because the way these are processed expects // the sequence ones to come first _callbacks[key][sequence_name ? 'unshift' : 'push']({ callback: callback, modifiers: modifiers, action: action, seq: sequence_name, level: level, combo: combination }); } /** * binds multiple combinations to the same callback * * @param {Array} combinations * @param {Function} callback * @param {string|undefined} action * @returns void */ function _bindMultiple(combinations, callback, action) { for (var i = 0; i < combinations.length; ++i) { _bindSingle(combinations[i], callback, action); } } // start! _addEvent(document, 'keypress', _handleKey); _addEvent(document, 'keydown', _handleKey); _addEvent(document, 'keyup', _handleKey); var mousetrap = { /** * binds an event to mousetrap * * can be a single key, a combination of keys separated with +, * a comma separated list of keys, an array of keys, or * a sequence of keys separated by spaces * * be sure to list the modifier keys first to make sure that the * correct key ends up getting bound (the last key in the pattern) * * @param {string|Array} keys * @param {Function} callback * @param {string=} action - 'keypress', 'keydown', or 'keyup' * @returns void */ bind: function(keys, callback, action) { _bindMultiple(keys instanceof Array ? keys : [keys], callback, action); _direct_map[keys + ':' + action] = callback; return this; }, /** * unbinds an event to mousetrap * * the unbinding sets the callback function of the specified key combo * to an empty function and deletes the corresponding key in the * _direct_map dict. * * the keycombo+action has to be exactly the same as * it was defined in the bind method * * TODO: actually remove this from the _callbacks dictionary instead * of binding an empty function * * @param {string|Array} keys * @param {string} action * @returns void */ unbind: function(keys, action) { if (_direct_map[keys + ':' + action]) { delete _direct_map[keys + ':' + action]; this.bind(keys, function() {}, action); } return this; }, /** * triggers an event that has already been bound * * @param {string} keys * @param {string=} action * @returns void */ trigger: function(keys, action) { _direct_map[keys + ':' + action](); return this; }, /** * resets the library back to its initial state. this is useful * if you want to clear out the current keyboard shortcuts and bind * new ones - for example if you switch to another page * * @returns void */ reset: function() { _callbacks = {}; _direct_map = {}; return this; } }; module.exports = mousetrap; },{}],6:[function(require,module,exports){ (function( factory ) { if (typeof define !== 'undefined' && define.amd) { define(['jquery'], factory); } else if (typeof module !== 'undefined' && module.exports) { var $ = require('jquery'); module.exports = factory( $ ); } else { window.scrollMonitor = factory( jQuery ); } })(function( $ ) { var exports = {}; var $window = $(window); var $document = $(document); var watchers = []; var VISIBILITYCHANGE = 'visibilityChange'; var ENTERVIEWPORT = 'enterViewport'; var FULLYENTERVIEWPORT = 'fullyEnterViewport'; var EXITVIEWPORT = 'exitViewport'; var PARTIALLYEXITVIEWPORT = 'partiallyExitViewport'; var LOCATIONCHANGE = 'locationChange'; var STATECHANGE = 'stateChange'; var eventTypes = [ VISIBILITYCHANGE, ENTERVIEWPORT, FULLYENTERVIEWPORT, EXITVIEWPORT, PARTIALLYEXITVIEWPORT, LOCATIONCHANGE, STATECHANGE ]; var defaultOffsets = {top: 0, bottom: 0}; exports.viewportTop; exports.viewportBottom; exports.documentHeight; exports.viewportHeight = windowHeight(); var previousDocumentHeight; var latestEvent; function windowHeight() { return window.innerHeight || document.documentElement.clientHeight; } var calculateViewportI; function calculateViewport() { exports.viewportTop = $window.scrollTop(); exports.viewportBottom = exports.viewportTop + exports.viewportHeight; exports.documentHeight = $document.height(); if (exports.documentHeight !== previousDocumentHeight) { calculateViewportI = watchers.length; while( calculateViewportI-- ) { watchers[calculateViewportI].recalculateLocation(); } previousDocumentHeight = exports.documentHeight; } } function recalculateWatchLocationsAndTrigger() { exports.viewportHeight = windowHeight(); calculateViewport(); updateAndTriggerWatchers(); } var recalculateAndTriggerTimer; function debouncedRecalcuateAndTrigger() { clearTimeout(recalculateAndTriggerTimer); recalculateAndTriggerTimer = setTimeout( recalculateWatchLocationsAndTrigger, 100 ); } var updateAndTriggerWatchersI; function updateAndTriggerWatchers() { // update all watchers then trigger the events so one can rely on another being up to date. updateAndTriggerWatchersI = watchers.length; while( updateAndTriggerWatchersI-- ) { watchers[updateAndTriggerWatchersI].update(); } updateAndTriggerWatchersI = watchers.length; while( updateAndTriggerWatchersI-- ) { watchers[updateAndTriggerWatchersI].triggerCallbacks(); } } function ElementWatcher( watchItem, offsets ) { var self = this; this.watchItem = watchItem; if (!offsets) { this.offsets = defaultOffsets; } else if (offsets === +offsets) { this.offsets = {top: offsets, bottom: offsets}; } else { this.offsets = $.extend({}, defaultOffsets, offsets); } this.callbacks = {}; // {callback: function, isOne: true } for (var i = 0, j = eventTypes.length; i < j; i++) { self.callbacks[eventTypes[i]] = []; } this.locked = false; var wasInViewport; var wasFullyInViewport; var wasAboveViewport; var wasBelowViewport; var listenerToTriggerListI; var listener; function triggerCallbackArray( listeners ) { if (listeners.length === 0) { return; } listenerToTriggerListI = listeners.length; while( listenerToTriggerListI-- ) { listener = listeners[listenerToTriggerListI]; listener.callback.call( self, latestEvent ); if (listener.isOne) { listeners.splice(listenerToTriggerListI, 1); } } } this.triggerCallbacks = function triggerCallbacks() { if (this.isInViewport && !wasInViewport) { triggerCallbackArray( this.callbacks[ENTERVIEWPORT] ); } if (this.isFullyInViewport && !wasFullyInViewport) { triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] ); } if (this.isAboveViewport !== wasAboveViewport && this.isBelowViewport !== wasBelowViewport) { triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] ); // if you skip completely past this element if (!wasFullyInViewport && !this.isFullyInViewport) { triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] ); triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] ); } if (!wasInViewport && !this.isInViewport) { triggerCallbackArray( this.callbacks[ENTERVIEWPORT] ); triggerCallbackArray( this.callbacks[EXITVIEWPORT] ); } } if (!this.isFullyInViewport && wasFullyInViewport) { triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] ); } if (!this.isInViewport && wasInViewport) { triggerCallbackArray( this.callbacks[EXITVIEWPORT] ); } if (this.isInViewport !== wasInViewport) { triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] ); } switch( true ) { case wasInViewport !== this.isInViewport: case wasFullyInViewport !== this.isFullyInViewport: case wasAboveViewport !== this.isAboveViewport: case wasBelowViewport !== this.isBelowViewport: triggerCallbackArray( this.callbacks[STATECHANGE] ); } wasInViewport = this.isInViewport; wasFullyInViewport = this.isFullyInViewport; wasAboveViewport = this.isAboveViewport; wasBelowViewport = this.isBelowViewport; }; this.recalculateLocation = function() { if (this.locked) { return; } var previousTop = this.top; var previousBottom = this.bottom; if (this.watchItem.nodeName) { // a dom element var cachedDisplay = this.watchItem.style.display; if (cachedDisplay === 'none') { this.watchItem.style.display = ''; } var elementLocation = $(this.watchItem).offset(); this.top = elementLocation.top; this.bottom = elementLocation.top + this.watchItem.offsetHeight; if (cachedDisplay === 'none') { this.watchItem.style.display = cachedDisplay; } } else if (this.watchItem === +this.watchItem) { // number if (this.watchItem > 0) { this.top = this.bottom = this.watchItem; } else { this.top = this.bottom = exports.documentHeight - this.watchItem; } } else { // an object with a top and bottom property this.top = this.watchItem.top; this.bottom = this.watchItem.bottom; } this.top -= this.offsets.top; this.bottom += this.offsets.bottom; this.height = this.bottom - this.top; if ( (previousTop !== undefined || previousBottom !== undefined) && (this.top !== previousTop || this.bottom !== previousBottom) ) { triggerCallbackArray( this.callbacks[LOCATIONCHANGE] ); } }; this.recalculateLocation(); this.update(); wasInViewport = this.isInViewport; wasFullyInViewport = this.isFullyInViewport; wasAboveViewport = this.isAboveViewport; wasBelowViewport = this.isBelowViewport; } ElementWatcher.prototype = { on: function( event, callback, isOne ) { // trigger the event if it applies to the element right now. switch( true ) { case event === VISIBILITYCHANGE && !this.isInViewport && this.isAboveViewport: case event === ENTERVIEWPORT && this.isInViewport: case event === FULLYENTERVIEWPORT && this.isFullyInViewport: case event === EXITVIEWPORT && this.isAboveViewport && !this.isInViewport: case event === PARTIALLYEXITVIEWPORT && this.isAboveViewport: callback(); if (isOne) { return; } } if (this.callbacks[event]) { this.callbacks[event].push({callback: callback, isOne: isOne}); } else { throw new Error('Tried to add a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', ')); } }, off: function( event, callback ) { if (this.callbacks[event]) { for (var i = 0, item; item = this.callbacks[event][i]; i++) { if (item.callback === callback) { this.callbacks[event].splice(i, 1); break; } } } else { throw new Error('Tried to remove a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', ')); } }, one: function( event, callback ) { this.on( event, callback, true); }, recalculateSize: function() { this.height = this.watchItem.offsetHeight + this.offsets.top + this.offsets.bottom; this.bottom = this.top + this.height; }, update: function() { this.isAboveViewport = this.top < exports.viewportTop; this.isBelowViewport = this.bottom > exports.viewportBottom; this.isInViewport = (this.top <= exports.viewportBottom && this.bottom >= exports.viewportTop); this.isFullyInViewport = (this.top >= exports.viewportTop && this.bottom <= exports.viewportBottom) || (this.isAboveViewport && this.isBelowViewport); }, destroy: function() { var index = watchers.indexOf(this), self = this; watchers.splice(index, 1); for (var i = 0, j = eventTypes.length; i < j; i++) { self.callbacks[eventTypes[i]].length = 0; } }, // prevent recalculating the element location lock: function() { this.locked = true; }, unlock: function() { this.locked = false; } }; var eventHandlerFactory = function (type) { return function( callback, isOne ) { this.on.call(this, type, callback, isOne); }; }; for (var i = 0, j = eventTypes.length; i < j; i++) { var type = eventTypes[i]; ElementWatcher.prototype[type] = eventHandlerFactory(type); } try { calculateViewport(); } catch (e) { $(calculateViewport); } function scrollMonitorListener(event) { latestEvent = event; calculateViewport(); updateAndTriggerWatchers(); } $window.on('scroll', scrollMonitorListener); $window.on('resize', debouncedRecalcuateAndTrigger); exports.beget = exports.create = function( element, offsets ) { if (typeof element === 'string') { element = $(element)[0]; } if (element instanceof $) { element = element[0]; } var watcher = new ElementWatcher( element, offsets ); watchers.push(watcher); watcher.update(); return watcher; }; exports.update = function() { latestEvent = null; calculateViewport(); updateAndTriggerWatchers(); }; exports.recalculateLocations = function() { exports.documentHeight = 0; exports.update(); }; return exports; }); },{"jquery":3}],7:[function(require,module,exports){ // Underscore.js 1.7.0 // http://underscorejs.org // (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `exports` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, concat = ArrayProto.concat, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.7.0'; // Internal function that returns an efficient (for current engines) version // of the passed-in callback, to be repeatedly applied in other Underscore // functions. var createCallback = function(func, context, argCount) { if (context === void 0) return func; switch (argCount == null ? 3 : argCount) { case 1: return function(value) { return func.call(context, value); }; case 2: return function(value, other) { return func.call(context, value, other); }; case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; }; // A mostly-internal function to generate callbacks that can be applied // to each element in a collection, returning the desired result — either // identity, an arbitrary callback, a property matcher, or a property accessor. _.iteratee = function(value, context, argCount) { if (value == null) return _.identity; if (_.isFunction(value)) return createCallback(value, context, argCount); if (_.isObject(value)) return _.matches(value); return _.property(value); }; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles raw objects in addition to array-likes. Treats all // sparse array-likes as if they were dense. _.each = _.forEach = function(obj, iteratee, context) { if (obj == null) return obj; iteratee = createCallback(iteratee, context); var i, length = obj.length; if (length === +length) { for (i = 0; i < length; i++) { iteratee(obj[i], i, obj); } } else { var keys = _.keys(obj); for (i = 0, length = keys.length; i < length; i++) { iteratee(obj[keys[i]], keys[i], obj); } } return obj; }; // Return the results of applying the iteratee to each element. _.map = _.collect = function(obj, iteratee, context) { if (obj == null) return []; iteratee = _.iteratee(iteratee, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, results = Array(length), currentKey; for (var index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; results[index] = iteratee(obj[currentKey], currentKey, obj); } return results; }; var reduceError = 'Reduce of empty array with no initial value'; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. _.reduce = _.foldl = _.inject = function(obj, iteratee, memo, context) { if (obj == null) obj = []; iteratee = createCallback(iteratee, context, 4); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index = 0, currentKey; if (arguments.length < 3) { if (!length) throw new TypeError(reduceError); memo = obj[keys ? keys[index++] : index++]; } for (; index < length; index++) { currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; // The right-associative version of reduce, also known as `foldr`. _.reduceRight = _.foldr = function(obj, iteratee, memo, context) { if (obj == null) obj = []; iteratee = createCallback(iteratee, context, 4); var keys = obj.length !== + obj.length && _.keys(obj), index = (keys || obj).length, currentKey; if (arguments.length < 3) { if (!index) throw new TypeError(reduceError); memo = obj[keys ? keys[--index] : --index]; } while (index--) { currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, predicate, context) { var result; predicate = _.iteratee(predicate, context); _.some(obj, function(value, index, list) { if (predicate(value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Aliased as `select`. _.filter = _.select = function(obj, predicate, context) { var results = []; if (obj == null) return results; predicate = _.iteratee(predicate, context); _.each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, predicate, context) { return _.filter(obj, _.negate(_.iteratee(predicate)), context); }; // Determine whether all of the elements match a truth test. // Aliased as `all`. _.every = _.all = function(obj, predicate, context) { if (obj == null) return true; predicate = _.iteratee(predicate, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index, currentKey; for (index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; if (!predicate(obj[currentKey], currentKey, obj)) return false; } return true; }; // Determine if at least one element in the object matches a truth test. // Aliased as `any`. _.some = _.any = function(obj, predicate, context) { if (obj == null) return false; predicate = _.iteratee(predicate, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index, currentKey; for (index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; if (predicate(obj[currentKey], currentKey, obj)) return true; } return false; }; // Determine if the array or object contains a given value (using `===`). // Aliased as `include`. _.contains = _.include = function(obj, target) { if (obj == null) return false; if (obj.length !== +obj.length) obj = _.values(obj); return _.indexOf(obj, target) >= 0; }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); var isFunc = _.isFunction(method); return _.map(obj, function(value) { return (isFunc ? method : value[method]).apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs) { return _.filter(obj, _.matches(attrs)); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.find(obj, _.matches(attrs)); }; // Return the maximum element (or element-based computation). _.max = function(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; if (iteratee == null && obj != null) { obj = obj.length === +obj.length ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value > result) { result = value; } } } else { iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed > lastComputed || computed === -Infinity && result === -Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Return the minimum element (or element-based computation). _.min = function(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, value, computed; if (iteratee == null && obj != null) { obj = obj.length === +obj.length ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value < result) { result = value; } } } else { iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed < lastComputed || computed === Infinity && result === Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Shuffle a collection, using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). _.shuffle = function(obj) { var set = obj && obj.length === +obj.length ? obj : _.values(obj); var length = set.length; var shuffled = Array(length); for (var index = 0, rand; index < length; index++) { rand = _.random(0, index); if (rand !== index) shuffled[index] = shuffled[rand]; shuffled[rand] = set[index]; } return shuffled; }; // Sample **n** random values from a collection. // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. _.sample = function(obj, n, guard) { if (n == null || guard) { if (obj.length !== +obj.length) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } return _.shuffle(obj).slice(0, Math.max(0, n)); }; // Sort the object's values by a criterion produced by an iteratee. _.sortBy = function(obj, iteratee, context) { iteratee = _.iteratee(iteratee, context); return _.pluck(_.map(obj, function(value, index, list) { return { value: value, index: index, criteria: iteratee(value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(behavior) { return function(obj, iteratee, context) { var result = {}; iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index) { var key = iteratee(value, index, obj); behavior(result, value, key); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, value, key) { if (_.has(result, key)) result[key].push(value); else result[key] = [value]; }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, value, key) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, value, key) { if (_.has(result, key)) result[key]++; else result[key] = 1; }); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iteratee, context) { iteratee = _.iteratee(iteratee, context, 1); var value = iteratee(obj); var low = 0, high = array.length; while (low < high) { var mid = low + high >>> 1; if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; }; // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (obj.length === +obj.length) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return obj.length === +obj.length ? obj.length : _.keys(obj).length; }; // Split a collection into two arrays: one whose elements all satisfy the given // predicate, and one whose elements all do not satisfy the predicate. _.partition = function(obj, predicate, context) { predicate = _.iteratee(predicate, context); var pass = [], fail = []; _.each(obj, function(value, key, obj) { (predicate(value, key, obj) ? pass : fail).push(value); }); return [pass, fail]; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[0]; if (n < 0) return []; return slice.call(array, 0, n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. The **guard** check allows it to work with // `_.map`. _.initial = function(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[array.length - 1]; return slice.call(array, Math.max(array.length - n, 0)); }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, strict, output) { if (shallow && _.every(input, _.isArray)) { return concat.apply(output, input); } for (var i = 0, length = input.length; i < length; i++) { var value = input[i]; if (!_.isArray(value) && !_.isArguments(value)) { if (!strict) output.push(value); } else if (shallow) { push.apply(output, value); } else { flatten(value, shallow, strict, output); } } return output; }; // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, false, []); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iteratee, context) { if (array == null) return []; if (!_.isBoolean(isSorted)) { context = iteratee; iteratee = isSorted; isSorted = false; } if (iteratee != null) iteratee = _.iteratee(iteratee, context); var result = []; var seen = []; for (var i = 0, length = array.length; i < length; i++) { var value = array[i]; if (isSorted) { if (!i || seen !== value) result.push(value); seen = value; } else if (iteratee) { var computed = iteratee(value, i, array); if (_.indexOf(seen, computed) < 0) { seen.push(computed); result.push(value); } } else if (_.indexOf(result, value) < 0) { result.push(value); } } return result; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(flatten(arguments, true, true, [])); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { if (array == null) return []; var result = []; var argsLength = arguments.length; for (var i = 0, length = array.length; i < length; i++) { var item = array[i]; if (_.contains(result, item)) continue; for (var j = 1; j < argsLength; j++) { if (!_.contains(arguments[j], item)) break; } if (j === argsLength) result.push(item); } return result; }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = flatten(slice.call(arguments, 1), true, true, []); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function(array) { if (array == null) return []; var length = _.max(arguments, 'length').length; var results = Array(length); for (var i = 0; i < length; i++) { results[i] = _.pluck(arguments, i); } return results; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { if (list == null) return {}; var result = {}; for (var i = 0, length = list.length; i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // Return the position of the first occurrence of an item in an array, // or -1 if the item is not included in the array. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { if (array == null) return -1; var i = 0, length = array.length; if (isSorted) { if (typeof isSorted == 'number') { i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted; } else { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } } for (; i < length; i++) if (array[i] === item) return i; return -1; }; _.lastIndexOf = function(array, item, from) { if (array == null) return -1; var idx = array.length; if (typeof from == 'number') { idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1); } while (--idx >= 0) if (array[idx] === item) return idx; return -1; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = step || 1; var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; }; // Function (ahem) Functions // ------------------ // Reusable constructor function for prototype setting. var Ctor = function(){}; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = function(func, context) { var args, bound; if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); args = slice.call(arguments, 2); bound = function() { if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); Ctor.prototype = func.prototype; var self = new Ctor; Ctor.prototype = null; var result = func.apply(self, args.concat(slice.call(arguments))); if (_.isObject(result)) return result; return self; }; return bound; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _ acts // as a placeholder, allowing any combination of arguments to be pre-filled. _.partial = function(func) { var boundArgs = slice.call(arguments, 1); return function() { var position = 0; var args = boundArgs.slice(); for (var i = 0, length = args.length; i < length; i++) { if (args[i] === _) args[i] = arguments[position++]; } while (position < arguments.length) args.push(arguments[position++]); return func.apply(this, args); }; }; // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. _.bindAll = function(obj) { var i, length = arguments.length, key; if (length <= 1) throw new Error('bindAll must be passed function names'); for (i = 1; i < length; i++) { key = arguments[i]; obj[key] = _.bind(obj[key], obj); } return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memoize = function(key) { var cache = memoize.cache; var address = hasher ? hasher.apply(this, arguments) : key; if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); return cache[address]; }; memoize.cache = {}; return memoize; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _.throttle = function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : _.now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; return function() { var now = _.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = _.now() - timestamp; if (last < wait && last > 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) context = args = null; } } }; return function() { context = this; args = arguments; timestamp = _.now(); var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; // Returns a negated version of the passed-in predicate. _.negate = function(predicate) { return function() { return !predicate.apply(this, arguments); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var args = arguments; var start = args.length - 1; return function() { var i = start; var result = args[start].apply(this, arguments); while (i--) result = args[i].call(this, result); return result; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Returns a function that will only be executed before being called N times. _.before = function(times, func) { var memo; return function() { if (--times > 0) { memo = func.apply(this, arguments); } else { func = null; } return memo; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = _.partial(_.before, 2); // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = function(obj) { if (!_.isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = function(obj) { if (!_.isObject(obj)) return obj; var source, prop; for (var i = 1, length = arguments.length; i < length; i++) { source = arguments[i]; for (prop in source) { if (hasOwnProperty.call(source, prop)) { obj[prop] = source[prop]; } } } return obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(obj, iteratee, context) { var result = {}, key; if (obj == null) return result; if (_.isFunction(iteratee)) { iteratee = createCallback(iteratee, context); for (key in obj) { var value = obj[key]; if (iteratee(value, key, obj)) result[key] = value; } } else { var keys = concat.apply([], slice.call(arguments, 1)); obj = new Object(obj); for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; if (key in obj) result[key] = obj[key]; } } return result; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj, iteratee, context) { if (_.isFunction(iteratee)) { iteratee = _.negate(iteratee); } else { var keys = _.map(concat.apply([], slice.call(arguments, 1)), String); iteratee = function(value, key) { return !_.contains(keys, key); }; } return _.pick(obj, iteratee, context); }; // Fill in a given object with default properties. _.defaults = function(obj) { if (!_.isObject(obj)) return obj; for (var i = 1, length = arguments.length; i < length; i++) { var source = arguments[i]; for (var prop in source) { if (obj[prop] === void 0) obj[prop] = source[prop]; } } return obj; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a === 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className !== toString.call(b)) return false; switch (className) { // Strings, numbers, regular expressions, dates, and booleans are compared by value. case '[object RegExp]': // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return '' + a === '' + b; case '[object Number]': // `NaN`s are equivalent, but non-reflexive. // Object(NaN) is equivalent to NaN if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. return +a === 0 ? 1 / +a === 1 / b : +a === +b; case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a === +b; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] === a) return bStack[length] === b; } // Objects with different constructors are not equivalent, but `Object`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if ( aCtor !== bCtor && // Handle Object.create(x) cases 'constructor' in a && 'constructor' in b && !(_.isFunction(aCtor) && aCtor instanceof aCtor && _.isFunction(bCtor) && bCtor instanceof bCtor) ) { return false; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size, result; // Recursively compare objects and arrays. if (className === '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size === b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { if (!(result = eq(a[size], b[size], aStack, bStack))) break; } } } else { // Deep compare objects. var keys = _.keys(a), key; size = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. result = _.keys(b).length === size; if (result) { while (size--) { // Deep compare each member key = keys[size]; if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; } } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return result; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b, [], []); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (_.isArray(obj) || _.isString(obj) || _.isArguments(obj)) return obj.length === 0; for (var key in obj) if (_.has(obj, key)) return false; return true; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) === '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) === '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return _.has(obj, 'callee'); }; } // Optimize `isFunction` if appropriate. Work around an IE 11 bug. if (typeof /./ !== 'function') { _.isFunction = function(obj) { return typeof obj == 'function' || false; }; } // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj !== +obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return obj != null && hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iteratees. _.identity = function(value) { return value; }; _.constant = function(value) { return function() { return value; }; }; _.noop = function(){}; _.property = function(key) { return function(obj) { return obj[key]; }; }; // Returns a predicate for checking whether an object has a given set of `key:value` pairs. _.matches = function(attrs) { var pairs = _.pairs(attrs), length = pairs.length; return function(obj) { if (obj == null) return !length; obj = new Object(obj); for (var i = 0; i < length; i++) { var pair = pairs[i], key = pair[0]; if (pair[1] !== obj[key] || !(key in obj)) return false; } return true; }; }; // Run a function **n** times. _.times = function(n, iteratee, context) { var accum = Array(Math.max(0, n)); iteratee = createCallback(iteratee, context, 1); for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // A (possibly faster) way to get the current timestamp as an integer. _.now = Date.now || function() { return new Date().getTime(); }; // List of HTML entities for escaping. var escapeMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '`': '&#x60;' }; var unescapeMap = _.invert(escapeMap); // Functions for escaping and unescaping strings to/from HTML interpolation. var createEscaper = function(map) { var escaper = function(match) { return map[match]; }; // Regexes for identifying a key that needs to be escaped var source = '(?:' + _.keys(map).join('|') + ')'; var testRegexp = RegExp(source); var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; }; _.escape = createEscaper(escapeMap); _.unescape = createEscaper(unescapeMap); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, property) { if (object == null) return void 0; var value = object[property]; return _.isFunction(value) ? object[property]() : value; }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\u2028|\u2029/g; var escapeChar = function(match) { return '\\' + escapes[match]; }; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. // NB: `oldSettings` only exists for backwards compatibility. _.template = function(text, settings, oldSettings) { if (!settings && oldSettings) settings = oldSettings; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escaper, escapeChar); index = offset + match.length; if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } else if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } // Adobe VMs need the match returned to produce the correct offest. return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; try { var render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } var template = function(data) { return render.call(this, data, _); }; // Provide the compiled source as a convenience for precompilation. var argument = settings.variable || 'obj'; template.source = 'function(' + argument + '){\n' + source + '}'; return template; }; // Add a "chain" function. Start chaining a wrapped Underscore object. _.chain = function(obj) { var instance = _(obj); instance._chain = true; return instance; }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var result = function(obj) { return this._chain ? _(obj).chain() : obj; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { _.each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return result.call(this, func.apply(_, args)); }; }); }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; return result.call(this, obj); }; }); // Add all accessor Array functions to the wrapper. _.each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result.call(this, method.apply(this._wrapped, arguments)); }; }); // Extracts the result from a wrapped and chained object. _.prototype.value = function() { return this._wrapped; }; // AMD registration happens at the end for compatibility with AMD loaders // that may not enforce next-turn semantics on modules. Even though general // practice for AMD registration is to be anonymous, underscore registers // as a named module because, like jQuery, it is a base library that is // popular enough to be bundled in a third party lib, but not be part of // an AMD load request. Those cases could generate an error when an // anonymous define() is called outside of a loader request. if (typeof define === 'function' && define.amd) { define('underscore', [], function() { return _; }); } }.call(this)); },{}],"base_object":[function(require,module,exports){ module.exports=require('2HNVgz'); },{}],"2HNVgz":[function(require,module,exports){ "use strict"; var _ = require('underscore'); var extend = require('./utils').extend; var Events = require('./events'); var pluginOptions = ['container']; var BaseObject = function BaseObject(options) { this.uniqueId = _.uniqueId('o'); options || (options = {}); _.extend(this, _.pick(options, pluginOptions)); }; ($traceurRuntime.createClass)(BaseObject, {}, {}, Events); BaseObject.extend = extend; module.exports = BaseObject; },{"./events":12,"./utils":24,"underscore":7}],"core_plugin":[function(require,module,exports){ module.exports=require('it+usN'); },{}],"it+usN":[function(require,module,exports){ "use strict"; var BaseObject = require('./base_object'); var CorePlugin = function CorePlugin(core) { $traceurRuntime.superCall(this, $CorePlugin.prototype, "constructor", [core]); this.core = core; }; var $CorePlugin = CorePlugin; ($traceurRuntime.createClass)(CorePlugin, {getExternalInterface: function() { return {}; }}, {}, BaseObject); module.exports = CorePlugin; },{"./base_object":"2HNVgz"}],12:[function(require,module,exports){ (function (global){ "use strict"; var _ = require('underscore'); var Log = require('../plugins/log'); var slice = Array.prototype.slice; var Events = function Events() {}; ($traceurRuntime.createClass)(Events, { on: function(name, callback, context) { if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({ callback: callback, context: context, ctx: context || this }); return this; }, once: function(name, callback, context) { if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function() { self.off(name, once); callback.apply(this, arguments); }); once._callback = callback; return this.on(name, once, context); }, off: function(name, callback, context) { var retain, ev, events, names, i, l, j, k; if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; if (!name && !callback && !context) { this._events = void 0; return this; } names = name ? [name] : _.keys(this._events); for (i = 0, l = names.length; i < l; i++) { name = names[i]; events = this._events[name]; if (events) { this._events[name] = retain = []; if (callback || context) { for (j = 0, k = events.length; j < k; j++) { ev = events[j]; if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) { retain.push(ev); } } } if (!retain.length) delete this._events[name]; } } return this; }, trigger: function(name) { var klass = arguments[arguments.length - 1]; if (global.DEBUG) { if (Log.BLACKLIST.indexOf(name) < 0) Log.info(klass, 'event ' + name + ' triggered'); } if (!this._events) return this; var args = slice.call(arguments, 1); if (!eventsApi(this, 'trigger', name, args)) return this; var events = this._events[name]; var allEvents = this._events.all; if (events) triggerEvents(events, args); if (allEvents) triggerEvents(allEvents, arguments); return this; }, stopListening: function(obj, name, callback) { var listeningTo = this._listeningTo; if (!listeningTo) return this; var remove = !name && !callback; if (!callback && typeof name === 'object') callback = this; if (obj) (listeningTo = {})[obj._listenId] = obj; for (var id in listeningTo) { obj = listeningTo[id]; obj.off(name, callback, this); if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id]; } return this; } }, {}); var eventSplitter = /\s+/; var eventsApi = function(obj, action, name, rest) { if (!name) return true; if (typeof name === 'object') { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } return false; } if (eventSplitter.test(name)) { var names = name.split(eventSplitter); for (var i = 0, l = names.length; i < l; i++) { obj[action].apply(obj, [names[i]].concat(rest)); } return false; } return true; }; var triggerEvents = function(events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return; } }; var listenMethods = { listenTo: 'on', listenToOnce: 'once' }; _.each(listenMethods, function(implementation, method) { Events.prototype[method] = function(obj, name, callback) { var listeningTo = this._listeningTo || (this._listeningTo = {}); var id = obj._listenId || (obj._listenId = _.uniqueId('l')); listeningTo[id] = obj; if (!callback && typeof name === 'object') callback = this; obj[implementation](name, callback, this); return this; }; }); module.exports = Events; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../plugins/log":56,"underscore":7}],13:[function(require,module,exports){ "use strict"; var _ = require('underscore'); module.exports = { 'media_control': _.template('<div class="media-control-background" data-background></div><div class="media-control-layer" data-controls> <% var renderBar = function(name) { %> <div class="bar-container" data-<%= name %>> <div class="bar-background" data-<%= name %>> <div class="bar-fill-1" data-<%= name %>></div> <div class="bar-fill-2" data-<%= name %>></div> </div> <div class="bar-scrubber" data-<%= name %>> <div class="bar-scrubber-icon" data-<%= name %>></div> </div> </div> <% }; %> <% var renderDrawer = function(name, renderContent) { %> <div class="drawer-container" data-<%= name %>> <div class="drawer-icon-container" data-<%= name %>> <div class="drawer-icon media-control-icon" data-<%= name %>></div> <span class="drawer-text" data-<%= name %>></span> </div> <% renderContent(name); %> </div> <% }; %> <% var renderIndicator = function(name) { %> <div class="media-control-indicator" data-<%= name %>></div> <% }; %> <% var renderButton = function(name) { %> <button class="media-control-button media-control-icon" data-<%= name %>></button> <% }; %> <% var render = function(settings) { _.each(settings, function(setting) { if(setting === "seekbar") { renderBar(setting); } else if (setting === "volume") { renderDrawer(setting, renderBar); } else if (setting === "duration" || setting === "position") { renderIndicator(setting); } else { renderButton(setting); } }); }; %> <% if (settings.default && settings.default.length) { %> <div class="media-control-center-panel" data-media-control> <% render(settings.default); %> </div> <% } %> <% if (settings.left && settings.left.length) { %> <div class="media-control-left-panel" data-media-control> <% render(settings.left); %> </div> <% } %> <% if (settings.right && settings.right.length) { %> <div class="media-control-right-panel" data-media-control> <% render(settings.right); %> </div> <% } %></div>'), 'flash': _.template(' <param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="gpu"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> <embed type="application/x-shockwave-flash" disabled="disabled" tabindex="-1" enablecontextmenu="false" allowScriptAccess="always" quality="autohight" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="gpu" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"> </embed>'), 'flash_vod': _.template(' <param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="gpu"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> <embed type="application/x-shockwave-flash" disabled="disabled" tabindex="-1" enablecontextmenu="false" allowScriptAccess="always" quality="autohight" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="gpu" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"> </embed>'), 'hls': _.template(' <param name="movie" value="<%= swfPath %>?inline=1"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> <embed type="application/x-shockwave-flash" tabindex="1" enablecontextmenu="false" allowScriptAccess="always" quality="autohigh" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"> </embed>'), 'background_button': _.template('<div class="playpause-button-wrapper" data-background-button> <span class="playpause-icon" data-background-button></span></div>'), 'poster': _.template('<div class="play-wrapper" data-poster> <span class="poster-icon play" data-poster /></div>'), 'seek_time': _.template('<span data-seek-time><%= time %></span>'), 'spinner_loading': _.template('<div data-spinner-container class="spin-container1"> <div data-circle1></div> <div data-circle2></div> <div data-circle3></div> <div data-circle4></div></div><div data-spinner-container class="spin-container2"> <div data-circle1></div> <div data-circle2></div> <div data-circle3></div> <div data-circle4></div></div><div data-spinner-container class="spin-container3"> <div data-circle1></div> <div data-circle2></div> <div data-circle3></div> <div data-circle4></div></div>'), 'spinner_three_bounce': _.template('<div data-bounce1></div><div data-bounce2></div><div data-bounce3></div>'), 'watermark': _.template('<div data-watermark data-watermark-<%=position %>><img src="<%= imageUrl %>"></div>'), CSS: { 'container': '[data-container]{position:absolute;background-color:#000;height:100%;width:100%}', 'core': '[data-player] *{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;margin:0;padding:0;border:0;font-style:normal;font-weight:400;text-align:center;font-size:100%;color:#000;font-family:"lucida grande",tahoma,verdana,arial,sans-serif;text-shadow:0 0 0;box-sizing:border-box}[data-player] * a,[data-player] * abbr,[data-player] * acronym,[data-player] * address,[data-player] * applet,[data-player] * article,[data-player] * aside,[data-player] * audio,[data-player] * b,[data-player] * big,[data-player] * blockquote,[data-player] * canvas,[data-player] * caption,[data-player] * center,[data-player] * cite,[data-player] * code,[data-player] * dd,[data-player] * del,[data-player] * details,[data-player] * dfn,[data-player] * div,[data-player] * dl,[data-player] * dt,[data-player] * em,[data-player] * embed,[data-player] * fieldset,[data-player] * figcaption,[data-player] * figure,[data-player] * footer,[data-player] * form,[data-player] * h1,[data-player] * h2,[data-player] * h3,[data-player] * h4,[data-player] * h5,[data-player] * h6,[data-player] * header,[data-player] * hgroup,[data-player] * i,[data-player] * iframe,[data-player] * img,[data-player] * ins,[data-player] * kbd,[data-player] * label,[data-player] * legend,[data-player] * li,[data-player] * mark,[data-player] * menu,[data-player] * nav,[data-player] * object,[data-player] * ol,[data-player] * output,[data-player] * p,[data-player] * pre,[data-player] * q,[data-player] * ruby,[data-player] * s,[data-player] * samp,[data-player] * section,[data-player] * small,[data-player] * span,[data-player] * strike,[data-player] * strong,[data-player] * sub,[data-player] * summary,[data-player] * sup,[data-player] * table,[data-player] * tbody,[data-player] * td,[data-player] * tfoot,[data-player] * th,[data-player] * thead,[data-player] * time,[data-player] * tr,[data-player] * tt,[data-player] * u,[data-player] * ul,[data-player] * var,[data-player] * video{margin:0;padding:0;border:0;font:inherit;font-size:100%;vertical-align:baseline}[data-player] * table{border-collapse:collapse;border-spacing:0}[data-player] * caption,[data-player] * td,[data-player] * th{text-align:left;font-weight:400;vertical-align:middle}[data-player] * blockquote,[data-player] * q{quotes:none}[data-player] * blockquote:after,[data-player] * blockquote:before,[data-player] * q:after,[data-player] * q:before{content:"";content:none}[data-player] * a img{border:none}[data-player]{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);transform:translate3d(0,0,0);position:relative;margin:0;height:594px;width:1055px;text-align:center;overflow:hidden}[data-player].fullscreen{width:100%;height:100%}[data-player].nocursor{cursor:none}', 'media_control': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.media-control[data-media-control]{position:absolute;border-radius:0;bottom:0;left:0;right:0;margin-left:auto;margin-right:auto;max-width:100%;min-width:60%;height:40px;z-index:9999;-webkit-transition:all .4s ease-out;-moz-transition:all .4s ease-out;-ms-transition:all .4s ease-out;-o-transition:all .4s ease-out;transition:all .4s ease-out}.media-control[data-media-control] .media-control-background[data-background]{position:absolute;height:150px;width:100%;bottom:0;background-image:-webkit-gradient(linear,left top,left bottom,from(rgba(0,0,0,0)),to(rgba(0,0,0,.9)));-webkit-transition:all .6s ease-out;-moz-transition:all .6s ease-out;-ms-transition:all .6s ease-out;-o-transition:all .6s ease-out;transition:all .6s ease-out}.media-control[data-media-control] .media-control-icon{font-family:Player;font-weight:400;font-style:normal;font-size:26px;line-height:32px;letter-spacing:0;speak:none;color:#fff;vertical-align:middle;text-align:left;padding:0 6px;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;color:rgba(255,255,255,.3)}.media-control[data-media-control] .media-control-icon:hover{color:#fff;opacity:.7;text-shadow:rgba(255,255,255,.5) 0 0 15px;-webkit-transition:all .1s ease-out;-moz-transition:all .1s ease-out;-ms-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control].media-control-hide{bottom:-50px}.media-control[data-media-control].media-control-hide .media-control-background[data-background],.media-control[data-media-control].media-control-hide .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls]{position:relative;top:10%;height:80%;vertical-align:middle}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-left-panel[data-media-control]{position:absolute;top:0;left:10px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-center-panel[data-media-control]{height:100%;text-align:center;line-height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-right-panel[data-media-control]{position:absolute;top:0;right:5px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button{background-color:transparent;border:0;margin:0 8px;cursor:pointer;display:inline-block}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button:focus{outline:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]{float:right;background-color:transparent;border:0;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]:before{content:"\\e006"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]{cursor:default;float:right;background-color:transparent;border:0;width:32px;height:100%;opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]:before{content:"\\e007"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].playing:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].paused:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].playing:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].stopped:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration],.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{display:inline-block;font-size:10px;color:#fff;cursor:default;line-height:32px;position:relative}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]{color:rgba(255,255,255,.3)}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]:before{content:"|";margin-right:3px}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]{position:absolute;top:-20px;left:0;display:inline-block;vertical-align:middle;width:100%;height:25px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar]{width:100%;height:1px;position:relative;top:12px;background-color:#666;overflow:hidden}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-1[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#c2c2c2;-webkit-transition:all .1s ease-out;-moz-transition:all .1s ease-out;-ms-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#005aff;-webkit-transition:all .1s ease-out;-moz-transition:all .1s ease-out;-ms-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{position:absolute;top:6px;left:0;width:20px;height:20px;opacity:1;-webkit-transition:all .1s ease-out;-moz-transition:all .1s ease-out;-ms-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] .bar-scrubber-icon[data-seekbar]{position:absolute;left:3px;top:3px;width:8px;height:8px;border-radius:10px;box-shadow:0 0 0 6px rgba(255,255,255,.2);background-color:#fff}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume]{float:right;display:inline-block;width:32px;height:32px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume]{position:absolute;bottom:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]{background-color:transparent;border:0;width:32px;height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:before{content:"\\e004"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:before{content:"\\e005"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume]{width:32px;height:88px;position:absolute;bottom:40px;background:rgba(2,2,2,.5);border-radius:4px;-webkit-transition:all .2s ease-out;-moz-transition:all .2s ease-out;-ms-transition:all .2s ease-out;-o-transition:all .2s ease-out;transition:all .2s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume].volume-bar-hide{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume]{margin-left:12px;background:#6f6f6f;border-radius:4px;width:8px;height:72px;position:relative;top:8px;overflow:hidden}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume] .bar-fill-1[data-volume]{position:absolute;bottom:0;background:#fff;width:100%;height:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-scrubber[data-volume]{position:absolute;bottom:40%;left:6px;width:20px;height:20px}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-scrubber[data-volume] .bar-scrubber-icon[data-volume]{position:absolute;left:4px;top:4px;width:12px;height:12px;border-radius:6px;border:1px solid #6f6f6f;background-color:#fff}', 'flash': '[data-flash]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none}', 'flash_vod': '[data-flash-vod]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none}', 'hls': '[data-hls]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none;top:0}', 'html5_video': '[data-html5-video]{position:absolute;height:100%;width:100%;display:block}', 'background_button': '.background-button[data-background-button]{font-family:Player;position:absolute;height:100%;width:100%;background-color:rgba(0,0,0,.2);-webkit-transition:all .4s ease-out;-moz-transition:all .4s ease-out;-ms-transition:all .4s ease-out;-o-transition:all .4s ease-out;transition:all .4s ease-out}.background-button[data-background-button].hide[data-background-button]{opacity:0}.background-button[data-background-button] .playpause-button-wrapper[data-background-button]{position:absolute;overflow:hidden;width:100%;height:25%;line-height:100%;font-size:20%;top:45%;margin-top:-5%;text-align:center}.background-button[data-background-button] .playpause-button-wrapper[data-background-button] .playpause-icon[data-background-button]{font-family:Player;cursor:pointer;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;font-size:90px;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;color:#fff;opacity:.75}.background-button[data-background-button] .playpause-button-wrapper[data-background-button] .playpause-icon[data-background-button]:hover{text-shadow:rgba(255,255,255,.5) 0 0 15px}.background-button[data-background-button] .playpause-button-wrapper[data-background-button] .playpause-icon[data-background-button].playing:before{content:"\\e002"}.background-button[data-background-button] .playpause-button-wrapper[data-background-button] .playpause-icon[data-background-button].paused:before{content:"\\e001"}', 'pip': '.pip-loading[data-pip]{left:25px;top:15px;position:relative;float:left;z-index:3001;color:#fff}.pip-transition[data-pip]{-webkit-transition:all .4s ease-out;-moz-transition:all .4s ease-out;-ms-transition:all .4s ease-out;-o-transition:all .4s ease-out;transition:all .4s ease-out}.master-container[data-pip]{cursor:default;width:100%;height:100%;font-size:100%;position:absolute;bottom:0;right:0;border:none}.pip-container[data-pip]{cursor:pointer;width:24%;height:24%;font-size:24%;z-index:2000;position:absolute;right:23px;bottom:23px;border-width:2px;border-radius:3px;border-style:solid;border-color:rgba(255,255,255,.25);background-clip:padding-box;-webkit-background-clip:padding-box}.pip-container[data-pip].over-media-control{bottom:63px}', 'poster': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.player-poster[data-poster]{cursor:pointer;position:absolute;height:100%;width:100%;z-index:998;top:0}.player-poster[data-poster] .poster-background[data-poster]{width:100%;height:100%}.player-poster[data-poster] .play-wrapper[data-poster]{position:absolute;overflow:hidden;width:100%;height:20%;line-height:100%;font-size:20%;top:50%;margin-top:-5%;text-align:center}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]{font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;color:#fff;opacity:.75}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster].play[data-poster]:before{content:"\\e001"}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]:hover{opacity:1}', 'seek_time': '.seek-time[data-seek-time]{position:absolute;width:auto;height:20px;bottom:55px;background-color:rgba(2,2,2,.5);z-index:9999;-webkit-transition:all .2s ease-in;-moz-transition:all .2s ease-in;-ms-transition:all .2s ease-in;-o-transition:all .2s ease-in;transition:all .2s ease-in}.seek-time[data-seek-time].hidden[data-seek-time]{opacity:0}.seek-time[data-seek-time] span[data-seek-time]{position:relative;color:#fff;font-size:10px;padding-left:7px;padding-right:7px}', 'spinner_loading': 'div[data-spinner]{width:50px;height:50px;position:relative;margin-left:auto;margin-right:auto;right:0;left:0;z-index:999;top:45%}.spin-container1>div,.spin-container2>div,.spin-container3>div{width:13px;height:13px;background-color:#fff;border-radius:100%;position:absolute;-webkit-animation:bouncedelay 1.2s infinite ease-in-out;animation:bouncedelay 1.2s infinite ease-in-out;-webkit-animation-fill-mode:both;animation-fill-mode:both}[data-spinner] [data-spinner-container]{position:absolute;width:100%;height:100%}.spin-container2{-webkit-transform:rotateZ(45deg);transform:rotateZ(45deg)}.spin-container3{-webkit-transform:rotateZ(90deg);transform:rotateZ(90deg)}[data-circle1]{top:0;left:0}[data-circle2]{top:0;right:0}[data-circle3]{right:0;bottom:0}[data-circle4]{left:0;bottom:0}.spin-container2 [data-circle1]{-webkit-animation-delay:-1.1s;animation-delay:-1.1s}.spin-container3 [data-circle1]{-webkit-animation-delay:-1s;animation-delay:-1s}.spin-container1 [data-circle2]{-webkit-animation-delay:-.9s;animation-delay:-.9s}.spin-container2 [data-circle2]{-webkit-animation-delay:-.8s;animation-delay:-.8s}.spin-container3 [data-circle2]{-webkit-animation-delay:-.7s;animation-delay:-.7s}.spin-container1 [data-circle3]{-webkit-animation-delay:-.6s;animation-delay:-.6s}.spin-container2 [data-circle3]{-webkit-animation-delay:-.5s;animation-delay:-.5s}.spin-container3 [data-circle3]{-webkit-animation-delay:-.4s;animation-delay:-.4s}.spin-container1 [data-circle4]{-webkit-animation-delay:-.3s;animation-delay:-.3s}.spin-container2 [data-circle4]{-webkit-animation-delay:-.2s;animation-delay:-.2s}.spin-container3 [data-circle4]{-webkit-animation-delay:-.1s;animation-delay:-.1s}@-webkit-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0)}40%{-webkit-transform:scale(1)}}@keyframes bouncedelay{0%,100%,80%{transform:scale(0);-webkit-transform:scale(0)}40%{transform:scale(1);-webkit-transform:scale(1)}}', 'spinner_three_bounce': '.spinner-three-bounce[data-spinner]{position:absolute;margin:0 auto;width:70px;text-align:center;z-index:10;top:47%;left:0;right:0}.spinner-three-bounce[data-spinner]>div{width:18px;height:18px;background-color:#FFF;border-radius:100%;display:inline-block;-webkit-animation:bouncedelay 1.4s infinite ease-in-out;-moz-animation:bouncedelay 1.4s infinite ease-in-out;-o-animation:bouncedelay 1.4s infinite ease-in-out;animation:bouncedelay 1.4s infinite ease-in-out;-webkit-animation-fill-mode:both;-moz-animation-fill-mode:both;-o-animation-fill-mode:both;animation-fill-mode:both}.spinner-three-bounce[data-spinner] [data-bounce1]{-webkit-animation-delay:-.32s;animation-delay:-.32s}.spinner-three-bounce[data-spinner] [data-bounce2]{-webkit-animation-delay:-.16s;animation-delay:-.16s}@-webkit-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);-moz-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);-moz-transform:scale(1);transform:scale(1)}}@-moz-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);-moz-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);-moz-transform:scale(1);transform:scale(1)}}@-ms-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);-moz-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);-moz-transform:scale(1);transform:scale(1)}}@keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);-moz-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);-moz-transform:scale(1);transform:scale(1)}}', 'watermark': '[data-watermark]{position:absolute;margin:100px auto 0;width:70px;text-align:center;z-index:10}[data-watermark-bottom-left]{bottom:10px;left:10px}[data-watermark-bottom-right]{bottom:10px;right:42px}[data-watermark-top-left]{top:-95px;left:10px}[data-watermark-top-right]{top:-95px;right:37px}' } }; },{"underscore":7}],"playback":[function(require,module,exports){ module.exports=require('VbgHr3'); },{}],"VbgHr3":[function(require,module,exports){ "use strict"; var UIObject = require('../base/ui_object'); var Playback = function Playback(options) { $traceurRuntime.superCall(this, $Playback.prototype, "constructor", [options]); this.settings = {}; }; var $Playback = Playback; ($traceurRuntime.createClass)(Playback, { play: function() {}, pause: function() {}, stop: function() {}, seek: function(time) {}, getDuration: function() { return 0; }, isPlaying: function() { return false; }, getPlaybackType: function() { return 'no_op'; }, isHighDefinitionInUse: function() { return false; }, destroy: function() { this.$el.remove(); } }, {}, UIObject); Playback.canPlay = (function(source) { return false; }); module.exports = Playback; },{"../base/ui_object":"8lqCAT"}],16:[function(require,module,exports){ "use strict"; var PluginMixin = { initialize: function() { this.bindEvents(); }, enable: function() { this.bindEvents(); }, disable: function() { this.stopListening(); } }; module.exports = PluginMixin; },{}],17:[function(require,module,exports){ "use strict"; var $ = require('jquery'); var _ = require('underscore'); var JST = require('./jst'); var Styler = {getStyleFor: function(name, options) { options = options || {}; return $('<style></style>').html(_.template(JST.CSS[name])(options)); }}; module.exports = Styler; },{"./jst":13,"jquery":3,"underscore":7}],"ui_core_plugin":[function(require,module,exports){ module.exports=require('gNZMEo'); },{}],"gNZMEo":[function(require,module,exports){ "use strict"; var UIObject = require('./ui_object'); var UICorePlugin = function UICorePlugin(core) { $traceurRuntime.superCall(this, $UICorePlugin.prototype, "constructor", [core]); this.core = core; this.render(); }; var $UICorePlugin = UICorePlugin; ($traceurRuntime.createClass)(UICorePlugin, { getExternalInterface: function() { return {}; }, render: function() { this.$el.html(this.template()); this.$el.append(this.styler.getStyleFor(this.name)); this.core.$el.append(this.el); return this; } }, {}, UIObject); module.exports = UICorePlugin; },{"./ui_object":"8lqCAT"}],"8lqCAT":[function(require,module,exports){ "use strict"; var $ = require('jquery'); var _ = require('underscore'); var extend = require('./utils').extend; var BaseObject = require('./base_object'); var delegateEventSplitter = /^(\S+)\s*(.*)$/; var UIObject = function UIObject(options) { $traceurRuntime.superCall(this, $UIObject.prototype, "constructor", [options]); this.cid = _.uniqueId('c'); this._ensureElement(); this.delegateEvents(); }; var $UIObject = UIObject; ($traceurRuntime.createClass)(UIObject, { get tagName() { return 'div'; }, $: function(selector) { return this.$el.find(selector); }, render: function() { return this; }, remove: function() { this.$el.remove(); this.stopListening(); return this; }, setElement: function(element, delegate) { if (this.$el) this.undelegateEvents(); this.$el = element instanceof $ ? element : $(element); this.el = this.$el[0]; if (delegate !== false) this.delegateEvents(); return this; }, delegateEvents: function(events) { if (!(events || (events = _.result(this, 'events')))) return this; this.undelegateEvents(); for (var key in events) { var method = events[key]; if (!_.isFunction(method)) method = this[events[key]]; if (!method) continue; var match = key.match(delegateEventSplitter); var eventName = match[1], selector = match[2]; method = _.bind(method, this); eventName += '.delegateEvents' + this.cid; if (selector === '') { this.$el.on(eventName, method); } else { this.$el.on(eventName, selector, method); } } return this; }, undelegateEvents: function() { this.$el.off('.delegateEvents' + this.cid); return this; }, _ensureElement: function() { if (!this.el) { var attrs = _.extend({}, _.result(this, 'attributes')); if (this.id) attrs.id = _.result(this, 'id'); if (this.className) attrs['class'] = _.result(this, 'className'); var $el = $('<' + _.result(this, 'tagName') + '>').attr(attrs); this.setElement($el, false); } else { this.setElement(_.result(this, 'el'), false); } } }, {}, BaseObject); UIObject.extend = extend; module.exports = UIObject; },{"./base_object":"2HNVgz","./utils":24,"jquery":3,"underscore":7}],"ui_object":[function(require,module,exports){ module.exports=require('8lqCAT'); },{}],"Z7u8cr":[function(require,module,exports){ "use strict"; var PluginMixin = require('./plugin_mixin'); var UIObject = require('./ui_object'); var extend = require('./utils').extend; var _ = require('underscore'); var UIPlugin = function UIPlugin() { $traceurRuntime.defaultSuperCall(this, $UIPlugin.prototype, arguments); }; var $UIPlugin = UIPlugin; ($traceurRuntime.createClass)(UIPlugin, { get type() { return 'ui'; }, enable: function() { $UIPlugin.super('enable').call(this); this.$el.show(); }, disable: function() { $UIPlugin.super('disable').call(this); this.$el.hide(); }, bindEvents: function() {} }, {}, UIObject); _.extend(UIPlugin.prototype, PluginMixin); UIPlugin.extend = extend; module.exports = UIPlugin; },{"./plugin_mixin":16,"./ui_object":"8lqCAT","./utils":24,"underscore":7}],"ui_plugin":[function(require,module,exports){ module.exports=require('Z7u8cr'); },{}],24:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('jquery'); var Moment = require('moment'); var extend = function(protoProps, staticProps) { var parent = this; var child; if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function() { return parent.apply(this, arguments); }; } _.extend(child, parent, staticProps); var Surrogate = function() { this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate(); if (protoProps) _.extend(child.prototype, protoProps); child.__super__ = parent.prototype; child.super = function(name) { return parent.prototype[name]; }; child.prototype.getClass = function() { return child; }; return child; }; var zeroPad = function(number, size) { return (new Array(size + 1 - number.toString().length)).join('0') + number; }; var formatTime = function(time, options) { options = options || {}; var separator = options.humanFriendly ? 'm' : ':'; var duration = Moment.duration(time * 1000); var str = zeroPad(duration.seconds(), 2); if (duration.hours()) { str = zeroPad(duration.minutes(), 2) + separator + (options.humanFriendly ? '' : str); if (options.humanFriendly) { separator = 'h'; } str = duration.hours() + separator + str; } else { var minutes = duration.minutes(); str = (!options.humanFriendly || minutes > 0 ? minutes + separator : '') + str; if (options.humanFriendly) { str += 's'; } } if (options.showMillis && !options.humanFriendly) { str += separator + duration.milliseconds(); } return str; }; var Fullscreen = { isFullscreen: function() { return document.webkitIsFullScreen || document.mozFullScreen; }, requestFullscreen: function(el) { if (el.requestFullscreen) { el.requestFullscreen(); } else if (el.webkitRequestFullscreen) { el.webkitRequestFullscreen(); } else if (el.mozRequestFullScreen) { el.mozRequestFullScreen(); } else if (el.msRequestFullscreen) { el.msRequestFullscreen(); } }, cancelFullscreen: function() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } } }; var HEX_TAB = "0123456789abcdef"; var B64_TAB = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; var b64pad = ""; var rstr2b64 = function(input) { var output = ""; var len = input.length; for (var i = 0; i < len; i += 3) { var triplet = (input.charCodeAt(i) << 16) | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0); for (var j = 0; j < 4; j++) { if (i * 8 + j * 6 > input.length * 8) output += b64pad; else output += B64_TAB.charAt((triplet >>> 6 * (3 - j)) & 0x3F); } } return output; }; var rstr2hex = function(input) { var output = ""; for (var i = 0; i < input.length; i++) { var x = input.charCodeAt(i); output += HEX_TAB.charAt((x >>> 4) & 0x0F) + HEX_TAB.charAt(x & 0x0F); } return output; }; var getHostname = function() { return location.hostname; }; var Ajax = { jsonp: function(settings) { var defer = new $.Deferred(); settings.callbackName = settings.callbackName || "json_callback"; settings.timeout = settings.timeout || 15000; window[settings.callbackName] = function(data) { if (!Ajax.isErrorObject(data)) { defer.resolve(data); } else { defer.reject(data); } }; var head = $("head")[0]; var script = document.createElement("script"); script.setAttribute("src", settings.url); script.setAttribute("async", "async"); script.onload = script.onreadystatechange = function(eventLoad) { if (!script.readyState || /loaded|complete/.test(script.readyState)) { if (settings.timeoutId) { window.clearTimeout(settings.timeoutId); } script.onload = script.onreadystatechange = null; if (head && script.parentNode) head.removeChild(script); script = undefined; } }; head.insertBefore(script, head.firstChild); if (settings.error) { settings.timeoutId = window.setTimeout(settings.error, settings.timeout); } return defer.promise(); }, isErrorObject: function(data) { return data && data.http_status_code && data.http_status_code != 200; } }; module.exports = { extend: extend, zeroPad: zeroPad, formatTime: formatTime, Fullscreen: Fullscreen, Ajax: Ajax, rstr2b64: rstr2b64, rstr2hex: rstr2hex, getHostname: getHostname }; },{"jquery":3,"moment":4,"underscore":7}],"browser":[function(require,module,exports){ module.exports=require('195Wj5'); },{}],"195Wj5":[function(require,module,exports){ "use strict"; var Browser = function Browser() {}; ($traceurRuntime.createClass)(Browser, {}, {}); Browser.isSafari = (!!navigator.userAgent.match(/safari/i) && navigator.userAgent.indexOf('Chrome') === -1); Browser.isChrome = !!(navigator.userAgent.match(/chrome/i)); Browser.isFirefox = !!(navigator.userAgent.match(/firefox/i)); Browser.isLegacyIE = !!(window.ActiveXObject); Browser.isMobile = !!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)); Browser.isWin8App = !!(/MSAppHost/i.test(navigator.userAgent)); module.exports = Browser; },{}],27:[function(require,module,exports){ "use strict"; var UIObject = require('../../base/ui_object'); var Styler = require('../../base/styler'); var _ = require('underscore'); var Container = function Container(options) { $traceurRuntime.superCall(this, $Container.prototype, "constructor", [options]); this.playback = options.playback; this.settings = this.playback.settings; this.isReady = false; this.mediaControlDisabled = false; this.plugins = [this.playback]; this.bindEvents(); }; var $Container = Container; ($traceurRuntime.createClass)(Container, { get name() { return 'Container'; }, get attributes() { return {'data-container': ''}; }, get events() { return {'click': 'clicked'}; }, bindEvents: function() { this.listenTo(this.playback, 'playback:progress', this.progress); this.listenTo(this.playback, 'playback:timeupdate', this.timeUpdated); this.listenTo(this.playback, 'playback:ready', this.ready); this.listenTo(this.playback, 'playback:buffering', this.buffering); this.listenTo(this.playback, 'playback:bufferfull', this.bufferfull); this.listenTo(this.playback, 'playback:settingsupdate', this.settingsUpdate); this.listenTo(this.playback, 'playback:loadedmetadata', this.loadedMetadata); this.listenTo(this.playback, 'playback:highdefinitionupdate', this.highDefinitionUpdate); this.listenTo(this.playback, 'playback:playbackstate', this.playbackStateChanged); this.listenTo(this.playback, 'playback:mediacontrol:disable', this.disableMediaControl); this.listenTo(this.playback, 'playback:mediacontrol:enable', this.enableMediaControl); this.listenTo(this.playback, 'playback:ended', this.ended); this.listenTo(this.playback, 'playback:play', this.playing); }, with: function(klass) { _.extend(this, klass); return this; }, playbackStateChanged: function() { this.trigger('container:playbackstate'); }, statsAdd: function(metric) { this.trigger('container:stats:add', metric); }, statsReport: function(metrics) { this.trigger('container:stats:report', metrics); }, getPlaybackType: function() { return this.playback.getPlaybackType(); }, destroy: function() { this.trigger('container:destroyed', this, this.name); this.playback.destroy(); this.$el.remove(); }, setStyle: function(style) { this.$el.css(style); }, animate: function(style, duration) { return this.$el.animate(style, duration).promise(); }, ready: function() { this.isReady = true; this.trigger('container:ready', this.name); }, isPlaying: function() { return this.playback.isPlaying(); }, getDuration: function() { return this.playback.getDuration(); }, error: function(errorObj) { this.trigger('container:error', errorObj, this.name); }, loadedMetadata: function(duration) { this.trigger('container:loadedmetadata', duration); }, timeUpdated: function(position, duration) { this.trigger('container:timeupdate', position, duration, this.name); }, progress: function(startPosition, endPosition, duration) { this.trigger('container:progress', startPosition, endPosition, duration, this.name); }, playing: function() { this.trigger('container:play', this.name); }, play: function() { this.playback.play(); }, stop: function() { this.trigger('container:stop', this.name); this.playback.stop(); }, pause: function() { this.trigger('container:pause', this.name); this.playback.pause(); }, ended: function() { this.trigger('container:ended', this, this.name); }, clicked: function() { this.trigger('container:click', this, this.name); }, setCurrentTime: function(time) { this.trigger('container:seek', time, this.name); this.playback.seek(time); }, setVolume: function(value) { this.trigger('container:volume', value, this.name); this.playback.volume(value); }, requestFullscreen: function() { this.trigger('container:fullscreen', this.name); }, buffering: function() { this.trigger('container:state:buffering', this.name); }, bufferfull: function() { this.trigger('container:state:bufferfull', this.name); }, addPlugin: function(plugin) { this.plugins.push(plugin); }, hasPlugin: function(name) { return !!this.getPlugin(name); }, getPlugin: function(name) { return _(this.plugins).find(function(plugin) { return plugin.name === name; }); }, settingsUpdate: function() { this.settings = this.playback.settings; this.trigger('container:settingsupdate'); }, highDefinitionUpdate: function() { this.trigger('container:highdefinitionupdate'); }, isHighDefinitionInUse: function() { return this.playback.isHighDefinitionInUse(); }, disableMediaControl: function() { this.mediaControlDisabled = true; this.trigger('container:mediacontrol:disable'); }, enableMediaControl: function() { this.mediaControlDisabled = false; this.trigger('container:mediacontrol:enable'); }, render: function() { var style = Styler.getStyleFor('container'); this.$el.append(style); this.$el.append(this.playback.render().el); return this; } }, {}, UIObject); module.exports = Container; },{"../../base/styler":17,"../../base/ui_object":"8lqCAT","underscore":7}],28:[function(require,module,exports){ "use strict"; module.exports = require('./container'); },{"./container":27}],29:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var BaseObject = require('../../base/base_object'); var Container = require('../container'); var $ = require('jquery'); var ContainerFactory = function ContainerFactory(options, loader) { $traceurRuntime.superCall(this, $ContainerFactory.prototype, "constructor", [options]); this.options = options; this.loader = loader; }; var $ContainerFactory = ContainerFactory; ($traceurRuntime.createClass)(ContainerFactory, { createContainers: function() { return $.Deferred(function(promise) { promise.resolve(_.map(this.options.sources, function(source) { return this.createContainer(source); }, this)); }.bind(this)); }, findPlaybackPlugin: function(source) { return _.find(this.loader.playbackPlugins, (function(p) { return p.canPlay(source.toString()); }), this); }, createContainer: function(source) { var playbackPlugin = this.findPlaybackPlugin(source); var options = _.extend({}, this.options, { src: source, autoPlay: !!this.options.autoPlay }); var playback = new playbackPlugin(options); var container = new Container({playback: playback}); var defer = $.Deferred(); defer.promise(container); this.addContainerPlugins(container, source); this.listenToOnce(container, 'container:ready', (function() { return defer.resolve(container); })); return container; }, addContainerPlugins: function(container, source) { _.each(this.loader.containerPlugins, function(Plugin) { var options = _.extend(this.options, { container: container, src: source }); container.addPlugin(new Plugin(options)); }, this); } }, {}, BaseObject); module.exports = ContainerFactory; },{"../../base/base_object":"2HNVgz","../container":28,"jquery":3,"underscore":7}],30:[function(require,module,exports){ "use strict"; module.exports = require('./container_factory'); },{"./container_factory":29}],31:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('jquery'); var UIObject = require('../../base/ui_object'); var ContainerFactory = require('../container_factory'); var Fullscreen = require('../../base/utils').Fullscreen; var Styler = require('../../base/styler'); var MediaControl = require('../media_control'); var PlayerInfo = require('../player_info'); var Core = function Core(options) { var $__0 = this; $traceurRuntime.superCall(this, $Core.prototype, "constructor", [options]); this.playerInfo = PlayerInfo.getInstance(); this.playerInfo.options = options; this.options = options; this.plugins = []; this.containers = []; this.createContainers(options); this.updateSize(); document.addEventListener('mozfullscreenchange', (function() { return $__0.exit(); })); $(window).resize((function() { return $__0.updateSize(); })); }; var $Core = Core; ($traceurRuntime.createClass)(Core, { get events() { return { 'webkitfullscreenchange': 'exit', 'mousemove': 'showMediaControl', 'mouseleave': 'hideMediaControl' }; }, get attributes() { return {'data-player': ''}; }, createContainers: function(options) { var $__0 = this; this.defer = $.Deferred(); this.defer.promise(this); this.containerFactory = new ContainerFactory(options, options.loader); this.containerFactory.createContainers().then((function(containers) { return $__0.setupContainers(containers); })).then((function(containers) { return $__0.resolveOnContainersReady(containers); })); }, updateSize: function() { if (Fullscreen.isFullscreen()) { this.$el.addClass('fullscreen'); this.$el.removeAttr('style'); } else { var needStretch = this.options.stretchWidth && this.options.stretchHeight; var width, height; if (needStretch && this.options.stretchWidth <= window.innerWidth && this.options.stretchHeight <= (window.innerHeight * 0.73)) { width = this.options.stretchWidth; height = this.options.stretchHeight; } else { width = this.options.width; height = this.options.height; } this.$el.css({width: width}); this.$el.css({height: height}); this.$el.removeClass('fullscreen'); } }, resolveOnContainersReady: function(containers) { var $__0 = this; $.when.apply($, containers).done((function() { return $__0.defer.resolve($__0); })); }, addPlugin: function(plugin) { this.plugins.push(plugin); }, hasPlugin: function(name) { return !!this.getPlugin(name); }, getPlugin: function(name) { return _(this.plugins).find((function(plugin) { return plugin.name === name; })); }, load: function(sources) { var $__0 = this; sources = _.isString(sources) ? [sources] : sources; _(this.containers).each((function(container) { return container.destroy(); })); this.containerFactory.options = _(this.options).extend({sources: sources}); this.containerFactory.createContainers().then((function(containers) { return $__0.setupContainers(containers); })); }, destroy: function() { _(this.containers).each((function(container) { return container.destroy(); })); this.$el.remove(); }, exit: function() { this.updateSize(); this.mediaControl.show(); }, setMediaControlContainer: function(container) { this.mediaControl.setContainer(container); this.mediaControl.render(); }, disableMediaControl: function() { this.mediaControl.disable(); this.$el.removeClass('nocursor'); }, enableMediaControl: function() { this.mediaControl.enable(); }, removeContainer: function(container) { console.log('container being removed'); this.stopListening(container); this.containers = _.without(this.containers, container); }, appendContainer: function(container) { this.listenTo(container, 'container:destroyed', this.removeContainer); this.el.appendChild(container.render().el); this.containers.push(container); }, prependContainer: function(container) { this.listenTo(container, 'container:destroyed', this.removeContainer); this.$el.append(container.render().el); this.containers.unshift(container); }, setupContainers: function(containers) { _.map(containers, this.appendContainer, this); this.setupMediaControl(this.getCurrentContainer()); this.render(); this.$el.appendTo(this.options.parentElement); return containers; }, createContainer: function(source) { var container = this.containerFactory.createContainer(source); this.appendContainer(container); return container; }, setupMediaControl: function(container) { if (this.mediaControl) { this.mediaControl.setContainer(container); } else { this.mediaControl = this.createMediaControl(_.extend({container: container}, this.options)); this.listenTo(this.mediaControl, 'mediacontrol:fullscreen', this.toggleFullscreen); this.listenTo(this.mediaControl, 'mediacontrol:show', this.onMediaControlShow.bind(this, true)); this.listenTo(this.mediaControl, 'mediacontrol:hide', this.onMediaControlShow.bind(this, false)); } }, createMediaControl: function(options) { if (options.mediacontrol && options.mediacontrol.external) { return new options.mediacontrol.external(options); } else { return new MediaControl(options); } }, getCurrentContainer: function() { return this.containers[0]; }, toggleFullscreen: function() { if (!Fullscreen.isFullscreen()) { Fullscreen.requestFullscreen(this.el); this.$el.addClass('fullscreen'); } else { Fullscreen.cancelFullscreen(); this.$el.removeClass('fullscreen nocursor'); } this.mediaControl.show(); }, showMediaControl: function(event) { this.mediaControl.show(event); }, hideMediaControl: function(event) { this.mediaControl.hide(event); }, onMediaControlShow: function(showing) { if (showing) this.$el.removeClass('nocursor'); else if (Fullscreen.isFullscreen()) this.$el.addClass('nocursor'); }, render: function() { var $__0 = this; var style = Styler.getStyleFor('core'); this.$el.append(style); this.$el.append(this.mediaControl.render().el); this.$el.ready((function() { $__0.options.width = $__0.options.width || $__0.$el.width(); $__0.options.height = $__0.options.height || $__0.$el.height(); $__0.updateSize(); })); return this; } }, {}, UIObject); module.exports = Core; },{"../../base/styler":17,"../../base/ui_object":"8lqCAT","../../base/utils":24,"../container_factory":30,"../media_control":"A8Uh+k","../player_info":"Pce0iO","jquery":3,"underscore":7}],32:[function(require,module,exports){ "use strict"; module.exports = require('./core'); },{"./core":31}],33:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var BaseObject = require('../../base/base_object'); var Core = require('../core'); var CoreFactory = function CoreFactory(player, loader) { this.player = player; this.options = player.options; this.loader = loader; this.options.loader = this.loader; }; ($traceurRuntime.createClass)(CoreFactory, { create: function() { this.core = new Core(this.options); this.core.then(this.addCorePlugins.bind(this)); return this.core; }, addCorePlugins: function() { _.each(this.loader.globalPlugins, function(Plugin) { var plugin = new Plugin(this.core); this.core.addPlugin(plugin); this.setupExternalInterface(plugin); }, this); return this.core; }, setupExternalInterface: function(plugin) { _.each(plugin.getExternalInterface(), function(value, key) { this.player[key] = value.bind(plugin); }, this); } }, {}, BaseObject); module.exports = CoreFactory; },{"../../base/base_object":"2HNVgz","../core":32,"underscore":7}],34:[function(require,module,exports){ "use strict"; module.exports = require('./core_factory'); },{"./core_factory":33}],35:[function(require,module,exports){ "use strict"; module.exports = require('./loader'); },{"./loader":36}],36:[function(require,module,exports){ "use strict"; var BaseObject = require('../../base/base_object'); var _ = require('underscore'); var PlayerInfo = require('../player_info'); var HTML5VideoPlayback = require('../../playbacks/html5_video'); var FlashVideoPlayback = require('../../playbacks/flash'); var HTML5AudioPlayback = require('../../playbacks/html5_audio'); var HLSVideoPlayback = require('../../playbacks/hls'); var NoOp = require('../../playbacks/no_op'); var SpinnerThreeBouncePlugin = require('../../plugins/spinner_three_bounce'); var StatsPlugin = require('../../plugins/stats'); var WaterMarkPlugin = require('../../plugins/watermark'); var PosterPlugin = require('../../plugins/poster'); var BackgroundButton = require('../../plugins/background_button'); var SeekTime = require('../../plugins/seek_time'); var Loader = function Loader(externalPlugins) { $traceurRuntime.superCall(this, $Loader.prototype, "constructor", []); this.playerInfo = PlayerInfo.getInstance(); this.playbackPlugins = [FlashVideoPlayback, HTML5VideoPlayback, HTML5AudioPlayback, HLSVideoPlayback, NoOp]; this.containerPlugins = [SpinnerThreeBouncePlugin, WaterMarkPlugin, PosterPlugin, StatsPlugin]; this.globalPlugins = [BackgroundButton, SeekTime]; if (externalPlugins) { this.addExternalPlugins(externalPlugins); } }; var $Loader = Loader; ($traceurRuntime.createClass)(Loader, { addExternalPlugins: function(plugins) { if (plugins.playback) { this.playbackPlugins = plugins.playback.concat(this.playbackPlugins); } if (plugins.container) { this.containerPlugins = plugins.container.concat(this.containerPlugins); } if (plugins.core) { this.globalPlugins = plugins.core.concat(this.globalPlugins); } this.playerInfo.playbackPlugins = this.playbackPlugins; }, getPlugin: function(name) { var allPlugins = _.union(this.containerPlugins, this.playbackPlugins, this.globalPlugins); return _.find(allPlugins, function(plugin) { return plugin.prototype.name === name; }); } }, {}, BaseObject); module.exports = Loader; },{"../../base/base_object":"2HNVgz","../../playbacks/flash":46,"../../playbacks/hls":48,"../../playbacks/html5_audio":50,"../../playbacks/html5_video":52,"../../playbacks/no_op":53,"../../plugins/background_button":55,"../../plugins/poster":58,"../../plugins/seek_time":60,"../../plugins/spinner_three_bounce":62,"../../plugins/stats":64,"../../plugins/watermark":66,"../player_info":"Pce0iO","underscore":7}],"A8Uh+k":[function(require,module,exports){ "use strict"; module.exports = require('./media_control'); },{"./media_control":39}],"media_control":[function(require,module,exports){ module.exports=require('A8Uh+k'); },{}],39:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('jquery'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var UIObject = require('../../base/ui_object'); var Utils = require('../../base/utils'); var Mousetrap = require('mousetrap'); var ScrollMonitor = require('scrollmonitor'); var MediaControl = function MediaControl(options) { var $__0 = this; $traceurRuntime.superCall(this, $MediaControl.prototype, "constructor", [options]); this.options = options; this.container = options.container; this.keepVisible = false; this.addEventListeners(); this.settings = { left: ['play', 'stop', 'pause'], right: ['volume'], default: ['position', 'seekbar', 'duration'] }; this.settings = _.isEmpty(this.container.settings) ? this.settings : this.container.settings; this.disabled = false; if (this.container.mediaControlDisabled || this.options.chromeless) { this.disable(); } this.currentVolume = 100; $(document).bind('mouseup', (function(event) { return $__0.stopDrag(event); })); $(document).bind('mousemove', (function(event) { return $__0.updateDrag(event); })); }; var $MediaControl = MediaControl; ($traceurRuntime.createClass)(MediaControl, { get name() { return 'MediaControl'; }, get attributes() { return { class: 'media-control', 'data-media-control': '' }; }, get events() { return { 'click [data-play]': 'play', 'click [data-pause]': 'pause', 'click [data-playpause]': 'togglePlayPause', 'click [data-stop]': 'stop', 'click [data-playstop]': 'togglePlayStop', 'click [data-fullscreen]': 'toggleFullscreen', 'click [data-seekbar]': 'seek', 'click .bar-background[data-volume]': 'volume', 'click .drawer-icon[data-volume]': 'toggleMute', 'mouseover .drawer-container[data-volume]': 'showVolumeBar', 'mouseleave .drawer-container[data-volume]': 'hideVolumeBar', 'mousedown .bar-scrubber[data-seekbar]': 'startSeekDrag', 'mousedown .bar-scrubber[data-volume]': 'startVolumeDrag', 'mousemove .bar-container[data-seekbar]': 'mousemoveOnSeekBar', 'mouseleave .bar-container[data-seekbar]': 'mouseleaveOnSeekBar', 'mouseenter .media-control-layer[data-controls]': 'setKeepVisible', 'mouseleave .media-control-layer[data-controls]': 'resetKeepVisible' }; }, get template() { return JST.media_control; }, addEventListeners: function() { var $__0 = this; this.listenTo(this.container, 'container:play', this.changeTogglePlay); this.listenTo(this.container, 'container:timeupdate', this.updateSeekBar); this.listenTo(this.container, 'container:progress', this.updateProgressBar); this.listenTo(this.container, 'container:settingsupdate', this.settingsUpdate); this.listenTo(this.container, 'container:highdefinitionupdate', this.highDefinitionUpdate); this.listenTo(this.container, 'container:mediacontrol:disable', this.disable); this.listenTo(this.container, 'container:mediacontrol:enable', this.enable); this.listenTo(this.container, 'container:playbackstate', this.updatePlaybackType); this.listenTo(this.container, 'container:ended', this.ended); if (this.options.autoPlayVisible) { this.elementWatcher = ScrollMonitor.create(this.$el); this.elementWatcher.enterViewport((function() { return $__0.enterViewport(); })); } }, disable: function() { this.disabled = true; this.hide(); this.$el.hide(); }, enable: function() { if (this.options.chromeless) return; this.disabled = false; this.show(); }, enterViewport: function() { if (this.elementWatcher.top !== 0 && !this.container.isPlaying()) { this.play(); } }, play: function() { this.container.play(); }, pause: function() { this.container.pause(); }, stop: function() { this.container.stop(); }, changeTogglePlay: function() { if (this.container.isPlaying()) { this.$playPauseToggle.removeClass('paused').addClass('playing'); this.$playStopToggle.removeClass('stopped').addClass('playing'); this.trigger('mediacontrol:playing'); } else { this.$playPauseToggle.removeClass('playing').addClass('paused'); this.$playStopToggle.removeClass('playing').addClass('stopped'); this.trigger('mediacontrol:notplaying'); } }, mousemoveOnSeekBar: function(event) { this.trigger('mediacontrol:mousemove:seekbar', event); }, mouseleaveOnSeekBar: function(event) { this.trigger('mediacontrol:mouseleave:seekbar', event); }, togglePlayPause: function() { if (this.container.isPlaying()) { this.container.pause(); } else { this.container.play(); } this.changeTogglePlay(); }, togglePlayStop: function() { if (this.container.isPlaying()) { this.container.stop(); } else { this.container.play(); } this.changeTogglePlay(); }, startSeekDrag: function(event) { this.draggingSeekBar = true; if (event) { event.preventDefault(); } }, startVolumeDrag: function(event) { this.draggingVolumeBar = true; if (event) { event.preventDefault(); } }, stopDrag: function(event) { if (this.draggingSeekBar) { this.seek(event); } this.draggingSeekBar = false; this.draggingVolumeBar = false; }, updateDrag: function(event) { if (event) { event.preventDefault(); } if (this.draggingSeekBar) { var offsetX = event.pageX - this.$seekBarContainer.offset().left; var pos = offsetX / this.$seekBarContainer.width() * 100; pos = Math.min(100, Math.max(pos, 0)); this.setSeekPercentage(pos); } else if (this.draggingVolumeBar) { this.volume(event); } }, volume: function(event) { var offsetY = event.pageY - this.$volumeBarContainer.offset().top; this.currentVolume = (1 - (offsetY / this.$volumeBarContainer.height())) * 100; this.currentVolume = Math.min(100, Math.max(this.currentVolume, 0)); this.container.setVolume(this.currentVolume); this.setVolumeLevel(this.currentVolume); }, toggleMute: function() { if (!!this.mute) { this.container.setVolume(this.currentVolume); this.setVolumeLevel(this.currentVolume); this.mute = false; } else { this.container.setVolume(0); this.setVolumeLevel(0); this.mute = true; } }, toggleFullscreen: function() { this.trigger('mediacontrol:fullscreen', this.name); }, setContainer: function(container) { this.stopListening(this.container); this.container = container; this.changeTogglePlay(); this.addEventListeners(); this.settingsUpdate(); this.container.setVolume(this.currentVolume); if (this.container.mediaControlDisabled) this.disable(); }, showVolumeBar: function() { if (this.hideVolumeId) { clearTimeout(this.hideVolumeId); } this.$volumeBarContainer.show(); this.$volumeBarContainer.removeClass('volume-bar-hide'); }, hideVolumeBar: function() { var $__0 = this; if (!this.$volumeBarContainer) return; if (this.hideVolumeId) { clearTimeout(this.hideVolumeId); } this.hideVolumeId = setTimeout((function() { $__0.$volumeBarContainer.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', (function() { $__0.$volumeBarContainer.off('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend'); $__0.$volumeBarContainer.hide(); })); $__0.$volumeBarContainer.addClass('volume-bar-hide'); }), 750); }, ended: function() { this.changeTogglePlay(); }, updateProgressBar: function(startPosition, endPosition, duration) { var loadedStart = startPosition / duration * 100; var loadedEnd = endPosition / duration * 100; this.$seekBarLoaded.css({ left: loadedStart + '%', width: (loadedEnd - loadedStart) + '%' }); }, updateSeekBar: function(position, duration) { if (this.draggingSeekBar) return; var seekbarValue = (100 / duration) * position; this.setSeekPercentage(seekbarValue); this.$('[data-position]').html(Utils.formatTime(position)); this.$('[data-duration]').html(Utils.formatTime(duration)); }, seek: function(event) { var offsetX = event.pageX - this.$seekBarContainer.offset().left; var pos = offsetX / this.$seekBarContainer.width() * 100; pos = Math.min(100, Math.max(pos, 0)); this.container.setCurrentTime(pos); }, setKeepVisible: function() { this.keepVisible = true; }, resetKeepVisible: function() { this.keepVisible = false; }, show: function(event) { var $__0 = this; if (this.disabled) return; var timeout = 2000; if (!event || (event.clientX !== this.lastMouseX && event.clientY !== this.lastMouseY) || navigator.userAgent.match(/firefox/i)) { if (this.hideId) { clearTimeout(this.hideId); } this.$el.show(); this.trigger('mediacontrol:show', this.name); this.$el.removeClass('media-control-hide'); this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); if (event) { this.lastMouseX = event.clientX; this.lastMouseY = event.clientY; } } }, hide: function() { var $__0 = this; var timeout = 2000; if (this.hideId) { clearTimeout(this.hideId); } if (this.keepVisible || this.draggingVolumeBar || this.draggingSeekBar) { this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); } else { if (this.$volumeBarContainer) { this.$volumeBarContainer.hide(); } this.trigger('mediacontrol:hide', this.name); this.$el.addClass('media-control-hide'); } }, settingsUpdate: function() { this.render(); }, highDefinitionUpdate: function() { if (this.container.isHighDefinitionInUse()) { this.$el.find('button[data-hd-indicator]').addClass("enabled"); } else { this.$el.find('button[data-hd-indicator]').removeClass("enabled"); } }, createCachedElements: function() { this.$playPauseToggle = this.$el.find('button.media-control-button[data-playpause]'); this.$playStopToggle = this.$el.find('button.media-control-button[data-playstop]'); this.$seekBarContainer = this.$el.find('.bar-container[data-seekbar]'); this.$seekBarLoaded = this.$el.find('.bar-fill-1[data-seekbar]'); this.$seekBarPosition = this.$el.find('.bar-fill-2[data-seekbar]'); this.$seekBarScrubber = this.$el.find('.bar-scrubber[data-seekbar]'); this.$volumeBarContainer = this.$el.find('.bar-container[data-volume]'); this.$volumeBarBackground = this.$el.find('.bar-background[data-volume]'); this.$volumeBarFill = this.$el.find('.bar-fill-1[data-volume]'); this.$volumeBarScrubber = this.$el.find('.bar-scrubber[data-volume]'); this.$volumeIcon = this.$el.find('.drawer-icon[data-volume]'); }, setVolumeLevel: function(value) { var containerHeight = this.$volumeBarContainer.height(); var barHeight = this.$volumeBarBackground.height(); var offset = (containerHeight - barHeight) / 2.0; var pos = barHeight * value / 100.0 - this.$volumeBarScrubber.height() / 2.0 + offset; this.$volumeBarFill.css({height: value + '%'}); this.$volumeBarScrubber.css({bottom: pos}); if (value > 0) { this.$volumeIcon.removeClass('muted'); } else { this.$volumeIcon.addClass('muted'); } }, setSeekPercentage: function(value) { if (value > 100) return; var pos = this.$seekBarContainer.width() * value / 100.0 - this.$seekBarScrubber.width() / 2.0; this.$seekBarPosition.css({width: value + '%'}); this.$seekBarScrubber.css({left: pos}); }, bindKeyEvents: function() { var $__0 = this; Mousetrap.bind(['space'], (function() { return $__0.togglePlayPause(); })); }, parseColors: function() { var $__0 = this; var translate = { query: { 'seekbar': '.bar-fill-2[data-seekbar]', 'buttons': '[data-media-control] > .media-control-icon, [data-volume]' }, rule: { 'seekbar': 'background-color', 'buttons': 'color' } }; var customColors = _.pick(this.options.mediacontrol, 'seekbar', 'buttons'); _.each(customColors, (function(value, key) { $__0.$el.find(translate.query[key]).css(translate.rule[key], customColors[key]); })); }, render: function() { var $__0 = this; var timeout = 1000; var style = Styler.getStyleFor('media_control'); this.$el.html(this.template({settings: this.settings})); this.$el.append(style); this.createCachedElements(); this.$playPauseToggle.addClass('paused'); this.$playStopToggle.addClass('stopped'); this.currentVolume = this.currentVolume || 100; this.$volumeBarContainer.hide(); this.changeTogglePlay(); this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); if (this.disabled) { this.hide(); } this.$el.ready((function() { $__0.setVolumeLevel($__0.currentVolume); $__0.setSeekPercentage(0); $__0.bindKeyEvents(); })); this.parseColors(); return this; } }, {}, UIObject); module.exports = MediaControl; },{"../../base/jst":13,"../../base/styler":17,"../../base/ui_object":"8lqCAT","../../base/utils":24,"jquery":3,"mousetrap":5,"scrollmonitor":6,"underscore":7}],40:[function(require,module,exports){ "use strict"; var Events = require('../base/events'); var events = new Events(); var Mediator = function Mediator() {}; ($traceurRuntime.createClass)(Mediator, {}, {}); Mediator.on = function(name, callback, context) { events.on(name, callback, context); return; }; Mediator.once = function(name, callback, context) { events.once(name, callback, context); return; }; Mediator.off = function(name, callback, context) { events.off(name, callback, context); return; }; Mediator.trigger = function(name, opts) { events.trigger(name, opts); return; }; Mediator.stopListening = function(obj, name, callback) { events.stopListening(obj, name, callback); return; }; module.exports = Mediator; },{"../base/events":12}],"Pce0iO":[function(require,module,exports){ "use strict"; module.exports = require('./player_info'); },{"./player_info":43}],"player_info":[function(require,module,exports){ module.exports=require('Pce0iO'); },{}],43:[function(require,module,exports){ "use strict"; var BaseObject = require('../../base/base_object'); var PlayerInfo = function PlayerInfo() { this.options = {}; this.playbackPlugins = []; }; ($traceurRuntime.createClass)(PlayerInfo, {}, {}, BaseObject); PlayerInfo.getInstance = function() { if (this._instance === undefined) { this._instance = new this(); } return this._instance; }; module.exports = PlayerInfo; },{"../../base/base_object":"2HNVgz"}],44:[function(require,module,exports){ (function (global){ "use strict"; var BaseObject = require('./base/base_object'); var CoreFactory = require('./components/core_factory'); var Loader = require('./components/loader'); var Mediator = require('./components/mediator'); var _ = require('underscore'); var Player = function Player(options) { $traceurRuntime.superCall(this, $Player.prototype, "constructor", [options]); window.p = this; this.options = options; this.options.sources = this.normalizeSources(options); this.loader = new Loader(this.options.plugins || []); this.coreFactory = new CoreFactory(this, this.loader); options.height || (options.height = 360); options.width || (options.width = 640); }; var $Player = Player; ($traceurRuntime.createClass)(Player, { attachTo: function(element) { this.options.parentElement = element; this.core = this.coreFactory.create(); }, normalizeSources: function(options) { return _.compact(_.flatten([options.source, options.sources])); }, load: function(sources) { this.core.load(sources); }, destroy: function() { this.core.destroy(); }, play: function() { this.core.mediaControl.container.play(); }, pause: function() { this.core.mediaControl.container.pause(); }, stop: function() { this.core.mediaControl.container.stop(); }, seek: function(time) { this.core.mediaControl.container.setCurrentTime(time); }, setVolume: function(volume) { this.core.mediaControl.container.setVolume(volume); }, mute: function() { this.core.mediaControl.container.setVolume(0); }, unmute: function() { this.core.mediaControl.container.setVolume(100); }, isPlaying: function() { return this.core.mediaControl.container.isPlaying(); } }, {}, BaseObject); global.DEBUG = false; window.Clappr = { Player: Player, Mediator: Mediator }; module.exports = window.Clappr; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./base/base_object":"2HNVgz","./components/core_factory":34,"./components/loader":35,"./components/mediator":40,"underscore":7}],45:[function(require,module,exports){ "use strict"; var UIObject = require('../../base/ui_object'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var Mediator = require('../../components/mediator'); var _ = require('underscore'); var $ = require('jquery'); var Browser = require('../../components/browser'); var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-flash-vod=""><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="gpu"> <param name="tabindex" value="1"> </object>'; var Flash = function Flash(options) { $traceurRuntime.superCall(this, $Flash.prototype, "constructor", [options]); console.log("flash plugin"); this.src = options.src; this.isRTMP = !!(this.src.indexOf("rtmp") > -1); this.swfPath = options.swfPath || "http://cdn.clappr.io/latest/assets/Player.swf"; this.autoPlay = options.autoPlay; this.settings = {default: ['seekbar']}; if (this.isRTMP) { this.settings.left = ["playstop", "volume"]; this.settings.right = ["fullscreen"]; } else { this.settings.left = ["playpause", "position", "duration"]; this.settings.right = ["volume", "fullscreen"]; } this.isReady = false; this.addListeners(); }; var $Flash = Flash; ($traceurRuntime.createClass)(Flash, { get name() { return 'flash'; }, get tagName() { return 'object'; }, get template() { return JST.flash; }, bootstrap: function() { this.el.width = "100%"; this.el.height = "100%"; this.isReady = true; this.trigger('playback:ready', this.name); this.currentState = "IDLE"; this.autoPlay && this.play(); $('<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%" />').insertAfter(this.$el); }, setupFirefox: function() { var $el = this.$('embed'); $el.attr('data-flash', ''); this.setElement($el[0]); }, isHighDefinitionInUse: function() { return false; }, updateTime: function() { this.trigger('playback:timeupdate', this.el.getPosition(), this.el.getDuration(), this.name); }, addListeners: function() { var $__0 = this; Mediator.on(this.uniqueId + ':progress', (function() { return $__0.progress(); })); Mediator.on(this.uniqueId + ':timeupdate', (function() { return $__0.updateTime(); })); Mediator.on(this.uniqueId + ':statechanged', (function() { return $__0.checkState(); })); Mediator.on(this.uniqueId + ':flashready', (function() { return $__0.bootstrap(); })); }, stopListening: function() { $traceurRuntime.superCall(this, $Flash.prototype, "stopListening", []); Mediator.off(this.uniqueId + ':progress'); Mediator.off(this.uniqueId + ':timeupdate'); Mediator.off(this.uniqueId + ':statechanged'); }, checkState: function() { if (this.currentState !== "PLAYING_BUFFERING" && this.el.getState() === "PLAYING_BUFFERING") { this.trigger('playback:buffering', this.name); this.currentState = "PLAYING_BUFFERING"; } else if (this.currentState === "PLAYING_BUFFERING" && this.el.getState() === "PLAYING") { this.trigger('playback:bufferfull', this.name); this.currentState = "PLAYING"; } else if (this.el.getState() === "IDLE") { this.currentState = "IDLE"; } else if (this.el.getState() === "ENDED") { this.trigger('playback:ended', this.name); this.trigger('playback:timeupdate', 0, this.el.getDuration(), this.name); this.currentState = "ENDED"; } }, progress: function() { if (this.currentState !== "IDLE" && this.currentState !== "ENDED") { this.trigger('playback:progress', 0, this.el.getBytesLoaded(), this.el.getBytesTotal(), this.name); } }, firstPlay: function() { this.currentState = "PLAYING"; this.el.playerPlay(this.src); }, play: function() { if (this.el.getState() === 'PAUSED') { this.currentState = "PLAYING"; this.el.playerResume(); } else if (this.el.getState() !== 'PLAYING') { this.firstPlay(); } this.trigger('playback:play', this.name); }, volume: function(value) { this.el.playerVolume(value); }, pause: function() { this.currentState = "PAUSED"; this.el.playerPause(); }, stop: function() { this.el.playerStop(); this.trigger('playback:timeupdate', 0, this.name); }, isPlaying: function() { return !!(this.isReady && this.currentState === "PLAYING"); }, getDuration: function() { return this.el.getDuration(); }, seek: function(time) { var seekTo = this.el.getDuration() * (time / 100); this.el.playerSeek(seekTo); this.trigger('playback:timeupdate', seekTo, this.el.getDuration(), this.name); if (this.currentState === "PAUSED") { this.pause(); } }, destroy: function() { clearInterval(this.bootstrapId); this.stopListening(); this.$el.remove(); }, setupIE: function() { this.setElement($(_.template(objectIE)({ cid: this.cid, swfPath: this.swfPath }))); }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId })); if (Browser.isFirefox) { this.setupFirefox(); } else if (Browser.isLegacyIE) { this.setupIE(); } this.$el.append(style); return this; } }, {}, UIObject); Flash.canPlay = function(resource) { if (resource.indexOf('rtmp') > -1) { return true; } else if (Browser.isFirefox || Browser.isLegacyIE) { return _.isString(resource) && !!resource.match(/(.*).(mp4|mov|f4v|3gpp|3gp)/); } else { return _.isString(resource) && !!resource.match(/(.*).(mov|f4v|3gpp|3gp)/); } }; module.exports = Flash; },{"../../base/jst":13,"../../base/styler":17,"../../base/ui_object":"8lqCAT","../../components/browser":"195Wj5","../../components/mediator":40,"jquery":3,"underscore":7}],46:[function(require,module,exports){ "use strict"; module.exports = require('./flash'); },{"./flash":45}],47:[function(require,module,exports){ "use strict"; var UIPlugin = require('../../base/ui_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var _ = require("underscore"); var Mediator = require('../../components/mediator'); var Browser = require('../../components/browser'); var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-hls=""><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> </object>'; var HLS = function HLS(options) { $traceurRuntime.superCall(this, $HLS.prototype, "constructor", [options]); this.src = options.src; this.swfPath = options.swfPath || "http://cdn.clappr.io/latest/assets/HLSPlayer.swf"; this.highDefinition = false; this.autoPlay = options.autoPlay; this.defaultSettings = { left: ["playstop", "volume"], default: ['seekbar'], right: ["fullscreen", "hd-indicator"] }; this.settings = _.extend({}, this.defaultSettings); this.addListeners(); }; var $HLS = HLS; ($traceurRuntime.createClass)(HLS, { get name() { return 'hls'; }, get tagName() { return 'object'; }, get template() { return JST.hls; }, get attributes() { return { 'data-hls': '', 'type': 'application/x-shockwave-flash' }; }, addListeners: function() { var $__0 = this; Mediator.on(this.uniqueId + ':flashready', (function() { return $__0.bootstrap(); })); Mediator.on(this.uniqueId + ':timeupdate', (function(params) { return $__0.updateTime(params); })); Mediator.on(this.uniqueId + ':playbackstate', (function(state) { return $__0.setPlaybackState(state); })); Mediator.on(this.uniqueId + ':playbackerror', (function() { return $__0.flashPlaybackError(); })); }, stopListening: function() { $traceurRuntime.superCall(this, $HLS.prototype, "stopListening", []); Mediator.off(this.uniqueId + ':flashready'); Mediator.off(this.uniqueId + ':timeupdate'); Mediator.off(this.uniqueId + ':playbackstate'); Mediator.off(this.uniqueId + ':highdefinition'); Mediator.off(this.uniqueId + ':playbackerror'); }, bootstrap: function() { this.el.width = "100%"; this.el.height = "100%"; this.trigger('playback:ready', this.name); this.currentState = "IDLE"; this.el.globoPlayerSetflushLiveURLCache(true); this.autoPlay && this.play(); }, updateHighDefinition: function(isHD) { this.highDefinition = (isHD === "true"); this.trigger('playback:highdefinitionupdate'); }, updateTime: function(params) { var duration = this.getDuration(); var position = this.el.globoGetPosition(); if (this.playbackType === 'live' && position >= duration) { position = duration; } this.trigger('playback:timeupdate', position, duration, this.name); var previousDVRStatus = this.dvrEnabled; this.dvrEnabled = (this.playbackType === 'live' && duration > 240); if (previousDVRStatus && this.dvrEnabled !== previousDVRStatus) { this.updateSettings(); } else { this.trigger('playback:timeupdate', this.el.globoGetPosition(), duration, this.name); } if (this.dvrEnabled !== previousDvrEnabled) { this.updateSettings(); } }, play: function() { if (this.el.currentState === 'PAUSED') { this.el.globoPlayerResume(); } else { this.firstPlay(); } this.trigger('playback:play', this.name); }, getPlaybackType: function() { if (this.playbackType) return this.playbackType; return null; }, getCurrentBitrate: function() { var currentLevel = this.getLevels()[this.el.globoGetLevel()]; return currentLevel.bitrate; }, getLastProgramDate: function() { var programDate = this.el.globoGetLastProgramDate(); return programDate - 1.08e+7; }, isHighDefinitionInUse: function() { return this.highDefinition; }, getLevels: function() { if (!this.levels || this.levels.length === 0) { this.levels = this.el.globoGetLevels(); } return this.levels; }, setPlaybackState: function(state) { var bufferLength = this.el.globoGetbufferLength(); if (state === "PLAYING_BUFFERING" && bufferLength < 1) { this.trigger('playback:buffering', this.name); this.updatePlaybackType(); } else if (state === "PLAYING") { if ((this.currentState === "PLAYING_BUFFERING" || this.currentState === "IDLE") && bufferLength !== this.lastBufferLength) { this.trigger('playback:bufferfull', this.name); this.updatePlaybackType(); } } else if (state === "IDLE") { this.trigger('playback:ended', this.name); this.trigger('playback:timeupdate', 0, this.el.globoGetDuration(), this.name); this.updatePlaybackType(); } this.lastBufferLength = bufferLength; this.currentState = state; }, updatePlaybackType: function() { if (!this.playbackType) { this.playbackType = this.el.globoGetType(); if (this.playbackType) { this.playbackType = this.playbackType.toLowerCase(); } this.trigger('playback:playbackstate'); } }, firstPlay: function() { this.el.globoPlayerLoad(this.src); this.el.globoPlayerPlay(); }, volume: function(value) { this.el.globoPlayerVolume(value); }, pause: function() { this.el.globoPlayerPause(); }, stop: function() { this.el.globoPlayerStop(); this.trigger('playback:timeupdate', 0, this.name); }, isPlaying: function() { if (this.currentState) { return !!(this.currentState.match(/playing/i)); } return false; }, getDuration: function() { var duration = this.el.globoGetDuration(); if (this.playbackType === 'live') { duration = duration - 10; } return duration; }, seek: function(time) { if (time < 0) { this.el.globoPlayerSeek(time); } else { var duration = this.getDuration(); time = duration * time / 100; if (this.playbackType === 'live' && duration - time < 2) time = -1; this.el.globoPlayerSeek(time); } }, flashPlaybackError: function() { this.trigger('playback:stop'); }, timeUpdate: function(time, duration) { this.trigger('playback:timeupdate', time, duration, this.name); }, destroy: function() { this.stopListening(); this.$el.remove(); }, setupFirefox: function() { var $el = this.$('embed'); $el.attr('data-hls', ''); this.setElement($el[0]); }, setupIE: function() { this.setElement($(_.template(objectIE)({ cid: this.cid, swfPath: this.swfPath }))); }, updateSettings: function() { this.settings = _.extend({}, this.defaultSettings); if (this.playbackType === "vod" || this.dvrEnabled) { this.settings.left = ["playpause", "position", "duration"]; this.settings.default = ["seekbar"]; } this.trigger('playback:settingsupdate', this.name); }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId })); this.$el.append(style); this.el.id = this.cid; if (Browser.isFirefox) { this.setupFirefox(); } else if (Browser.isLegacyIE) { this.setupIE(); } return this; } }, {}, UIPlugin); HLS.canPlay = function(resource) { return !!resource.match(/^http(.*).m3u8/); }; module.exports = HLS; },{"../../base/jst":13,"../../base/styler":17,"../../base/ui_plugin":"Z7u8cr","../../components/browser":"195Wj5","../../components/mediator":40,"underscore":7}],48:[function(require,module,exports){ "use strict"; module.exports = require('./hls'); },{"./hls":47}],49:[function(require,module,exports){ "use strict"; var UIPlugin = require('../../base/ui_plugin'); var HTML5Audio = function HTML5Audio(params) { $traceurRuntime.superCall(this, $HTML5Audio.prototype, "constructor", [params]); this.el.src = params.src; this.settings = { left: ['playpause', 'position', 'duration'], right: ['fullscreen', 'volume'], default: ['seekbar'] }; this.render(); params.autoPlay && this.play(); }; var $HTML5Audio = HTML5Audio; ($traceurRuntime.createClass)(HTML5Audio, { get name() { return 'html5_audio'; }, get tagName() { return 'audio'; }, get events() { return { 'timeupdate': 'timeUpdated', 'ended': 'ended' }; }, bindEvents: function() { this.listenTo(this.container, 'container:play', this.play); this.listenTo(this.container, 'container:pause', this.pause); this.listenTo(this.container, 'container:seek', this.seek); this.listenTo(this.container, 'container:volume', this.volume); this.listenTo(this.container, 'container:stop', this.stop); }, play: function() { this.el.play(); this.trigger('playback:play'); }, pause: function() { this.el.pause(); }, stop: function() { this.pause(); this.el.currentTime = 0; }, volume: function(value) { this.el.volume = value / 100; }, mute: function() { this.el.volume = 0; }, unmute: function() { this.el.volume = 1; }, isMuted: function() { return !!this.el.volume; }, ended: function() { this.trigger('container:timeupdate', 0); }, seek: function(seekBarValue) { var time = this.el.duration * (seekBarValue / 100); this.el.currentTime = time; }, getCurrentTime: function() { return this.el.currentTime; }, getDuration: function() { return this.el.duration; }, isPlaying: function() { return !this.el.paused && !this.el.ended; }, timeUpdated: function() { this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name); }, render: function() { return this; } }, {}, UIPlugin); HTML5Audio.canPlay = function(resource) { return !!resource.match(/(.*).mp3/); }; module.exports = HTML5Audio; },{"../../base/ui_plugin":"Z7u8cr"}],50:[function(require,module,exports){ "use strict"; module.exports = require('./html5_audio'); },{"./html5_audio":49}],51:[function(require,module,exports){ "use strict"; var Playback = require('../../base/playback'); var Styler = require('../../base/styler'); var Browser = require('../../components/browser'); var HTML5Video = function HTML5Video(options) { $traceurRuntime.superCall(this, $HTML5Video.prototype, "constructor", [options]); this.options = options; this.src = options.src; this.el.src = options.src; this.el.loop = options.loop; this.isHLS = !!(this.src.indexOf('m3u8') > -1); this.settings = {default: ['seekbar']}; if (this.isHLS) { this.settings.left = ["playstop", "volume"]; this.settings.right = ["fullscreen"]; } else { this.settings.left = ["playpause", "position", "duration"]; this.settings.right = ["fullscreen", "volume"]; } }; var $HTML5Video = HTML5Video; ($traceurRuntime.createClass)(HTML5Video, { get name() { return 'html5_video'; }, get tagName() { return 'video'; }, get attributes() { return {'data-html5-video': ''}; }, get events() { return { 'timeupdate': 'timeUpdated', 'progress': 'progress', 'ended': 'ended', 'playing': 'playing', 'stalled': 'stalled', 'waiting': 'waiting', 'canplaythrough': 'bufferFull', 'loadedmetadata': 'loadedMetadata' }; }, loadedMetadata: function(e) { this.trigger('playback:loadedmetadata', e.target.duration); }, getPlaybackType: function() { return this.isHLS ? 'live' : 'vod'; }, isHighDefinitionInUse: function() { return false; }, play: function() { this.el.play(); this.trigger('playback:play'); if (this.isHLS) { this.trigger('playback:timeupdate', 1, 1, this.name); } }, pause: function() { this.el.pause(); }, stop: function() { this.pause(); if (this.el.readyState !== 0) { this.el.currentTime = 0; } }, volume: function(value) { this.el.volume = value / 100; }, mute: function() { this.el.volume = 0; }, unmute: function() { this.el.volume = 1; }, isMuted: function() { return !!this.el.volume; }, isPlaying: function() { return !this.el.paused && !this.el.ended; }, ended: function() { this.trigger('playback:ended', this.name); this.trigger('playback:timeupdate', 0, this.el.duration, this.name); }, stalled: function() { if (this.getPlaybackType() === 'vod') { this.trigger('playback:buffering', this.name); } }, waiting: function() { this.trigger('playback:buffering', this.name); }, bufferFull: function() { this.trigger('playback:bufferfull', this.name); }, destroy: function() { this.stop(); this.el.src = ''; this.$el.remove(); }, seek: function(seekBarValue) { var time = this.el.duration * (seekBarValue / 100); this.el.currentTime = time; }, getCurrentTime: function() { return this.el.currentTime; }, getDuration: function() { return this.el.duration; }, timeUpdated: function() { if (!this.isHLS) { this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name); } }, progress: function() { if (!this.el.buffered.length) return; var bufferedPos = 0; for (var i = 0; i < this.el.buffered.length; i++) { if (this.el.currentTime >= this.el.buffered.start(i) && this.el.currentTime <= this.el.buffered.end(i)) { bufferedPos = i; break; } } this.trigger('playback:progress', this.el.buffered.start(bufferedPos), this.el.buffered.end(bufferedPos), this.el.duration, this.name); }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.append(style); this.trigger('playback:ready', this.name); this.options.autoPlay && this.play(); return this; } }, {}, Playback); HTML5Video.canPlay = function(resource) { return (!!resource.match(/(.*).mp4/) || Browser.isSafari || Browser.isMobile || Browser.isWin8App); }; module.exports = HTML5Video; },{"../../base/playback":"VbgHr3","../../base/styler":17,"../../components/browser":"195Wj5"}],52:[function(require,module,exports){ "use strict"; module.exports = require('./html5_video'); },{"./html5_video":51}],53:[function(require,module,exports){ "use strict"; var Playback = require('../base/playback'); var NoOp = function NoOp() { $traceurRuntime.defaultSuperCall(this, $NoOp.prototype, arguments); }; var $NoOp = NoOp; ($traceurRuntime.createClass)(NoOp, {}, {}, Playback); NoOp.canPlay = (function(source) { return true; }); module.exports = NoOp; },{"../base/playback":"VbgHr3"}],54:[function(require,module,exports){ "use strict"; var UIObject = require('../../base/ui_object'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var BackgroundButton = function BackgroundButton(core) { $traceurRuntime.superCall(this, $BackgroundButton.prototype, "constructor", [core]); this.name = "background_button"; this.core = core; this.listenTo(this.core.mediaControl.container, 'container:state:buffering', this.hide); this.listenTo(this.core.mediaControl.container, 'container:state:bufferfull', this.show); this.listenTo(this.core.mediaControl, 'mediacontrol:show', this.show); this.listenTo(this.core.mediaControl, 'mediacontrol:hide', this.hide); this.listenTo(this.core.mediaControl, 'mediacontrol:playing', this.playing); this.listenTo(this.core.mediaControl, 'mediacontrol:notplaying', this.notplaying); if (this.shouldRender()) { this.render(); } }; var $BackgroundButton = BackgroundButton; ($traceurRuntime.createClass)(BackgroundButton, { get template() { return JST.background_button; }, get events() { return {'click .playpause-icon': 'click'}; }, get attributes() { return { 'class': 'background-button', 'data-background-button': '' }; }, shouldRender: function() { var settings = this.core.mediaControl.settings; return settings.default.indexOf('playpause') >= 0 || settings.left.indexOf('playpause') >= 0 || settings.right.indexOf('playpause') >= 0; }, click: function() { this.core.mediaControl.togglePlayPause(); }, show: function() { this.$el.removeClass('hide'); }, hide: function() { this.$el.addClass('hide'); }, playing: function() { this.$el.find('.playpause-icon[data-background-button]').removeClass('paused').addClass('playing'); }, notplaying: function() { this.$el.find('.playpause-icon[data-background-button]').removeClass('playing').addClass('paused'); }, getExternalInterface: function() {}, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); this.core.mediaControl.$el.find('[data-playpause]').hide(); this.core.$el.append(this.$el); return this; } }, {}, UIObject); module.exports = BackgroundButton; },{"../../base/jst":13,"../../base/styler":17,"../../base/ui_object":"8lqCAT"}],55:[function(require,module,exports){ "use strict"; module.exports = require('./background_button'); },{"./background_button":54}],56:[function(require,module,exports){ "use strict"; module.exports = require('./log'); },{"./log":57}],57:[function(require,module,exports){ "use strict"; var $ = require('jquery'); var BOLD = 'font-weight: bold; font-size: 13px;'; var INFO = 'color: green;' + BOLD; var DEBUG = 'color: #222;' + BOLD; var ERROR = 'color: red;' + BOLD; var DEFAULT = ''; $(document).keydown(function(e) { if (e.ctrlKey && e.shiftKey && e.keyCode === 68) { window.DEBUG = !window.DEBUG; } }); var Log = function(klass) { this.klass = klass || 'Logger'; }; Log.info = function(klass, msg) { console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, klass, msg); }; Log.error = function(klass, msg) { console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, klass, msg); }; Log.BLACKLIST = ['mediacontrol:show', 'mediacontrol:hide', 'playback:timeupdate', 'playback:progress', 'container:hover', 'container:timeupdate', 'container:progress']; Log.prototype = { log: function(msg) { this.info(msg); }, info: function(msg) { console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, this.klass, msg); }, error: function(msg) { console.log('%s %cERROR%c [%s] %s', (new Date()).toLocaleTimeString(), ERROR, DEFAULT, this.klass, msg); } }; module.exports = Log; },{"jquery":3}],58:[function(require,module,exports){ "use strict"; module.exports = require('./poster'); },{"./poster":59}],59:[function(require,module,exports){ "use strict"; var UIPlugin = require('../../base/ui_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var $ = require('jquery'); var _ = require('underscore'); var PosterPlugin = function PosterPlugin(options) { $traceurRuntime.superCall(this, $PosterPlugin.prototype, "constructor", [options]); this.options = options; _.defaults(this.options, {disableControlsOnPoster: true}); if (this.options.disableControlsOnPoster) { this.container.disableMediaControl(); } this.render(); this.bindEvents(); }; var $PosterPlugin = PosterPlugin; ($traceurRuntime.createClass)(PosterPlugin, { get name() { return 'poster'; }, get template() { return JST.poster; }, get attributes() { return { 'class': 'player-poster', 'data-poster': '' }; }, get events() { return {'click': 'clicked'}; }, bindEvents: function() { this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:play', this.onPlay); this.listenTo(this.container, 'container:stop', this.onStop); this.listenTo(this.container, 'container:ended', this.onStop); }, onBuffering: function() { this.hidePlayButton(); }, onPlay: function() { this.$el.hide(); if (this.options.disableControlsOnPoster) { this.container.enableMediaControl(); } }, onStop: function() { this.$el.show(); if (this.options.disableControlsOnPoster) { this.container.disableMediaControl(); } if (!this.options.hidePlayButton) { this.showPlayButton(); } }, hidePlayButton: function() { this.$playButton.hide(); }, showPlayButton: function() { this.$el.css({fontSize: this.$el.height()}); this.$playButton.show(); }, clicked: function() { this.container.play(); }, render: function() { var $__0 = this; var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); this.container.$el.append(this.el); this.$el.ready((function() { $__0.$el.css({fontSize: $__0.options.height || $__0.$el.height()}); })); this.$playButton = $(this.$el.find('.play-wrapper')); if (this.options.poster !== undefined) { var imgEl = $('<img data-poster class="poster-background"></img>'); imgEl.attr('src', this.options.poster); this.$el.prepend(imgEl); } return this; } }, {}, UIPlugin); module.exports = PosterPlugin; },{"../../base/jst":13,"../../base/styler":17,"../../base/ui_plugin":"Z7u8cr","jquery":3,"underscore":7}],60:[function(require,module,exports){ "use strict"; module.exports = require('./seek_time'); },{"./seek_time":61}],61:[function(require,module,exports){ "use strict"; var UIObject = require('../../base/ui_object'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var formatTime = require('../../base/utils').formatTime; var $ = require('jquery'); var SeekTime = function SeekTime(core) { $traceurRuntime.superCall(this, $SeekTime.prototype, "constructor", [core]); this.name = 'seek_time'; this.core = core; this.mediaControl = this.core.mediaControl; var type = this.mediaControl.container.getPlaybackType(); if (type && type !== 'live') { this.listenTo(this.mediaControl, 'mediacontrol:mousemove:seekbar', this.showTime); this.listenTo(this.mediaControl, 'mediacontrol:mouseleave:seekbar', this.hideTime); this.render(); } }; var $SeekTime = SeekTime; ($traceurRuntime.createClass)(SeekTime, { get template() { return JST.seek_time; }, get attributes() { return { 'class': 'seek-time hidden', 'data-seek-time': '' }; }, showTime: function(event) { var offsetX = event.pageX - $(event.target).offset().left; var pos = offsetX / $(event.target).width() * 100; pos = Math.min(100, Math.max(pos, 0)); var currentTime = pos * this.mediaControl.container.getDuration() / 100; this.time = formatTime(currentTime); this.$el.css('left', event.pageX - Math.floor((this.$el.width() / 2) + 6)); this.$el.removeClass('hidden'); this.render(); }, hideTime: function(event) { this.$el.addClass('hidden'); }, getExternalInterface: function() {}, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template({time: this.time})); this.$el.append(style); this.core.$el.append(this.el); } }, {}, UIObject); module.exports = SeekTime; },{"../../base/jst":13,"../../base/styler":17,"../../base/ui_object":"8lqCAT","../../base/utils":24,"jquery":3}],62:[function(require,module,exports){ "use strict"; module.exports = require('./spinner_three_bounce'); },{"./spinner_three_bounce":63}],63:[function(require,module,exports){ "use strict"; var UIPlugin = require('../../base/ui_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var SpinnerThreeBouncePlugin = function SpinnerThreeBouncePlugin(options) { $traceurRuntime.superCall(this, $SpinnerThreeBouncePlugin.prototype, "constructor", [options]); this.template = JST[this.name]; this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull); this.listenTo(this.container, 'container:stop', this.onStop); this.render(); }; var $SpinnerThreeBouncePlugin = SpinnerThreeBouncePlugin; ($traceurRuntime.createClass)(SpinnerThreeBouncePlugin, { get name() { return 'spinner_three_bounce'; }, get attributes() { return { 'data-spinner': '', 'class': 'spinner-three-bounce' }; }, onBuffering: function() { this.$el.show(); }, onBufferFull: function() { this.$el.hide(); }, onStop: function() { this.$el.hide(); }, render: function() { this.$el.hide(); this.$el.html(this.template()); var style = Styler.getStyleFor(this.name); this.container.$el.append(style); this.container.$el.append(this.$el); return this; } }, {}, UIPlugin); module.exports = SpinnerThreeBouncePlugin; },{"../../base/jst":13,"../../base/styler":17,"../../base/ui_plugin":"Z7u8cr"}],64:[function(require,module,exports){ "use strict"; module.exports = require('./stats'); },{"./stats":65}],65:[function(require,module,exports){ "use strict"; var BaseObject = require('../../base/base_object'); var $ = require("jquery"); var StatsPlugin = function StatsPlugin(options) { $traceurRuntime.superCall(this, $StatsPlugin.prototype, "constructor", [options]); this.setInitialAttrs(); this.reportInterval = options.reportInterval || 5000; this.state = "IDLE"; this.bindEvents(); }; var $StatsPlugin = StatsPlugin; ($traceurRuntime.createClass)(StatsPlugin, { get name() { return 'stats'; }, bindEvents: function() { this.listenTo(this.container.playback, 'playback:play', this.onPlay); this.listenTo(this.container, 'container:stop', this.onStop); this.listenTo(this.container, 'container:destroyed', this.onStop); this.listenTo(this.container, 'container:setreportinterval', this.setReportInterval); this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull); this.listenTo(this.container, 'container:stats:add', this.onStatsAdd); this.listenTo(this.container.playback, 'playback:stats:add', this.onStatsAdd); }, setReportInterval: function(reportInterval) { this.reportInterval = reportInterval; }, setInitialAttrs: function() { this.firstPlay = true; this.startupTime = 0; this.rebufferingTime = 0; this.watchingTime = 0; this.rebuffers = 0; this.externalMetrics = {}; }, onPlay: function() { this.state = "PLAYING"; this.watchingTimeInit = Date.now(); this.intervalId = setInterval(this.report.bind(this), this.reportInterval); }, onStop: function() { clearInterval(this.intervalId); this.state = "STOPPED"; }, onBuffering: function() { if (this.firstPlay) { this.startupTimeInit = Date.now(); } else { this.rebufferingTimeInit = Date.now(); } this.state = "BUFFERING"; this.rebuffers++; }, onBufferFull: function() { if (this.firstPlay) { this.firstPlay = false; this.startupTime = Date.now() - this.startupTimeInit; this.watchingTimeInit = Date.now(); } else if (!!this.rebufferingTimeInit) { this.rebufferingTime += this.getRebufferingTime(); } this.rebufferingTimeInit = undefined; this.state = "PLAYING"; }, getRebufferingTime: function() { return Date.now() - this.rebufferingTimeInit; }, getWatchingTime: function() { var totalTime = (Date.now() - this.watchingTimeInit); return totalTime - this.rebufferingTime; }, isRebuffering: function() { return !!this.rebufferingTimeInit; }, onStatsAdd: function(metric) { $.extend(this.externalMetrics, metric); }, getStats: function() { var metrics = { startupTime: this.startupTime, rebuffers: this.rebuffers, rebufferingTime: this.isRebuffering() ? this.rebufferingTime + this.getRebufferingTime() : this.rebufferingTime, watchingTime: this.isRebuffering() ? this.getWatchingTime() - this.getRebufferingTime() : this.getWatchingTime() }; $.extend(metrics, this.externalMetrics); return metrics; }, report: function() { var stats = this.getStats(); this.container.statsReport(this.getStats()); } }, {}, BaseObject); module.exports = StatsPlugin; },{"../../base/base_object":"2HNVgz","jquery":3}],66:[function(require,module,exports){ "use strict"; module.exports = require('./watermark'); },{"./watermark":67}],67:[function(require,module,exports){ "use strict"; var UIPlugin = require('../../base/ui_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var WaterMarkPlugin = function WaterMarkPlugin(options) { $traceurRuntime.superCall(this, $WaterMarkPlugin.prototype, "constructor", [options]); this.template = JST[this.name]; this.position = options.position || "bottom-right"; if (options.watermark) { this.imageUrl = options.watermark; this.render(); } else { this.$el.remove(); } }; var $WaterMarkPlugin = WaterMarkPlugin; ($traceurRuntime.createClass)(WaterMarkPlugin, { get name() { return 'watermark'; }, bindEvents: function() { this.listenTo(this.container, 'container:play', this.onPlay); this.listenTo(this.container, 'container:stop', this.onStop); }, onPlay: function() { if (!this.hidden) this.$el.show(); }, onStop: function() { this.$el.hide(); }, render: function() { this.$el.hide(); var templateOptions = { position: this.position, imageUrl: this.imageUrl }; this.$el.html(this.template(templateOptions)); var style = Styler.getStyleFor(this.name); this.container.$el.append(style); this.container.$el.append(this.$el); return this; } }, {}, UIPlugin); module.exports = WaterMarkPlugin; },{"../../base/jst":13,"../../base/styler":17,"../../base/ui_plugin":"Z7u8cr"}]},{},[2,44])
react/src/components/AtomForm/MultiAttachmentsSelect.js
sinfin/folio
import React from 'react' import { connect } from 'react-redux' import { getFiles, makeFilesStatusSelector, makeFilesPaginationSelector, changeFilesPage, makeRawUnselectedFilesForListSelector, makeFilesReactTypeIsImageSelector } from 'ducks/files' import { atomFormPlacementsSelect, atomFormPlacementsUnselect, atomFormPlacementsSort, atomFormPlacementsChangeTitle, atomFormPlacementsChangeAlt } from 'ducks/atoms' import { displayAsThumbsSelector } from 'ducks/display' import MultiSelectComponent from 'components/MultiSelectComponent' class MultiAttachmentsSelect extends React.PureComponent { getFiles = () => { this.props.dispatch(getFiles(this.props.fileType, this.props.filesUrl)) } changeFilesPage = (page) => { this.props.dispatch(changeFilesPage(this.props.fileType, this.props.filesUrl, page)) } onSortEnd = ({ oldIndex, newIndex }) => { this.props.dispatch( atomFormPlacementsSort( this.props.index, this.props.attachmentType.key, oldIndex, newIndex ) ) } onAltChange = (_fileType, filePlacement, alt) => { this.props.dispatch( atomFormPlacementsChangeAlt( this.props.index, this.props.attachmentType.key, filePlacement, alt ) ) } onTitleChange = (_fileType, filePlacement, title) => { this.props.dispatch( atomFormPlacementsChangeTitle( this.props.index, this.props.attachmentType.key, filePlacement, title ) ) } unselectFilePlacement = (_fileType, filePlacement) => { this.props.dispatch( atomFormPlacementsUnselect( this.props.index, this.props.attachmentType.key, filePlacement ) ) } selectFile = (file) => { this.props.dispatch( atomFormPlacementsSelect( this.props.index, this.props.attachmentType.key, file ) ) } render () { return ( <MultiSelectComponent fileType={this.props.fileType} filesUrl={this.props.filesUrl} filesStatus={this.props.filesStatus} fileTypeIsImage={this.props.fileTypeIsImage} getFiles={this.getFiles} filePlacements={this.props.filePlacements} onSortEnd={this.onSortEnd} onAltChange={this.onAltChange} onTitleChange={this.onTitleChange} unselectFilePlacement={this.unselectFilePlacement} unselectedFilesForList={this.props.unselectedFilesForList} displayAsThumbs={this.props.displayAsThumbs} selectFile={this.selectFile} filesPagination={this.props.filesPagination} changeFilesPage={this.changeFilesPage} openFileModal={(file) => this.props.openFileModal(this.props.fileType, this.props.filesUrl, file)} shouldLoadFiles nested /> ) } } const mapStateToProps = (state, props) => { const all = props.atom.record[props.attachmentType.key] const selected = [] const deleted = [] const selectedFileIds = [] if (all && all.length) { all.forEach((placement) => { if (placement._destroy) { deleted.push(placement) } else { selected.push(placement) selectedFileIds.push(String(placement.file_id)) } }) } const fileType = props.attachmentType['file_type'] const filesUrl = props.attachmentType['files_url'] const filePlacements = { selected, deleted, attachmentable: 'foo', placementType: props.attachmentType.key.replace('_attributes', '') } return { fileType, filesUrl, filesStatus: makeFilesStatusSelector(fileType)(state), displayAsThumbs: displayAsThumbsSelector(state), filesPagination: makeFilesPaginationSelector(fileType)(state), fileTypeIsImage: makeFilesReactTypeIsImageSelector(fileType)(state), filePlacements, unselectedFilesForList: makeRawUnselectedFilesForListSelector(fileType, selectedFileIds)(state) } } function mapDispatchToProps (dispatch) { return { dispatch } } export { MultiAttachmentsSelect } export default connect(mapStateToProps, mapDispatchToProps)(MultiAttachmentsSelect)
app/javascript/mastodon/components/admin/Dimension.js
Ryanaka/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import api from 'mastodon/api'; import { FormattedNumber } from 'react-intl'; import { roundTo10 } from 'mastodon/utils/numbers'; import Skeleton from 'mastodon/components/skeleton'; export default class Dimension extends React.PureComponent { static propTypes = { dimension: PropTypes.string.isRequired, start_at: PropTypes.string.isRequired, end_at: PropTypes.string.isRequired, limit: PropTypes.number.isRequired, label: PropTypes.string.isRequired, params: PropTypes.object, }; state = { loading: true, data: null, }; componentDidMount () { const { start_at, end_at, dimension, limit, params } = this.props; api().post('/api/v1/admin/dimensions', { keys: [dimension], start_at, end_at, limit, [dimension]: params }).then(res => { this.setState({ loading: false, data: res.data, }); }).catch(err => { console.error(err); }); } render () { const { label, limit } = this.props; const { loading, data } = this.state; let content; if (loading) { content = ( <table> <tbody> {Array.from(Array(limit)).map((_, i) => ( <tr className='dimension__item' key={i}> <td className='dimension__item__key'> <Skeleton width={100} /> </td> <td className='dimension__item__value'> <Skeleton width={60} /> </td> </tr> ))} </tbody> </table> ); } else { const sum = data[0].data.reduce((sum, cur) => sum + (cur.value * 1), 0); content = ( <table> <tbody> {data[0].data.map(item => ( <tr className='dimension__item' key={item.key}> <td className='dimension__item__key'> <span className={`dimension__item__indicator dimension__item__indicator--${roundTo10(((item.value * 1) / sum) * 100)}`} /> <span title={item.key}>{item.human_key}</span> </td> <td className='dimension__item__value'> {typeof item.human_value !== 'undefined' ? item.human_value : <FormattedNumber value={item.value} />} </td> </tr> ))} </tbody> </table> ); } return ( <div className='dimension'> <h4>{label}</h4> {content} </div> ); } }
src/parser/warlock/affliction/modules/azerite/WrackingBrilliance.js
sMteX/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import StatTracker from 'parser/shared/modules/StatTracker'; import SPELLS from 'common/SPELLS'; import { calculateAzeriteEffects } from 'common/stats'; import { formatPercentage } from 'common/format'; import AzeritePowerStatistic from 'interface/statistics/AzeritePowerStatistic'; import BoringSpellValueText from 'interface/statistics/components/BoringSpellValueText'; import IntellectIcon from 'interface/icons/Intellect'; const wrackingBrillianceStats = traits => traits.reduce((total, rank) => { const [ intellect ] = calculateAzeriteEffects(SPELLS.WRACKING_BRILLIANCE.id, rank); return total + intellect; }, 0); const debug = false; /* Wracking Brilliance: Every other Soul Shard your Agony generates also increases your Intellect by X for 6 sec. */ class WrackingBrilliance extends Analyzer { static dependencies = { statTracker: StatTracker, }; intellect = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrait(SPELLS.WRACKING_BRILLIANCE.id); if (!this.active) { return; } this.intellect = wrackingBrillianceStats(this.selectedCombatant.traitsBySpellId[SPELLS.WRACKING_BRILLIANCE.id]); debug && this.log(`Total bonus from WB: ${this.intellect}`); this.statTracker.add(SPELLS.WRACKING_BRILLIANCE_BUFF.id, { intellect: this.intellect, }); } get uptime() { return this.selectedCombatant.getBuffUptime(SPELLS.WRACKING_BRILLIANCE_BUFF.id) / this.owner.fightDuration; } get averageIntellect() { return (this.uptime * this.intellect).toFixed(0); } statistic() { return ( <AzeritePowerStatistic size="small" tooltip={`Wracking Brilliance grants ${this.intellect} Intellect while active. You had ${formatPercentage(this.uptime)} % uptime on the buff.`} > <BoringSpellValueText spell={SPELLS.WRACKING_BRILLIANCE}> <IntellectIcon /> {this.averageIntellect} <small>average Intellect</small> </BoringSpellValueText> </AzeritePowerStatistic> ); } } export default WrackingBrilliance;
node_modules/@material-ui/core/esm/FormHelperText/FormHelperText.js
pcclarke/civ-techs
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; import _extends from "@babel/runtime/helpers/extends"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import formControlState from '../FormControl/formControlState'; import withFormControlContext from '../FormControl/withFormControlContext'; import withStyles from '../styles/withStyles'; export var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: _extends({ color: theme.palette.text.secondary }, theme.typography.caption, { textAlign: 'left', marginTop: 8, lineHeight: '1em', minHeight: '1em', margin: 0, '&$disabled': { color: theme.palette.text.disabled }, '&$error': { color: theme.palette.error.main } }), /* Styles applied to the root element if `error={true}`. */ error: {}, /* Styles applied to the root element if `disabled={true}`. */ disabled: {}, /* Styles applied to the root element if `margin="dense"`. */ marginDense: { marginTop: 4 }, /* Styles applied to the root element if `variant="filled"` or `variant="outlined"`. */ contained: { margin: '8px 12px 0' }, /* Styles applied to the root element if `focused={true}`. */ focused: {}, /* Styles applied to the root element if `filled={true}`. */ filled: {}, /* Styles applied to the root element if `required={true}`. */ required: {} }; }; var FormHelperText = React.forwardRef(function FormHelperText(props, ref) { var classes = props.classes, classNameProp = props.className, _props$component = props.component, Component = _props$component === void 0 ? 'p' : _props$component, disabled = props.disabled, error = props.error, filled = props.filled, focused = props.focused, margin = props.margin, muiFormControl = props.muiFormControl, required = props.required, variant = props.variant, other = _objectWithoutProperties(props, ["classes", "className", "component", "disabled", "error", "filled", "focused", "margin", "muiFormControl", "required", "variant"]); var fcs = formControlState({ props: props, muiFormControl: muiFormControl, states: ['variant', 'margin', 'disabled', 'error', 'filled', 'focused', 'required'] }); return React.createElement(Component, _extends({ className: clsx(classes.root, (fcs.variant === 'filled' || fcs.variant === 'outlined') && classes.contained, fcs.margin === 'dense' && classes.marginDense, fcs.disabled && classes.disabled, fcs.error && classes.error, fcs.filled && classes.filled, fcs.focused && classes.focused, fcs.required && classes.required, classNameProp), ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? FormHelperText.propTypes = { /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType, /** * If `true`, the helper text should be displayed in a disabled state. */ disabled: PropTypes.bool, /** * If `true`, helper text should be displayed in an error state. */ error: PropTypes.bool, /** * If `true`, the helper text should use filled classes key. */ filled: PropTypes.bool, /** * If `true`, the helper text should use focused classes key. */ focused: PropTypes.bool, /** * If `dense`, will adjust vertical spacing. This is normally obtained via context from * FormControl. */ margin: PropTypes.oneOf(['dense']), /** * @ignore */ muiFormControl: PropTypes.object, /** * If `true`, the helper text should use required classes key. */ required: PropTypes.bool, /** * The variant to use. */ variant: PropTypes.oneOf(['standard', 'outlined', 'filled']) } : void 0; export default withStyles(styles, { name: 'MuiFormHelperText' })(withFormControlContext(FormHelperText));
src/svg-icons/action/record-voice-over.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionRecordVoiceOver = (props) => ( <SvgIcon {...props}> <circle cx="9" cy="9" r="4"/><path d="M9 15c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4zm7.76-9.64l-1.68 1.69c.84 1.18.84 2.71 0 3.89l1.68 1.69c2.02-2.02 2.02-5.07 0-7.27zM20.07 2l-1.63 1.63c2.77 3.02 2.77 7.56 0 10.74L20.07 16c3.9-3.89 3.91-9.95 0-14z"/> </SvgIcon> ); ActionRecordVoiceOver = pure(ActionRecordVoiceOver); ActionRecordVoiceOver.displayName = 'ActionRecordVoiceOver'; ActionRecordVoiceOver.muiName = 'SvgIcon'; export default ActionRecordVoiceOver;
app/components/ToggleOption/index.js
SenyOrg/kekecmed-frontend
/** * * ToggleOption * */ import React from 'react'; import { injectIntl, intlShape } from 'react-intl'; const ToggleOption = ({ value, message, intl }) => ( <option value={value}> {intl.formatMessage(message)} </option> ); ToggleOption.propTypes = { value: React.PropTypes.string.isRequired, message: React.PropTypes.object.isRequired, intl: intlShape.isRequired, }; export default injectIntl(ToggleOption);
admin_tools/media/admin_tools/js/jquery/jquery.min.js
liberation/django-admin-tools
/*! * jQuery JavaScript Library v1.4.2 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Sat Feb 13 22:33:48 2010 -0500 */ (function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i? e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r= j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g, "&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e= true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/, Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&& (d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this, a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b=== "find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this, function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)|| c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded", L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype, "isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+ a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f], d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]=== a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&& !c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari= true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected, parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent= false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n= s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true, applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando]; else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this, a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b=== w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i, cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ", i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ", " ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className= this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i= e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected= c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed"); a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g, function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split("."); k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a), C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!= null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type= e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&& f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive; if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop|| d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this, "events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent= a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y, isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submitBubbles)c.event.special.submit= {setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}}; if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data", e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a, "_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a, d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&& !a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}}, toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector, u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "), function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q]; if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift(); t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D|| g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[]; for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length- 1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}}, relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]= l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[]; h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()}, CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m, g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)}, text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}}, setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h= h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m= m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m=== "="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g, h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition|| !h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m= h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&& q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>"; if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}(); (function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}: function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/, gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length; c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j= {},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a=== "string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode", d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")? a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType=== 1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)? a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d= c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})}, prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b, this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild); return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja, ""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&& this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]|| u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length=== 1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]); return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["", ""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e= c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]? c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja= function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter= Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a, "border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f= a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b= a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!== "string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this}, serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href, global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&& e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)? "&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache=== false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B= false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since", c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E|| d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x); g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status=== 1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b=== "json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional; if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay"); this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a], "olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)}, animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing= j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]); this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration=== "number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]|| c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start; this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now= this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem, e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length|| c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement? function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b= this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle; k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&& f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b); c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a, d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top- f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset": "pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);
ajax/libs/forerunnerdb/1.3.872/fdb-core.min.js
jonobr1/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":6,"../lib/Shim.IE8":30}],2:[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):!1},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)):-1===d.value&&(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):-1===b?(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):!1):(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),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},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)),-1===e&&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)),-1===g&&(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&&-1!==j))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":26,"./Shared":29}],3:[function(a,b,c){"use strict";var d,e;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}(),e=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},b.exports=e},{}],4:[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){this.sharedPathSolver=o,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._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:!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.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(){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.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){return this.find(a,c).filter(b)},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){var c={};return c[this._primaryKey]=a,this.update(c,b)[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;k>j;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;k>j;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;k>j;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(0>k)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;B>w;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 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;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)},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:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,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&&-1===D.indexOf(o)&&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)):!1},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)):-1===f.value&&(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(-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)},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;j>e;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():!1},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){return this._indexByName?this._indexByName[a]:void 0},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;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},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(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}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&&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=p},{"./Condition":5,"./Index2d":9,"./IndexBinaryTree":10,"./IndexHashMap":11,"./KeyValueStore":12,"./Metrics":13,"./Overload":25,"./Path":26,"./ReactorIO":27,"./Shared":29}],5:[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":29}],6:[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):!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.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":7,"./Metrics.js":13,"./Overload":25,"./Shared":29}],7:[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&&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"),d.mixin(j.prototype,"Mixin.Tags"),d.mixin(j.prototype,"Mixin.Events"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Checksum.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.Checksum=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.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._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;d>b;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;d>b;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;e>c;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 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},{"./Checksum.js":3,"./Collection.js":4,"./Metrics.js":13,"./Overload":25,"./Shared":29}],8:[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;n>=e;e++)for(d=p[e],f=0;o>f;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-1!==g[b][d].indexOf(c)&&(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;5>g;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,4>j?j++:(l+=e[k],j=0,k=0);return l},"undefined"!=typeof b&&(b.exports=k)},{}],9:[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:!1,this.unique(b&&b.unique?b.unique:!1),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;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}},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):!1},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):!1},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]),o>=q&&(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":2,"./GeoHash":8,"./Path":26,"./Shared":29}],10:[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:!1,this.unique(b&&b.unique?b.unique:!1),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;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},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):!1},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":2,"./Path":26,"./Shared":29}],11:[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._size=0,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.index.hashed=f,d.finishModule("IndexHashMap"),b.exports=f},{"./Path":26,"./Shared":29}],12:[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=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;c>b;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):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":29}],13:[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":24,"./Shared":29}],14:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],15:[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)}},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;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&&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},{}],16:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,make:function(a){return h.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;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return JSON.parse(a,h.reviver())},jStringify:function(a){return JSON.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},hash:function(a){return JSON.stringify(a)},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"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}},b.exports=d},{"./Overload":25,"./Serialiser":28}],17:[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},{}],18:[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;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._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":25}],19:[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 c>b;case"$lte":return c>=b;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;j>h;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;m>k;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?-1!==c.indexOf(b):(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]]?!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;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},{}],20:[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},{}],21:[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},{}],22:[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.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):!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},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):!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._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;h>g;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;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":25}],23:[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;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},{}],24:[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":26,"./Shared":29}],25:[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,""),-1===f.indexOf("*"))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;d>c;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},{}],26:[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&&-1===b.indexOf("."))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;f>k;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;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":29}],27:[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":29}],28:[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):!1},function(b){return"string"==typeof b&&0===b.indexOf("$date:")?a.convert(new Date(b.substr(6))):void 0}),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):!1},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},{}],29:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.872",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":14,"./Mixin.ChainReactor":15,"./Mixin.Common":16,"./Mixin.Constants":17,"./Mixin.Events":18,"./Mixin.Matching":19,"./Mixin.Sorting":20,"./Mixin.Tags":21,"./Mixin.Triggers":22,"./Mixin.Updating":23,"./Overload":25}],30:[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/material-ui/4.12.2/es/ClickAwayListener/ClickAwayListener.min.js
cdnjs/cdnjs
import*as React from"react";import*as ReactDOM from"react-dom";import PropTypes from"prop-types";import ownerDocument from"../utils/ownerDocument";import useForkRef from"../utils/useForkRef";import useEventCallback from"../utils/useEventCallback";import{elementAcceptingRef,exactProp}from"@material-ui/utils";function mapEventPropToEvent(e){return e.substring(2).toLowerCase()}function clickedRootScrollbar(e){return document.documentElement.clientWidth<e.clientX||document.documentElement.clientHeight<e.clientY}function ClickAwayListener(e){const{children:r,disableReactTree:o=!1,mouseEvent:n="onClick",onClickAway:c,touchEvent:u="onTouchEnd"}=e,s=React.useRef(!1),i=React.useRef(null),a=React.useRef(!1),l=React.useRef(!1);React.useEffect(()=>(setTimeout(()=>{a.current=!0},0),()=>{a.current=!1}),[]);var t=React.useCallback(e=>{i.current=ReactDOM.findDOMNode(e)},[]),e=useForkRef(r.ref,t);const p=useEventCallback(t=>{var n=l.current;if(l.current=!1,a.current&&i.current&&!clickedRootScrollbar(t))if(s.current)s.current=!1;else{let e;if(t.composedPath)e=-1<t.composedPath().indexOf(i.current);else{const r=ownerDocument(i.current);e=!r.documentElement.contains(t.target)||i.current.contains(t.target)}e||!o&&n||c(t)}});t=n=>e=>{l.current=!0;const t=r.props[n];t&&t(e)};const m={ref:e};return!1!==u&&(m[u]=t(u)),React.useEffect(()=>{if(!1!==u){const e=mapEventPropToEvent(u),t=ownerDocument(i.current),n=()=>{s.current=!0};return t.addEventListener(e,p),t.addEventListener("touchmove",n),()=>{t.removeEventListener(e,p),t.removeEventListener("touchmove",n)}}},[p,u]),!1!==n&&(m[n]=t(n)),React.useEffect(()=>{if(!1!==n){const e=mapEventPropToEvent(n),t=ownerDocument(i.current);return t.addEventListener(e,p),()=>{t.removeEventListener(e,p)}}},[p,n]),React.createElement(React.Fragment,null,React.cloneElement(r,m))}"production"!==process.env.NODE_ENV&&(ClickAwayListener.propTypes={children:elementAcceptingRef.isRequired,disableReactTree:PropTypes.bool,mouseEvent:PropTypes.oneOf(["onClick","onMouseDown","onMouseUp",!1]),onClickAway:PropTypes.func.isRequired,touchEvent:PropTypes.oneOf(["onTouchEnd","onTouchStart",!1])}),"production"!==process.env.NODE_ENV&&(ClickAwayListener.propTypes=exactProp(ClickAwayListener.propTypes));export default ClickAwayListener;
src/app.js
JakeGinnivan/Drone
import React from 'react' import ReactDOM from 'react-dom' import { ReduxRouter, routerStateReducer, reduxReactRouter } from 'redux-router' import Routes from './routes' import createHistory from 'history/lib/createBrowserHistory' import drone from './reducers/drone' import { createStore, compose, combineReducers } from 'redux' import { Provider } from 'react-redux' // Grab the state from a global injected into server-generated HTML const initialState = window.__INITIAL_STATE__ const reducer = combineReducers({ router: routerStateReducer, drone }) let store = compose( reduxReactRouter({ createHistory }) //, devTools() )(createStore)(reducer, initialState) ReactDOM.render( <Provider store={store}> <ReduxRouter>{Routes}</ReduxRouter> </Provider>, document.getElementById('container') )
src/js/components/Fields/VolumeControl.js
jaedb/Iris
import React from 'react'; import { throttle } from '../../util/helpers'; export default class VolumeControl extends React.Component { constructor(props) { super(props); this.handleChange = throttle(this.handleChange.bind(this), 100); } handleChange(value) { this.props.onVolumeChange(value, this.props.volume); } render() { const { className, mute, volume, vertical, } = this.props; let sliderClassName = 'slider slider--volume'; if (mute) sliderClassName += ' slider--muted'; return ( <div className={`slider__wrapper slider__wrapper--${vertical ? 'vertical' : 'horiztonal'} ${className}`}> <div className={sliderClassName}> <input className="slider__input" type="range" min="0" max="25" orient={vertical ? 'vertical' : 'horizontal'} value={volume / 4} onChange={(e) => this.handleChange(parseInt(e.target.value) * 4)} /> <div className="slider__track"> <div className="slider__track__progress" style={vertical ? { height: `${volume}%` } : { width: `${volume}%` }} /> </div> </div> </div> ); } }
__benchmarks__/index.js
SamyPesse/aqueduc
import React from 'react'; import Benchmark from 'benchmark'; import * as ReactRedux from 'react-redux'; import createTestStore from '../src/__tests__/utils/createTestStore'; import connect from '../src/connect'; import render from '../src/render'; const suite = new Benchmark.Suite(); @ReactRedux.connect((state, props) => ({ value: state[props.stateKey] || 0 })) @connect( props => props.value < props.max, props => new Promise((resolve, reject) => { setTimeout(() => { props.dispatch({ type: 'set', key: props.stateKey, value: props.value + 1 }); resolve(); }, 10); }) ) class AsyncDeferred extends React.Component { props: { children: React.Node, stateKey: string, value: number, max: number }; render() { return ( <div> {this.props.stateKey}={this.props.value} {this.props.children} </div> ); } } suite.add('Rendering', { defer: true, fn(deferred) { const store = createTestStore(); render(() => ( <ReactRedux.Provider store={store}> <AsyncDeferred stateKey="a" max={10}> <AsyncDeferred stateKey="b" max={10} /> <AsyncDeferred stateKey="c" max={10}> <AsyncDeferred stateKey="d" max={10} /> </AsyncDeferred> </AsyncDeferred> </ReactRedux.Provider> )).then( html => { deferred.resolve(); }, error => { deferred.reject(error); } ); } }); suite .on('cycle', event => { console.log(String(event.target)); }) .on('complete', () => { // console.log(`Fastest is ${this.filter('fastest').map('name')}`); }) .run({ async: true });
modules/TransitionHook.js
apoco/react-router
import React from 'react'; import warning from 'warning'; var { object } = React.PropTypes; var TransitionHook = { contextTypes: { router: object.isRequired }, componentDidMount() { warning( typeof this.routerWillLeave === 'function', 'Components that mixin TransitionHook should have a routerWillLeave method, check %s', this.constructor.displayName || this.constructor.name ); if (this.routerWillLeave) this.context.router.addTransitionHook(this.routerWillLeave); }, componentWillUnmount() { if (this.routerWillLeave) this.context.router.removeTransitionHook(this.routerWillLeave); } }; export default TransitionHook;
tests/SingleList/SingleList.js
appbaseio/reactivebase
import React from 'react'; import { ReactiveBase, SingleList, ReactiveList } from '../../app/app.js'; import {config} from './config'; import renderer from 'react-test-renderer'; function testComponent(cb) { const onData = function(res, err) { cb(res, err); } const component = renderer.create( <ReactiveBase app={config.ReactiveBase.app} credentials={`${config.ReactiveBase.username}:${config.ReactiveBase.password}`} type={config.ReactiveBase.type} > <div className="row"> <div className="col s6 col-xs-6"> <SingleList componentId="CitySensor" dataField={config.mapping.city} title="SingleList" defaultSelected={config.SingleList.defaultSelected} size={100} /> </div> <div className="col s6 col-xs-6"> <ReactiveList componentId="SearchResult" dataField={config.mapping.topic} title="Results" sortBy={config.ReactiveList.sortBy} from={config.ReactiveList.from} size={config.ReactiveList.size} onData={onData} requestOnScroll={true} react={{ 'and': ["CitySensor"] }} /> </div> </div> </ReactiveBase> ); } export var SingleListTest = function() { return new Promise((resolve, reject) => { testComponent(function(res,err) { if (err) { reject(err); } else if (res) { resolve(res); } }); }); }
pages/less.js
simonrose121/portfolio
import React from 'react' import './example.less' import DocumentTitle from 'react-document-title' import { config } from 'config' export default class Less extends React.Component { render () { return ( <DocumentTitle title={`${config.siteTitle} | Hi lessy friends`}> <div> <h1 className="the-less-class" > Hi lessy friends </h1> <div className="less-nav-example"> <h2>Nav example</h2> <ul> <li> <a href="#">Store</a> </li> <li> <a href="#">Help</a> </li> <li> <a href="#">Logout</a> </li> </ul> </div> </div> </DocumentTitle> ) } }
src/container.js
ionutmilica/redux-modal-container
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import * as modalActionCreators from './actions'; class ModalContainer extends React.Component { static defaultProps = { modals: {}, }; render() { const { showModal, hideModal, modals, currentModals } = this.props; if (currentModals.length < 1) { return null; } const { id, props } = currentModals[0]; const Component = modals[id]; return ( <Component {...props} hideModal={() => hideModal(id)} showModal={showModal} /> ); } } export default connect( state => ({ currentModals: state.modals.collection }), dispatch => bindActionCreators(modalActionCreators, dispatch), )(ModalContainer);
node_modules/react-icons/io/locked.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const IoLocked = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m6.7 37.5c-0.9 0-1.7-0.8-1.7-1.7v-16.6c0-0.9 0.8-1.7 1.7-1.7h1.7v-2.4c0-3.3 1.4-6.8 3.4-9s5-3.6 8.2-3.6c3.2 0 6.2 1.4 8.2 3.6s3.4 5.7 3.4 9v2.4h1.7c0.9 0 1.7 0.8 1.7 1.7v16.6c0 0.9-0.8 1.7-1.7 1.7h-26.6z m5.9-22.4v2.4h14.8v-2.4c0-2.1-0.8-4.8-2.2-6.3v0c-1.4-1.5-3.2-2.3-5.2-2.3-2 0-3.8 0.8-5.2 2.3v0c-1.4 1.5-2.2 4.2-2.2 6.3z"/></g> </Icon> ) export default IoLocked
react/features/video-quality/components/Slider.js
gpolitis/jitsi-meet
// @flow import { makeStyles } from '@material-ui/core/styles'; import clsx from 'clsx'; import React from 'react'; import { commonClassName } from '../../base/ui/constants'; type Props = { /** * The 'aria-label' text. */ ariaLabel: string, /** * The maximum value for slider value. */ max: number, /** * The minimum value for slider value. */ min: number, /** * Callback invoked on change. */ onChange: Function, /** * The granularity that the value must adhere to. */ step: number, /** * The current value where the knob is positioned. */ value: number } const useStyles = makeStyles(theme => { // keep the same hight for all elements: // input, input track & fake track(div) const height = 6; const inputTrack = { background: 'transparent', height }; const inputThumb = { background: theme.palette.text01, border: 0, borderRadius: '50%', height: 24, width: 24 }; const focused = { outline: `1px solid ${theme.palette.action03Focus}` }; return { sliderContainer: { cursor: 'pointer', width: '100%', position: 'relative', textAlign: 'center' }, knobContainer: { display: 'flex', justifyContent: 'space-between', marginLeft: 2, marginRight: 2, position: 'absolute', width: '100%' }, knob: { background: theme.palette.text01, borderRadius: '50%', display: 'inline-block', height, width: 6 }, track: { background: theme.palette.ui02, borderRadius: theme.shape.borderRadius / 2, height }, slider: { // Use an additional class here to override global CSS specificity '&.custom-slider': { '-webkit-appearance': 'none', background: 'transparent', height, left: 0, position: 'absolute', top: 0, width: '100%', '&:focus': { // override global styles in order to use our own color outline: 'none !important', '&::-webkit-slider-runnable-track': focused, '&::ms-track': focused, '&::-moz-range-track': focused }, '&::-webkit-slider-runnable-track': { '-webkit-appearance': 'none', ...inputTrack }, '&::-webkit-slider-thumb': { '-webkit-appearance': 'none', position: 'relative', top: -6, ...inputThumb }, '&::ms-track': { ...inputTrack }, '&::-ms-thumb': { ...inputThumb }, '&::-moz-range-track': { ...inputTrack }, '&::-moz-range-thumb': { ...inputThumb } } } }; }); /** * Custom slider. * * @returns {ReactElement} */ function Slider({ ariaLabel, max, min, onChange, step, value }: Props) { const classes = useStyles(); const knobs = [ ...Array(Math.floor((max - min) / step) + 1) ]; return ( <div className = { classes.sliderContainer }> <ul className = { clsx(commonClassName.emptyList, classes.knobContainer) }> {knobs.map((_, i) => ( <li className = { classes.knob } key = { `knob-${i}` } />))} </ul> <div className = { classes.track } /> <input aria-label = { ariaLabel } className = { clsx(classes.slider, 'custom-slider') } max = { max } min = { min } onChange = { onChange } step = { step } type = 'range' value = { value } /> </div> ); } export default Slider;
ajax/libs/yui/3.11.0/datatable-core/datatable-core-coverage.js
brix/cdnjs
if (typeof __coverage__ === 'undefined') { __coverage__ = {}; } if (!__coverage__['build/datatable-core/datatable-core.js']) { __coverage__['build/datatable-core/datatable-core.js'] = {"path":"build/datatable-core/datatable-core.js","s":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"80":0,"81":0,"82":0,"83":0,"84":0,"85":0,"86":0,"87":0,"88":0,"89":0,"90":0,"91":0,"92":0,"93":0,"94":0,"95":0,"96":0,"97":0,"98":0,"99":0,"100":0,"101":0,"102":0,"103":0,"104":0,"105":0,"106":0,"107":0,"108":0,"109":0,"110":0,"111":0,"112":0,"113":0,"114":0,"115":0,"116":0,"117":0,"118":0,"119":0,"120":0,"121":0,"122":0,"123":0,"124":0,"125":0,"126":0,"127":0,"128":0,"129":0,"130":0,"131":0,"132":0,"133":0,"134":0,"135":0,"136":0,"137":0,"138":0,"139":0,"140":0,"141":0,"142":0,"143":0,"144":0,"145":0,"146":0,"147":0,"148":0,"149":0,"150":0,"151":0,"152":0,"153":0,"154":0,"155":0,"156":0,"157":0,"158":0,"159":0,"160":0,"161":0,"162":0},"b":{"1":[0,0],"2":[0,0],"3":[0,0],"4":[0,0],"5":[0,0],"6":[0,0],"7":[0,0],"8":[0,0,0],"9":[0,0],"10":[0,0],"11":[0,0],"12":[0,0],"13":[0,0,0],"14":[0,0],"15":[0,0],"16":[0,0],"17":[0,0],"18":[0,0],"19":[0,0],"20":[0,0],"21":[0,0],"22":[0,0],"23":[0,0,0],"24":[0,0],"25":[0,0],"26":[0,0],"27":[0,0],"28":[0,0],"29":[0,0],"30":[0,0],"31":[0,0,0],"32":[0,0],"33":[0,0],"34":[0,0],"35":[0,0,0],"36":[0,0],"37":[0,0],"38":[0,0],"39":[0,0],"40":[0,0],"41":[0,0],"42":[0,0],"43":[0,0],"44":[0,0],"45":[0,0],"46":[0,0],"47":[0,0],"48":[0,0],"49":[0,0],"50":[0,0],"51":[0,0],"52":[0,0,0],"53":[0,0],"54":[0,0],"55":[0,0],"56":[0,0],"57":[0,0],"58":[0,0],"59":[0,0,0],"60":[0,0],"61":[0,0,0],"62":[0,0],"63":[0,0,0],"64":[0,0],"65":[0,0]},"f":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":26},"end":{"line":1,"column":45}}},"2":{"name":"(anonymous_2)","line":38,"loc":{"start":{"line":38,"column":40},"end":{"line":38,"column":52}}},"3":{"name":"(anonymous_3)","line":231,"loc":{"start":{"line":231,"column":15},"end":{"line":231,"column":31}}},"4":{"name":"(anonymous_4)","line":278,"loc":{"start":{"line":278,"column":15},"end":{"line":278,"column":31}}},"5":{"name":"(anonymous_5)","line":344,"loc":{"start":{"line":344,"column":25},"end":{"line":344,"column":38}}},"6":{"name":"(anonymous_6)","line":357,"loc":{"start":{"line":357,"column":22},"end":{"line":357,"column":35}}},"7":{"name":"(anonymous_7)","line":377,"loc":{"start":{"line":377,"column":28},"end":{"line":377,"column":41}}},"8":{"name":"(anonymous_8)","line":406,"loc":{"start":{"line":406,"column":24},"end":{"line":406,"column":41}}},"9":{"name":"(anonymous_9)","line":429,"loc":{"start":{"line":429,"column":16},"end":{"line":429,"column":28}}},"10":{"name":"(anonymous_10)","line":445,"loc":{"start":{"line":445,"column":17},"end":{"line":445,"column":42}}},"11":{"name":"(anonymous_11)","line":468,"loc":{"start":{"line":468,"column":19},"end":{"line":468,"column":38}}},"12":{"name":"(anonymous_12)","line":480,"loc":{"start":{"line":480,"column":20},"end":{"line":480,"column":35}}},"13":{"name":"(anonymous_13)","line":500,"loc":{"start":{"line":500,"column":18},"end":{"line":500,"column":30}}},"14":{"name":"(anonymous_14)","line":526,"loc":{"start":{"line":526,"column":21},"end":{"line":526,"column":33}}},"15":{"name":"(anonymous_15)","line":544,"loc":{"start":{"line":544,"column":15},"end":{"line":544,"column":27}}},"16":{"name":"(anonymous_16)","line":569,"loc":{"start":{"line":569,"column":23},"end":{"line":569,"column":39}}},"17":{"name":"(anonymous_17)","line":607,"loc":{"start":{"line":607,"column":17},"end":{"line":607,"column":35}}},"18":{"name":"(anonymous_18)","line":653,"loc":{"start":{"line":653,"column":19},"end":{"line":653,"column":38}}},"19":{"name":"process","line":656,"loc":{"start":{"line":656,"column":8},"end":{"line":656,"column":31}}},"20":{"name":"(anonymous_20)","line":704,"loc":{"start":{"line":704,"column":17},"end":{"line":704,"column":32}}},"21":{"name":"copyObj","line":710,"loc":{"start":{"line":710,"column":8},"end":{"line":710,"column":28}}},"22":{"name":"genId","line":736,"loc":{"start":{"line":736,"column":8},"end":{"line":736,"column":29}}},"23":{"name":"process","line":750,"loc":{"start":{"line":750,"column":8},"end":{"line":750,"column":39}}},"24":{"name":"(anonymous_24)","line":806,"loc":{"start":{"line":806,"column":19},"end":{"line":806,"column":34}}},"25":{"name":"(anonymous_25)","line":829,"loc":{"start":{"line":829,"column":14},"end":{"line":829,"column":29}}},"26":{"name":"(anonymous_26)","line":867,"loc":{"start":{"line":867,"column":19},"end":{"line":867,"column":34}}},"27":{"name":"(anonymous_27)","line":872,"loc":{"start":{"line":872,"column":21},"end":{"line":872,"column":39}}},"28":{"name":"(anonymous_28)","line":899,"loc":{"start":{"line":899,"column":20},"end":{"line":899,"column":35}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":915,"column":79}},"2":{"start":{"line":11,"column":0},"end":{"line":24,"column":10}},"3":{"start":{"line":38,"column":0},"end":{"line":38,"column":55}},"4":{"start":{"line":40,"column":0},"end":{"line":199,"column":2}},"5":{"start":{"line":201,"column":0},"end":{"line":912,"column":3}},"6":{"start":{"line":232,"column":8},"end":{"line":232,"column":39}},"7":{"start":{"line":234,"column":8},"end":{"line":242,"column":9}},"8":{"start":{"line":239,"column":12},"end":{"line":239,"column":23}},"9":{"start":{"line":241,"column":12},"end":{"line":241,"column":46}},"10":{"start":{"line":244,"column":8},"end":{"line":246,"column":9}},"11":{"start":{"line":245,"column":12},"end":{"line":245,"column":23}},"12":{"start":{"line":248,"column":8},"end":{"line":248,"column":38}},"13":{"start":{"line":250,"column":8},"end":{"line":259,"column":9}},"14":{"start":{"line":251,"column":12},"end":{"line":251,"column":33}},"15":{"start":{"line":252,"column":12},"end":{"line":252,"column":27}},"16":{"start":{"line":254,"column":12},"end":{"line":256,"column":13}},"17":{"start":{"line":255,"column":16},"end":{"line":255,"column":63}},"18":{"start":{"line":258,"column":12},"end":{"line":258,"column":51}},"19":{"start":{"line":261,"column":8},"end":{"line":261,"column":20}},"20":{"start":{"line":279,"column":8},"end":{"line":279,"column":78}},"21":{"start":{"line":281,"column":8},"end":{"line":290,"column":9}},"22":{"start":{"line":282,"column":12},"end":{"line":284,"column":13}},"23":{"start":{"line":283,"column":16},"end":{"line":283,"column":46}},"24":{"start":{"line":287,"column":12},"end":{"line":289,"column":13}},"25":{"start":{"line":288,"column":16},"end":{"line":288,"column":73}},"26":{"start":{"line":292,"column":8},"end":{"line":292,"column":30}},"27":{"start":{"line":345,"column":8},"end":{"line":345,"column":37}},"28":{"start":{"line":358,"column":8},"end":{"line":358,"column":33}},"29":{"start":{"line":360,"column":8},"end":{"line":360,"column":29}},"30":{"start":{"line":362,"column":8},"end":{"line":366,"column":9}},"31":{"start":{"line":365,"column":12},"end":{"line":365,"column":32}},"32":{"start":{"line":378,"column":8},"end":{"line":378,"column":38}},"33":{"start":{"line":380,"column":8},"end":{"line":380,"column":35}},"34":{"start":{"line":382,"column":8},"end":{"line":382,"column":30}},"35":{"start":{"line":384,"column":8},"end":{"line":390,"column":9}},"36":{"start":{"line":385,"column":12},"end":{"line":389,"column":13}},"37":{"start":{"line":386,"column":16},"end":{"line":386,"column":36}},"38":{"start":{"line":388,"column":16},"end":{"line":388,"column":58}},"39":{"start":{"line":407,"column":8},"end":{"line":407,"column":26}},"40":{"start":{"line":409,"column":8},"end":{"line":417,"column":9}},"41":{"start":{"line":410,"column":12},"end":{"line":410,"column":23}},"42":{"start":{"line":412,"column":12},"end":{"line":414,"column":13}},"43":{"start":{"line":413,"column":16},"end":{"line":413,"column":37}},"44":{"start":{"line":415,"column":15},"end":{"line":417,"column":9}},"45":{"start":{"line":416,"column":12},"end":{"line":416,"column":26}},"46":{"start":{"line":419,"column":8},"end":{"line":419,"column":76}},"47":{"start":{"line":430,"column":8},"end":{"line":430,"column":72}},"48":{"start":{"line":449,"column":8},"end":{"line":449,"column":59}},"49":{"start":{"line":469,"column":8},"end":{"line":469,"column":63}},"50":{"start":{"line":487,"column":8},"end":{"line":487,"column":53}},"51":{"start":{"line":501,"column":8},"end":{"line":502,"column":17}},"52":{"start":{"line":505,"column":8},"end":{"line":514,"column":9}},"53":{"start":{"line":507,"column":12},"end":{"line":507,"column":37}},"54":{"start":{"line":509,"column":12},"end":{"line":511,"column":13}},"55":{"start":{"line":510,"column":16},"end":{"line":510,"column":37}},"56":{"start":{"line":513,"column":12},"end":{"line":513,"column":44}},"57":{"start":{"line":516,"column":8},"end":{"line":516,"column":36}},"58":{"start":{"line":527,"column":8},"end":{"line":531,"column":11}},"59":{"start":{"line":545,"column":8},"end":{"line":547,"column":42}},"60":{"start":{"line":549,"column":8},"end":{"line":551,"column":9}},"61":{"start":{"line":550,"column":12},"end":{"line":550,"column":41}},"62":{"start":{"line":553,"column":8},"end":{"line":553,"column":25}},"63":{"start":{"line":570,"column":8},"end":{"line":570,"column":23}},"64":{"start":{"line":572,"column":8},"end":{"line":596,"column":9}},"65":{"start":{"line":573,"column":12},"end":{"line":573,"column":48}},"66":{"start":{"line":575,"column":12},"end":{"line":589,"column":13}},"67":{"start":{"line":576,"column":16},"end":{"line":576,"column":33}},"68":{"start":{"line":578,"column":16},"end":{"line":580,"column":17}},"69":{"start":{"line":579,"column":20},"end":{"line":579,"column":49}},"70":{"start":{"line":584,"column":16},"end":{"line":584,"column":46}},"71":{"start":{"line":586,"column":16},"end":{"line":588,"column":17}},"72":{"start":{"line":587,"column":20},"end":{"line":587,"column":49}},"73":{"start":{"line":595,"column":12},"end":{"line":595,"column":38}},"74":{"start":{"line":608,"column":8},"end":{"line":610,"column":23}},"75":{"start":{"line":614,"column":8},"end":{"line":614,"column":37}},"76":{"start":{"line":620,"column":8},"end":{"line":633,"column":9}},"77":{"start":{"line":621,"column":12},"end":{"line":622,"column":51}},"78":{"start":{"line":624,"column":12},"end":{"line":628,"column":13}},"79":{"start":{"line":625,"column":16},"end":{"line":625,"column":49}},"80":{"start":{"line":626,"column":19},"end":{"line":628,"column":13}},"81":{"start":{"line":627,"column":16},"end":{"line":627,"column":40}},"82":{"start":{"line":630,"column":12},"end":{"line":632,"column":13}},"83":{"start":{"line":631,"column":16},"end":{"line":631,"column":45}},"84":{"start":{"line":635,"column":8},"end":{"line":635,"column":28}},"85":{"start":{"line":637,"column":8},"end":{"line":637,"column":32}},"86":{"start":{"line":639,"column":8},"end":{"line":639,"column":31}},"87":{"start":{"line":654,"column":8},"end":{"line":654,"column":21}},"88":{"start":{"line":656,"column":8},"end":{"line":679,"column":9}},"89":{"start":{"line":657,"column":12},"end":{"line":657,"column":33}},"90":{"start":{"line":659,"column":12},"end":{"line":678,"column":13}},"91":{"start":{"line":660,"column":16},"end":{"line":660,"column":30}},"92":{"start":{"line":661,"column":16},"end":{"line":661,"column":30}},"93":{"start":{"line":668,"column":16},"end":{"line":670,"column":17}},"94":{"start":{"line":669,"column":20},"end":{"line":669,"column":35}},"95":{"start":{"line":673,"column":16},"end":{"line":673,"column":35}},"96":{"start":{"line":675,"column":16},"end":{"line":677,"column":17}},"97":{"start":{"line":676,"column":20},"end":{"line":676,"column":42}},"98":{"start":{"line":681,"column":8},"end":{"line":681,"column":25}},"99":{"start":{"line":683,"column":8},"end":{"line":683,"column":30}},"100":{"start":{"line":705,"column":8},"end":{"line":708,"column":41}},"101":{"start":{"line":710,"column":8},"end":{"line":734,"column":9}},"102":{"start":{"line":711,"column":12},"end":{"line":712,"column":28}},"103":{"start":{"line":714,"column":12},"end":{"line":714,"column":26}},"104":{"start":{"line":715,"column":12},"end":{"line":715,"column":35}},"105":{"start":{"line":717,"column":12},"end":{"line":731,"column":13}},"106":{"start":{"line":718,"column":16},"end":{"line":730,"column":17}},"107":{"start":{"line":719,"column":20},"end":{"line":719,"column":33}},"108":{"start":{"line":721,"column":20},"end":{"line":729,"column":21}},"109":{"start":{"line":722,"column":24},"end":{"line":722,"column":48}},"110":{"start":{"line":723,"column":27},"end":{"line":729,"column":21}},"111":{"start":{"line":724,"column":24},"end":{"line":724,"column":51}},"112":{"start":{"line":726,"column":24},"end":{"line":726,"column":77}},"113":{"start":{"line":728,"column":24},"end":{"line":728,"column":43}},"114":{"start":{"line":733,"column":12},"end":{"line":733,"column":24}},"115":{"start":{"line":736,"column":8},"end":{"line":748,"column":9}},"116":{"start":{"line":739,"column":12},"end":{"line":739,"column":44}},"117":{"start":{"line":741,"column":12},"end":{"line":745,"column":13}},"118":{"start":{"line":742,"column":16},"end":{"line":742,"column":39}},"119":{"start":{"line":744,"column":16},"end":{"line":744,"column":31}},"120":{"start":{"line":747,"column":12},"end":{"line":747,"column":24}},"121":{"start":{"line":750,"column":8},"end":{"line":789,"column":9}},"122":{"start":{"line":751,"column":12},"end":{"line":752,"column":34}},"123":{"start":{"line":754,"column":12},"end":{"line":786,"column":13}},"124":{"start":{"line":755,"column":16},"end":{"line":756,"column":78}},"125":{"start":{"line":758,"column":16},"end":{"line":758,"column":36}},"126":{"start":{"line":761,"column":16},"end":{"line":765,"column":17}},"127":{"start":{"line":764,"column":20},"end":{"line":764,"column":34}},"128":{"start":{"line":766,"column":16},"end":{"line":770,"column":17}},"129":{"start":{"line":769,"column":20},"end":{"line":769,"column":41}},"130":{"start":{"line":772,"column":16},"end":{"line":776,"column":17}},"131":{"start":{"line":773,"column":20},"end":{"line":773,"column":41}},"132":{"start":{"line":775,"column":20},"end":{"line":775,"column":39}},"133":{"start":{"line":781,"column":16},"end":{"line":781,"column":63}},"134":{"start":{"line":783,"column":16},"end":{"line":785,"column":17}},"135":{"start":{"line":784,"column":20},"end":{"line":784,"column":62}},"136":{"start":{"line":788,"column":12},"end":{"line":788,"column":27}},"137":{"start":{"line":791,"column":8},"end":{"line":791,"column":35}},"138":{"start":{"line":807,"column":8},"end":{"line":807,"column":33}},"139":{"start":{"line":809,"column":8},"end":{"line":809,"column":44}},"140":{"start":{"line":830,"column":8},"end":{"line":832,"column":9}},"141":{"start":{"line":831,"column":12},"end":{"line":831,"column":21}},"142":{"start":{"line":834,"column":8},"end":{"line":850,"column":9}},"143":{"start":{"line":835,"column":12},"end":{"line":835,"column":37}},"144":{"start":{"line":841,"column":12},"end":{"line":841,"column":51}},"145":{"start":{"line":846,"column":12},"end":{"line":846,"column":28}},"146":{"start":{"line":847,"column":15},"end":{"line":850,"column":9}},"147":{"start":{"line":849,"column":12},"end":{"line":849,"column":26}},"148":{"start":{"line":852,"column":8},"end":{"line":852,"column":19}},"149":{"start":{"line":868,"column":8},"end":{"line":868,"column":17}},"150":{"start":{"line":870,"column":8},"end":{"line":876,"column":9}},"151":{"start":{"line":871,"column":12},"end":{"line":871,"column":22}},"152":{"start":{"line":872,"column":12},"end":{"line":874,"column":15}},"153":{"start":{"line":873,"column":16},"end":{"line":873,"column":46}},"154":{"start":{"line":875,"column":12},"end":{"line":875,"column":23}},"155":{"start":{"line":878,"column":8},"end":{"line":878,"column":30}},"156":{"start":{"line":880,"column":8},"end":{"line":880,"column":19}},"157":{"start":{"line":900,"column":8},"end":{"line":900,"column":23}},"158":{"start":{"line":903,"column":8},"end":{"line":907,"column":9}},"159":{"start":{"line":904,"column":12},"end":{"line":904,"column":29}},"160":{"start":{"line":905,"column":15},"end":{"line":907,"column":9}},"161":{"start":{"line":906,"column":12},"end":{"line":906,"column":54}},"162":{"start":{"line":909,"column":8},"end":{"line":909,"column":37}}},"branchMap":{"1":{"line":234,"type":"if","locations":[{"start":{"line":234,"column":8},"end":{"line":234,"column":8}},{"start":{"line":234,"column":8},"end":{"line":234,"column":8}}]},"2":{"line":234,"type":"binary-expr","locations":[{"start":{"line":234,"column":12},"end":{"line":234,"column":26}},{"start":{"line":234,"column":30},"end":{"line":234,"column":44}}]},"3":{"line":244,"type":"if","locations":[{"start":{"line":244,"column":8},"end":{"line":244,"column":8}},{"start":{"line":244,"column":8},"end":{"line":244,"column":8}}]},"4":{"line":250,"type":"if","locations":[{"start":{"line":250,"column":8},"end":{"line":250,"column":8}},{"start":{"line":250,"column":8},"end":{"line":250,"column":8}}]},"5":{"line":250,"type":"binary-expr","locations":[{"start":{"line":250,"column":12},"end":{"line":250,"column":26}},{"start":{"line":250,"column":30},"end":{"line":250,"column":43}}]},"6":{"line":254,"type":"binary-expr","locations":[{"start":{"line":254,"column":47},"end":{"line":254,"column":51}},{"start":{"line":254,"column":55},"end":{"line":254,"column":62}}]},"7":{"line":255,"type":"binary-expr","locations":[{"start":{"line":255,"column":23},"end":{"line":255,"column":36}},{"start":{"line":255,"column":40},"end":{"line":255,"column":62}}]},"8":{"line":258,"type":"binary-expr","locations":[{"start":{"line":258,"column":20},"end":{"line":258,"column":24}},{"start":{"line":258,"column":28},"end":{"line":258,"column":41}},{"start":{"line":258,"column":46},"end":{"line":258,"column":50}}]},"9":{"line":279,"type":"binary-expr","locations":[{"start":{"line":279,"column":21},"end":{"line":279,"column":44}},{"start":{"line":279,"column":48},"end":{"line":279,"column":77}}]},"10":{"line":281,"type":"if","locations":[{"start":{"line":281,"column":8},"end":{"line":281,"column":8}},{"start":{"line":281,"column":8},"end":{"line":281,"column":8}}]},"11":{"line":282,"type":"if","locations":[{"start":{"line":282,"column":12},"end":{"line":282,"column":12}},{"start":{"line":282,"column":12},"end":{"line":282,"column":12}}]},"12":{"line":287,"type":"if","locations":[{"start":{"line":287,"column":12},"end":{"line":287,"column":12}},{"start":{"line":287,"column":12},"end":{"line":287,"column":12}}]},"13":{"line":287,"type":"binary-expr","locations":[{"start":{"line":287,"column":16},"end":{"line":287,"column":23}},{"start":{"line":287,"column":27},"end":{"line":287,"column":36}},{"start":{"line":287,"column":40},"end":{"line":287,"column":59}}]},"14":{"line":292,"type":"binary-expr","locations":[{"start":{"line":292,"column":15},"end":{"line":292,"column":21}},{"start":{"line":292,"column":25},"end":{"line":292,"column":29}}]},"15":{"line":362,"type":"if","locations":[{"start":{"line":362,"column":8},"end":{"line":362,"column":8}},{"start":{"line":362,"column":8},"end":{"line":362,"column":8}}]},"16":{"line":362,"type":"binary-expr","locations":[{"start":{"line":362,"column":12},"end":{"line":362,"column":32}},{"start":{"line":362,"column":36},"end":{"line":362,"column":52}}]},"17":{"line":384,"type":"if","locations":[{"start":{"line":384,"column":8},"end":{"line":384,"column":8}},{"start":{"line":384,"column":8},"end":{"line":384,"column":8}}]},"18":{"line":384,"type":"binary-expr","locations":[{"start":{"line":384,"column":12},"end":{"line":384,"column":32}},{"start":{"line":384,"column":36},"end":{"line":384,"column":40}}]},"19":{"line":385,"type":"if","locations":[{"start":{"line":385,"column":12},"end":{"line":385,"column":12}},{"start":{"line":385,"column":12},"end":{"line":385,"column":12}}]},"20":{"line":409,"type":"if","locations":[{"start":{"line":409,"column":8},"end":{"line":409,"column":8}},{"start":{"line":409,"column":8},"end":{"line":409,"column":8}}]},"21":{"line":415,"type":"if","locations":[{"start":{"line":415,"column":15},"end":{"line":415,"column":15}},{"start":{"line":415,"column":15},"end":{"line":415,"column":15}}]},"22":{"line":449,"type":"cond-expr","locations":[{"start":{"line":449,"column":33},"end":{"line":449,"column":48}},{"start":{"line":449,"column":51},"end":{"line":449,"column":58}}]},"23":{"line":487,"type":"binary-expr","locations":[{"start":{"line":487,"column":15},"end":{"line":487,"column":18}},{"start":{"line":487,"column":23},"end":{"line":487,"column":32}},{"start":{"line":487,"column":36},"end":{"line":487,"column":51}}]},"24":{"line":501,"type":"binary-expr","locations":[{"start":{"line":501,"column":22},"end":{"line":501,"column":41}},{"start":{"line":501,"column":45},"end":{"line":501,"column":47}}]},"25":{"line":505,"type":"if","locations":[{"start":{"line":505,"column":8},"end":{"line":505,"column":8}},{"start":{"line":505,"column":8},"end":{"line":505,"column":8}}]},"26":{"line":505,"type":"binary-expr","locations":[{"start":{"line":505,"column":12},"end":{"line":505,"column":27}},{"start":{"line":505,"column":31},"end":{"line":505,"column":47}}]},"27":{"line":509,"type":"if","locations":[{"start":{"line":509,"column":12},"end":{"line":509,"column":12}},{"start":{"line":509,"column":12},"end":{"line":509,"column":12}}]},"28":{"line":549,"type":"if","locations":[{"start":{"line":549,"column":8},"end":{"line":549,"column":8}},{"start":{"line":549,"column":8},"end":{"line":549,"column":8}}]},"29":{"line":572,"type":"if","locations":[{"start":{"line":572,"column":8},"end":{"line":572,"column":8}},{"start":{"line":572,"column":8},"end":{"line":572,"column":8}}]},"30":{"line":575,"type":"if","locations":[{"start":{"line":575,"column":12},"end":{"line":575,"column":12}},{"start":{"line":575,"column":12},"end":{"line":575,"column":12}}]},"31":{"line":575,"type":"binary-expr","locations":[{"start":{"line":575,"column":16},"end":{"line":575,"column":20}},{"start":{"line":575,"column":24},"end":{"line":575,"column":33}},{"start":{"line":575,"column":37},"end":{"line":575,"column":48}}]},"32":{"line":578,"type":"if","locations":[{"start":{"line":578,"column":16},"end":{"line":578,"column":16}},{"start":{"line":578,"column":16},"end":{"line":578,"column":16}}]},"33":{"line":586,"type":"if","locations":[{"start":{"line":586,"column":16},"end":{"line":586,"column":16}},{"start":{"line":586,"column":16},"end":{"line":586,"column":16}}]},"34":{"line":620,"type":"if","locations":[{"start":{"line":620,"column":8},"end":{"line":620,"column":8}},{"start":{"line":620,"column":8},"end":{"line":620,"column":8}}]},"35":{"line":621,"type":"binary-expr","locations":[{"start":{"line":621,"column":26},"end":{"line":621,"column":43}},{"start":{"line":621,"column":47},"end":{"line":621,"column":72}},{"start":{"line":622,"column":28},"end":{"line":622,"column":50}}]},"36":{"line":624,"type":"if","locations":[{"start":{"line":624,"column":12},"end":{"line":624,"column":12}},{"start":{"line":624,"column":12},"end":{"line":624,"column":12}}]},"37":{"line":626,"type":"if","locations":[{"start":{"line":626,"column":19},"end":{"line":626,"column":19}},{"start":{"line":626,"column":19},"end":{"line":626,"column":19}}]},"38":{"line":626,"type":"binary-expr","locations":[{"start":{"line":626,"column":23},"end":{"line":626,"column":36}},{"start":{"line":626,"column":40},"end":{"line":626,"column":51}}]},"39":{"line":630,"type":"if","locations":[{"start":{"line":630,"column":12},"end":{"line":630,"column":12}},{"start":{"line":630,"column":12},"end":{"line":630,"column":12}}]},"40":{"line":668,"type":"if","locations":[{"start":{"line":668,"column":16},"end":{"line":668,"column":16}},{"start":{"line":668,"column":16},"end":{"line":668,"column":16}}]},"41":{"line":668,"type":"binary-expr","locations":[{"start":{"line":668,"column":20},"end":{"line":668,"column":23}},{"start":{"line":668,"column":27},"end":{"line":668,"column":36}}]},"42":{"line":675,"type":"if","locations":[{"start":{"line":675,"column":16},"end":{"line":675,"column":16}},{"start":{"line":675,"column":16},"end":{"line":675,"column":16}}]},"43":{"line":718,"type":"if","locations":[{"start":{"line":718,"column":16},"end":{"line":718,"column":16}},{"start":{"line":718,"column":16},"end":{"line":718,"column":16}}]},"44":{"line":721,"type":"if","locations":[{"start":{"line":721,"column":20},"end":{"line":721,"column":20}},{"start":{"line":721,"column":20},"end":{"line":721,"column":20}}]},"45":{"line":723,"type":"if","locations":[{"start":{"line":723,"column":27},"end":{"line":723,"column":27}},{"start":{"line":723,"column":27},"end":{"line":723,"column":27}}]},"46":{"line":726,"type":"cond-expr","locations":[{"start":{"line":726,"column":47},"end":{"line":726,"column":59}},{"start":{"line":726,"column":62},"end":{"line":726,"column":76}}]},"47":{"line":741,"type":"if","locations":[{"start":{"line":741,"column":12},"end":{"line":741,"column":12}},{"start":{"line":741,"column":12},"end":{"line":741,"column":12}}]},"48":{"line":756,"type":"cond-expr","locations":[{"start":{"line":756,"column":42},"end":{"line":756,"column":58}},{"start":{"line":756,"column":61},"end":{"line":756,"column":77}}]},"49":{"line":761,"type":"if","locations":[{"start":{"line":761,"column":16},"end":{"line":761,"column":16}},{"start":{"line":761,"column":16},"end":{"line":761,"column":16}}]},"50":{"line":766,"type":"if","locations":[{"start":{"line":766,"column":16},"end":{"line":766,"column":16}},{"start":{"line":766,"column":16},"end":{"line":766,"column":16}}]},"51":{"line":772,"type":"if","locations":[{"start":{"line":772,"column":16},"end":{"line":772,"column":16}},{"start":{"line":772,"column":16},"end":{"line":772,"column":16}}]},"52":{"line":781,"type":"binary-expr","locations":[{"start":{"line":781,"column":32},"end":{"line":781,"column":40}},{"start":{"line":781,"column":44},"end":{"line":781,"column":51}},{"start":{"line":781,"column":55},"end":{"line":781,"column":61}}]},"53":{"line":783,"type":"if","locations":[{"start":{"line":783,"column":16},"end":{"line":783,"column":16}},{"start":{"line":783,"column":16},"end":{"line":783,"column":16}}]},"54":{"line":791,"type":"binary-expr","locations":[{"start":{"line":791,"column":15},"end":{"line":791,"column":18}},{"start":{"line":791,"column":22},"end":{"line":791,"column":34}}]},"55":{"line":809,"type":"cond-expr","locations":[{"start":{"line":809,"column":30},"end":{"line":809,"column":33}},{"start":{"line":809,"column":36},"end":{"line":809,"column":43}}]},"56":{"line":830,"type":"if","locations":[{"start":{"line":830,"column":8},"end":{"line":830,"column":8}},{"start":{"line":830,"column":8},"end":{"line":830,"column":8}}]},"57":{"line":834,"type":"if","locations":[{"start":{"line":834,"column":8},"end":{"line":834,"column":8}},{"start":{"line":834,"column":8},"end":{"line":834,"column":8}}]},"58":{"line":847,"type":"if","locations":[{"start":{"line":847,"column":15},"end":{"line":847,"column":15}},{"start":{"line":847,"column":15},"end":{"line":847,"column":15}}]},"59":{"line":847,"type":"binary-expr","locations":[{"start":{"line":847,"column":19},"end":{"line":847,"column":23}},{"start":{"line":847,"column":27},"end":{"line":847,"column":36}},{"start":{"line":847,"column":40},"end":{"line":847,"column":51}}]},"60":{"line":870,"type":"if","locations":[{"start":{"line":870,"column":8},"end":{"line":870,"column":8}},{"start":{"line":870,"column":8},"end":{"line":870,"column":8}}]},"61":{"line":870,"type":"binary-expr","locations":[{"start":{"line":870,"column":12},"end":{"line":870,"column":15}},{"start":{"line":870,"column":19},"end":{"line":870,"column":30}},{"start":{"line":870,"column":34},"end":{"line":870,"column":60}}]},"62":{"line":903,"type":"if","locations":[{"start":{"line":903,"column":8},"end":{"line":903,"column":8}},{"start":{"line":903,"column":8},"end":{"line":903,"column":8}}]},"63":{"line":903,"type":"binary-expr","locations":[{"start":{"line":903,"column":12},"end":{"line":903,"column":27}},{"start":{"line":903,"column":31},"end":{"line":903,"column":51}},{"start":{"line":903,"column":55},"end":{"line":903,"column":77}}]},"64":{"line":905,"type":"if","locations":[{"start":{"line":905,"column":15},"end":{"line":905,"column":15}},{"start":{"line":905,"column":15},"end":{"line":905,"column":15}}]},"65":{"line":909,"type":"binary-expr","locations":[{"start":{"line":909,"column":15},"end":{"line":909,"column":25}},{"start":{"line":909,"column":29},"end":{"line":909,"column":36}}]}},"code":["(function () { YUI.add('datatable-core', function (Y, NAME) {","","/**","The core implementation of the `DataTable` and `DataTable.Base` Widgets.","","@module datatable","@submodule datatable-core","@since 3.5.0","**/","","var INVALID = Y.Attribute.INVALID_VALUE,",""," Lang = Y.Lang,"," isFunction = Lang.isFunction,"," isObject = Lang.isObject,"," isArray = Lang.isArray,"," isString = Lang.isString,"," isNumber = Lang.isNumber,",""," toArray = Y.Array,",""," keys = Y.Object.keys,",""," Table;"," ","/**","_API docs for this extension are included in the DataTable class._","","Class extension providing the core API and structure for the DataTable Widget.","","Use this class extension with Widget or another Base-based superclass to create","the basic DataTable model API and composing class structure.","","@class DataTable.Core","@for DataTable","@since 3.5.0","**/","Table = Y.namespace('DataTable').Core = function () {};","","Table.ATTRS = {"," /**"," Columns to include in the rendered table."," "," If omitted, the attributes on the configured `recordType` or the first item"," in the `data` collection will be used as a source.",""," This attribute takes an array of strings or objects (mixing the two is"," fine). Each string or object is considered a column to be rendered."," Strings are converted to objects, so `columns: ['first', 'last']` becomes"," `columns: [{ key: 'first' }, { key: 'last' }]`.",""," DataTable.Core only concerns itself with a few properties of columns."," These properties are:",""," * `key` - Used to identify the record field/attribute containing content for"," this column. Also used to create a default Model if no `recordType` or"," `data` are provided during construction. If `name` is not specified, this"," is assigned to the `_id` property (with added incrementer if the key is"," used by multiple columns)."," * `children` - Traversed to initialize nested column objects"," * `name` - Used in place of, or in addition to, the `key`. Useful for"," columns that aren't bound to a field/attribute in the record data. This"," is assigned to the `_id` property."," * `id` - For backward compatibility. Implementers can specify the id of"," the header cell. This should be avoided, if possible, to avoid the"," potential for creating DOM elements with duplicate IDs."," * `field` - For backward compatibility. Implementers should use `name`."," * `_id` - Assigned unique-within-this-instance id for a column. By order"," of preference, assumes the value of `name`, `key`, `id`, or `_yuid`."," This is used by the rendering views as well as feature module"," as a means to identify a specific column without ambiguity (such as"," multiple columns using the same `key`."," * `_yuid` - Guid stamp assigned to the column object."," * `_parent` - Assigned to all child columns, referencing their parent"," column.",""," @attribute columns"," @type {Object[]|String[]}"," @default (from `recordType` ATTRS or first item in the `data`)"," @since 3.5.0"," **/"," columns: {"," // TODO: change to setter to clone input array/objects"," validator: isArray,"," setter: '_setColumns',"," getter: '_getColumns'"," },",""," /**"," Model subclass to use as the `model` for the ModelList stored in the `data`"," attribute.",""," If not provided, it will try really hard to figure out what to use. The"," following attempts will be made to set a default value:"," "," 1. If the `data` attribute is set with a ModelList instance and its `model`"," property is set, that will be used."," 2. If the `data` attribute is set with a ModelList instance, and its"," `model` property is unset, but it is populated, the `ATTRS` of the"," `constructor of the first item will be used."," 3. If the `data` attribute is set with a non-empty array, a Model subclass"," will be generated using the keys of the first item as its `ATTRS` (see"," the `_createRecordClass` method)."," 4. If the `columns` attribute is set, a Model subclass will be generated"," using the columns defined with a `key`. This is least desirable because"," columns can be duplicated or nested in a way that's not parsable."," 5. If neither `data` nor `columns` is set or populated, a change event"," subscriber will listen for the first to be changed and try all over"," again.",""," @attribute recordType"," @type {Function}"," @default (see description)"," @since 3.5.0"," **/"," recordType: {"," getter: '_getRecordType',"," setter: '_setRecordType'"," },",""," /**"," The collection of data records to display. This attribute is a pass"," through to a `data` property, which is a ModelList instance.",""," If this attribute is passed a ModelList or subclass, it will be assigned to"," the property directly. If an array of objects is passed, a new ModelList"," will be created using the configured `recordType` as its `model` property"," and seeded with the array.",""," Retrieving this attribute will return the ModelList stored in the `data`"," property.",""," @attribute data"," @type {ModelList|Object[]}"," @default `new ModelList()`"," @since 3.5.0"," **/"," data: {"," valueFn: '_initData',"," setter : '_setData',"," lazyAdd: false"," },",""," /**"," Content for the `<table summary=\"ATTRIBUTE VALUE HERE\">`. Values assigned"," to this attribute will be HTML escaped for security.",""," @attribute summary"," @type {String}"," @default '' (empty string)"," @since 3.5.0"," **/"," //summary: {},",""," /**"," HTML content of an optional `<caption>` element to appear above the table."," Leave this config unset or set to a falsy value to remove the caption.",""," @attribute caption"," @type HTML"," @default '' (empty string)"," @since 3.5.0"," **/"," //caption: {},",""," /**"," Deprecated as of 3.5.0. Passes through to the `data` attribute.",""," WARNING: `get('recordset')` will NOT return a Recordset instance as of"," 3.5.0. This is a break in backward compatibility.",""," @attribute recordset"," @type {Object[]|Recordset}"," @deprecated Use the `data` attribute"," @since 3.5.0"," **/"," recordset: {"," setter: '_setRecordset',"," getter: '_getRecordset',"," lazyAdd: false"," },",""," /**"," Deprecated as of 3.5.0. Passes through to the `columns` attribute.",""," WARNING: `get('columnset')` will NOT return a Columnset instance as of"," 3.5.0. This is a break in backward compatibility.",""," @attribute columnset"," @type {Object[]}"," @deprecated Use the `columns` attribute"," @since 3.5.0"," **/"," columnset: {"," setter: '_setColumnset',"," getter: '_getColumnset',"," lazyAdd: false"," }","};","","Y.mix(Table.prototype, {"," // -- Instance properties -------------------------------------------------"," /**"," The ModelList that manages the table's data.",""," @property data"," @type {ModelList}"," @default undefined (initially unset)"," @since 3.5.0"," **/"," //data: null,",""," // -- Public methods ------------------------------------------------------",""," /**"," Gets the column configuration object for the given key, name, or index. For"," nested columns, `name` can be an array of indexes, each identifying the index"," of that column in the respective parent's \"children\" array.",""," If you pass a column object, it will be returned.",""," For columns with keys, you can also fetch the column with"," `instance.get('columns.foo')`.",""," @method getColumn"," @param {String|Number|Number[]} name Key, \"name\", index, or index array to"," identify the column"," @return {Object} the column configuration object"," @since 3.5.0"," **/"," getColumn: function (name) {"," var col, columns, i, len, cols;",""," if (isObject(name) && !isArray(name)) {"," // TODO: support getting a column from a DOM node - this will cross"," // the line into the View logic, so it should be relayed",""," // Assume an object passed in is already a column def"," col = name;"," } else {"," col = this.get('columns.' + name);"," }",""," if (col) {"," return col;"," }",""," columns = this.get('columns');",""," if (isNumber(name) || isArray(name)) {"," name = toArray(name);"," cols = columns;",""," for (i = 0, len = name.length - 1; cols && i < len; ++i) {"," cols = cols[name[i]] && cols[name[i]].children;"," }",""," return (cols && cols[name[i]]) || null;"," }",""," return null;"," },",""," /**"," Returns the Model associated to the record `id`, `clientId`, or index (not"," row index). If none of those yield a Model from the `data` ModelList, the"," arguments will be passed to the `view` instance's `getRecord` method"," if it has one.",""," If no Model can be found, `null` is returned.",""," @method getRecord"," @param {Number|String|Node} seed Record `id`, `clientId`, index, Node, or"," identifier for a row or child element"," @return {Model}"," @since 3.5.0"," **/"," getRecord: function (seed) {"," var record = this.data.getById(seed) || this.data.getByClientId(seed);",""," if (!record) {"," if (isNumber(seed)) {"," record = this.data.item(seed);"," }"," "," // TODO: this should be split out to base somehow"," if (!record && this.view && this.view.getRecord) {"," record = this.view.getRecord.apply(this.view, arguments);"," }"," }",""," return record || null;"," },",""," // -- Protected and private properties and methods ------------------------",""," /**"," This tells `Y.Base` that it should create ad-hoc attributes for config"," properties passed to DataTable's constructor. This is useful for setting"," configurations on the DataTable that are intended for the rendering View(s).",""," @property _allowAdHocAttrs"," @type Boolean"," @default true"," @protected"," @since 3.6.0"," **/"," _allowAdHocAttrs: true,",""," /**"," A map of column key to column configuration objects parsed from the"," `columns` attribute.",""," @property _columnMap"," @type {Object}"," @default undefined (initially unset)"," @protected"," @since 3.5.0"," **/"," //_columnMap: null,",""," /**"," The Node instance of the table containing the data rows. This is set when"," the table is rendered. It may also be set by progressive enhancement,"," though this extension does not provide the logic to parse from source.",""," @property _tableNode"," @type {Node}"," @default undefined (initially unset)"," @protected"," @since 3.5.0"," **/"," //_tableNode: null,",""," /**"," Updates the `_columnMap` property in response to changes in the `columns`"," attribute.",""," @method _afterColumnsChange"," @param {EventFacade} e The `columnsChange` event object"," @protected"," @since 3.5.0"," **/"," _afterColumnsChange: function (e) {"," this._setColumnMap(e.newVal);"," },",""," /**"," Updates the `modelList` attributes of the rendered views in response to the"," `data` attribute being assigned a new ModelList.",""," @method _afterDataChange"," @param {EventFacade} e the `dataChange` event"," @protected"," @since 3.5.0"," **/"," _afterDataChange: function (e) {"," var modelList = e.newVal;",""," this.data = e.newVal;",""," if (!this.get('columns') && modelList.size()) {"," // TODO: this will cause a re-render twice because the Views are"," // subscribed to columnsChange"," this._initColumns();"," }"," },",""," /**"," Assigns to the new recordType as the model for the data ModelList",""," @method _afterRecordTypeChange"," @param {EventFacade} e recordTypeChange event"," @protected"," @since 3.6.0"," **/"," _afterRecordTypeChange: function (e) {"," var data = this.data.toJSON();",""," this.data.model = e.newVal;",""," this.data.reset(data);",""," if (!this.get('columns') && data) {"," if (data.length) {"," this._initColumns();"," } else {"," this.set('columns', keys(e.newVal.ATTRS));"," }"," }"," },",""," /**"," Creates a Model subclass from an array of attribute names or an object of"," attribute definitions. This is used to generate a class suitable to"," represent the data passed to the `data` attribute if no `recordType` is"," set.",""," @method _createRecordClass"," @param {String[]|Object} attrs Names assigned to the Model subclass's"," `ATTRS` or its entire `ATTRS` definition object"," @return {Model}"," @protected"," @since 3.5.0"," **/"," _createRecordClass: function (attrs) {"," var ATTRS, i, len;",""," if (isArray(attrs)) {"," ATTRS = {};",""," for (i = 0, len = attrs.length; i < len; ++i) {"," ATTRS[attrs[i]] = {};"," }"," } else if (isObject(attrs)) {"," ATTRS = attrs;"," }",""," return Y.Base.create('record', Y.Model, [], null, { ATTRS: ATTRS });"," },",""," /**"," Tears down the instance.",""," @method destructor"," @protected"," @since 3.6.0"," **/"," destructor: function () {"," new Y.EventHandle(Y.Object.values(this._eventHandles)).detach();"," },",""," /**"," The getter for the `columns` attribute. Returns the array of column"," configuration objects if `instance.get('columns')` is called, or the"," specific column object if `instance.get('columns.columnKey')` is called.",""," @method _getColumns"," @param {Object[]} columns The full array of column objects"," @param {String} name The attribute name requested"," (e.g. 'columns' or 'columns.foo');"," @protected"," @since 3.5.0"," **/"," _getColumns: function (columns, name) {"," // Workaround for an attribute oddity (ticket #2529254)"," // getter is expected to return an object if get('columns.foo') is called."," // Note 'columns.' is 8 characters"," return name.length > 8 ? this._columnMap : columns;"," },",""," /**"," Relays the `get()` request for the deprecated `columnset` attribute to the"," `columns` attribute.",""," THIS BREAKS BACKWARD COMPATIBILITY. 3.4.1 and prior implementations will"," expect a Columnset instance returned from `get('columnset')`.",""," @method _getColumnset"," @param {Object} ignored The current value stored in the `columnset` state"," @param {String} name The attribute name requested"," (e.g. 'columnset' or 'columnset.foo');"," @deprecated This will be removed with the `columnset` attribute in a future"," version."," @protected"," @since 3.5.0"," **/"," _getColumnset: function (_, name) {"," return this.get(name.replace(/^columnset/, 'columns'));"," },",""," /**"," Returns the Model class of the instance's `data` attribute ModelList. If"," not set, returns the explicitly configured value.",""," @method _getRecordType"," @param {Model} val The currently configured value"," @return {Model}"," **/"," _getRecordType: function (val) {"," // Prefer the value stored in the attribute because the attribute"," // change event defaultFn sets e.newVal = this.get('recordType')"," // before notifying the after() subs. But if this getter returns"," // this.data.model, then after() subs would get e.newVal === previous"," // model before _afterRecordTypeChange can set"," // this.data.model = e.newVal"," return val || (this.data && this.data.model);"," },",""," /**"," Initializes the `_columnMap` property from the configured `columns`"," attribute. If `columns` is not set, but there are records in the `data`"," ModelList, use"," `ATTRS` of that class.",""," @method _initColumns"," @protected"," @since 3.5.0"," **/"," _initColumns: function () {"," var columns = this.get('columns') || [],"," item;"," "," // Default column definition from the configured recordType"," if (!columns.length && this.data.size()) {"," // TODO: merge superclass attributes up to Model?"," item = this.data.item(0);",""," if (item.toJSON) {"," item = item.toJSON();"," }",""," this.set('columns', keys(item));"," }",""," this._setColumnMap(columns);"," },",""," /**"," Sets up the change event subscriptions to maintain internal state.",""," @method _initCoreEvents"," @protected"," @since 3.6.0"," **/"," _initCoreEvents: function () {"," this._eventHandles.coreAttrChanges = this.after({"," columnsChange : Y.bind('_afterColumnsChange', this),"," recordTypeChange: Y.bind('_afterRecordTypeChange', this),"," dataChange : Y.bind('_afterDataChange', this)"," });"," },",""," /**"," Defaults the `data` attribute to an empty ModelList if not set during"," construction. Uses the configured `recordType` for the ModelList's `model`"," proeprty if set.",""," @method _initData"," @protected"," @return {ModelList}"," @since 3.6.0"," **/"," _initData: function () {"," var recordType = this.get('recordType'),"," // TODO: LazyModelList if recordType doesn't have complex ATTRS"," modelList = new Y.ModelList();",""," if (recordType) {"," modelList.model = recordType;"," }",""," return modelList;"," },",""," /**"," Initializes the instance's `data` property from the value of the `data`"," attribute. If the attribute value is a ModelList, it is assigned directly"," to `this.data`. If it is an array, a ModelList is created, its `model`"," property is set to the configured `recordType` class, and it is seeded with"," the array data. This ModelList is then assigned to `this.data`.",""," @method _initDataProperty"," @param {Array|ModelList|ArrayList} data Collection of data to populate the"," DataTable"," @protected"," @since 3.6.0"," **/"," _initDataProperty: function (data) {"," var recordType;",""," if (!this.data) {"," recordType = this.get('recordType');",""," if (data && data.each && data.toJSON) {"," this.data = data;",""," if (recordType) {"," this.data.model = recordType;"," }"," } else {"," // TODO: customize the ModelList or read the ModelList class"," // from a configuration option?"," this.data = new Y.ModelList();"," "," if (recordType) {"," this.data.model = recordType;"," }"," }",""," // TODO: Replace this with an event relay for specific events."," // Using bubbling causes subscription conflicts with the models'"," // aggregated change event and 'change' events from DOM elements"," // inside the table (via Widget UI event)."," this.data.addTarget(this);"," }"," },",""," /**"," Initializes the columns, `recordType` and data ModelList.",""," @method initializer"," @param {Object} config Configuration object passed to constructor"," @protected"," @since 3.5.0"," **/"," initializer: function (config) {"," var data = config.data,"," columns = config.columns,"," recordType;",""," // Referencing config.data to allow _setData to be more stringent"," // about its behavior"," this._initDataProperty(data);",""," // Default columns from recordType ATTRS if recordType is supplied at"," // construction. If no recordType is supplied, but the data is"," // supplied as a non-empty array, use the keys of the first item"," // as the columns."," if (!columns) {"," recordType = (config.recordType || config.data === this.data) &&"," this.get('recordType');",""," if (recordType) {"," columns = keys(recordType.ATTRS);"," } else if (isArray(data) && data.length) {"," columns = keys(data[0]);"," }",""," if (columns) {"," this.set('columns', columns);"," }"," }",""," this._initColumns();",""," this._eventHandles = {};",""," this._initCoreEvents();"," },",""," /**"," Iterates the array of column configurations to capture all columns with a"," `key` property. An map is built with column keys as the property name and"," the corresponding column object as the associated value. This map is then"," assigned to the instance's `_columnMap` property.",""," @method _setColumnMap"," @param {Object[]|String[]} columns The array of column config objects"," @protected"," @since 3.6.0"," **/"," _setColumnMap: function (columns) {"," var map = {};"," "," function process(cols) {"," var i, len, col, key;",""," for (i = 0, len = cols.length; i < len; ++i) {"," col = cols[i];"," key = col.key;",""," // First in wins for multiple columns with the same key"," // because the first call to genId (in _setColumns) will"," // return the same key, which will then be overwritten by the"," // subsequent same-keyed column. So table.getColumn(key) would"," // return the last same-keyed column."," if (key && !map[key]) {"," map[key] = col;"," }",""," //TODO: named columns can conflict with keyed columns"," map[col._id] = col;",""," if (col.children) {"," process(col.children);"," }"," }"," }",""," process(columns);",""," this._columnMap = map;"," },",""," /**"," Translates string columns into objects with that string as the value of its"," `key` property.",""," All columns are assigned a `_yuid` stamp and `_id` property corresponding"," to the column's configured `name` or `key` property with any spaces"," replaced with dashes. If the same `name` or `key` appears in multiple"," columns, subsequent appearances will have their `_id` appended with an"," incrementing number (e.g. if column \"foo\" is included in the `columns`"," attribute twice, the first will get `_id` of \"foo\", and the second an `_id`"," of \"foo1\"). Columns that are children of other columns will have the"," `_parent` property added, assigned the column object to which they belong.",""," @method _setColumns"," @param {null|Object[]|String[]} val Array of config objects or strings"," @return {null|Object[]}"," @protected"," **/"," _setColumns: function (val) {"," var keys = {},"," known = [],"," knownCopies = [],"," arrayIndex = Y.Array.indexOf;"," "," function copyObj(o) {"," var copy = {},"," key, val, i;",""," known.push(o);"," knownCopies.push(copy);",""," for (key in o) {"," if (o.hasOwnProperty(key)) {"," val = o[key];",""," if (isArray(val)) {"," copy[key] = val.slice();"," } else if (isObject(val, true)) {"," i = arrayIndex(val, known);",""," copy[key] = i === -1 ? copyObj(val) : knownCopies[i];"," } else {"," copy[key] = o[key];"," }"," }"," }",""," return copy;"," }",""," function genId(name) {"," // Sanitize the name for use in generated CSS classes."," // TODO: is there more to do for other uses of _id?"," name = name.replace(/\\s+/, '-');",""," if (keys[name]) {"," name += (keys[name]++);"," } else {"," keys[name] = 1;"," }",""," return name;"," }",""," function process(cols, parent) {"," var columns = [],"," i, len, col, yuid;",""," for (i = 0, len = cols.length; i < len; ++i) {"," columns[i] = // chained assignment"," col = isString(cols[i]) ? { key: cols[i] } : copyObj(cols[i]);",""," yuid = Y.stamp(col);",""," // For backward compatibility"," if (!col.id) {"," // Implementers can shoot themselves in the foot by setting"," // this config property to a non-unique value"," col.id = yuid;"," }"," if (col.field) {"," // Field is now known as \"name\" to avoid confusion with data"," // fields or schema.resultFields"," col.name = col.field;"," }",""," if (parent) {"," col._parent = parent;"," } else {"," delete col._parent;"," }",""," // Unique id based on the column's configured name or key,"," // falling back to the yuid. Duplicates will have a counter"," // added to the end."," col._id = genId(col.name || col.key || col.id);",""," if (isArray(col.children)) {"," col.children = process(col.children, col);"," }"," }",""," return columns;"," }",""," return val && process(val);"," },",""," /**"," Relays attribute assignments of the deprecated `columnset` attribute to the"," `columns` attribute. If a Columnset is object is passed, its basic object"," structure is mined.",""," @method _setColumnset"," @param {Array|Columnset} val The columnset value to relay"," @deprecated This will be removed with the deprecated `columnset` attribute"," in a later version."," @protected"," @since 3.5.0"," **/"," _setColumnset: function (val) {"," this.set('columns', val);",""," return isArray(val) ? val : INVALID;"," },",""," /**"," Accepts an object with `each` and `getAttrs` (preferably a ModelList or"," subclass) or an array of data objects. If an array is passes, it will"," create a ModelList to wrap the data. In doing so, it will set the created"," ModelList's `model` property to the class in the `recordType` attribute,"," which will be defaulted if not yet set.",""," If the `data` property is already set with a ModelList, passing an array as"," the value will call the ModelList's `reset()` method with that array rather"," than replacing the stored ModelList wholesale.",""," Any non-ModelList-ish and non-array value is invalid.",""," @method _setData"," @protected"," @since 3.5.0"," **/"," _setData: function (val) {"," if (val === null) {"," val = [];"," }",""," if (isArray(val)) {"," this._initDataProperty();",""," // silent to prevent subscribers to both reset and dataChange"," // from reacting to the change twice."," // TODO: would it be better to return INVALID to silence the"," // dataChange event, or even allow both events?"," this.data.reset(val, { silent: true });",""," // Return the instance ModelList to avoid storing unprocessed"," // data in the state and their vivified Model representations in"," // the instance's data property. Decreases memory consumption."," val = this.data;"," } else if (!val || !val.each || !val.toJSON) {"," // ModelList/ArrayList duck typing"," val = INVALID;"," }",""," return val;"," },",""," /**"," Relays the value assigned to the deprecated `recordset` attribute to the"," `data` attribute. If a Recordset instance is passed, the raw object data"," will be culled from it.",""," @method _setRecordset"," @param {Object[]|Recordset} val The recordset value to relay"," @deprecated This will be removed with the deprecated `recordset` attribute"," in a later version."," @protected"," @since 3.5.0"," **/"," _setRecordset: function (val) {"," var data;",""," if (val && Y.Recordset && val instanceof Y.Recordset) {"," data = [];"," val.each(function (record) {"," data.push(record.get('data'));"," });"," val = data;"," }",""," this.set('data', val);",""," return val;"," },",""," /**"," Accepts a Base subclass (preferably a Model subclass). Alternately, it will"," generate a custom Model subclass from an array of attribute names or an"," object defining attributes and their respective configurations (it is"," assigned as the `ATTRS` of the new class).",""," Any other value is invalid.",""," @method _setRecordType"," @param {Function|String[]|Object} val The Model subclass, array of"," attribute names, or the `ATTRS` definition for a custom model"," subclass"," @return {Function} A Base/Model subclass"," @protected"," @since 3.5.0"," **/"," _setRecordType: function (val) {"," var modelClass;",""," // Duck type based on known/likely consumed APIs"," if (isFunction(val) && val.prototype.toJSON && val.prototype.setAttrs) {"," modelClass = val;"," } else if (isObject(val)) {"," modelClass = this._createRecordClass(val);"," }",""," return modelClass || INVALID;"," }","","});","","","}, '@VERSION@', {\"requires\": [\"escape\", \"model-list\", \"node-event-delegate\"]});","","}());"]}; } var __cov_adU3eEuYYFqBLZ6_IZplXQ = __coverage__['build/datatable-core/datatable-core.js']; __cov_adU3eEuYYFqBLZ6_IZplXQ.s['1']++;YUI.add('datatable-core',function(Y,NAME){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['1']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['2']++;var INVALID=Y.Attribute.INVALID_VALUE,Lang=Y.Lang,isFunction=Lang.isFunction,isObject=Lang.isObject,isArray=Lang.isArray,isString=Lang.isString,isNumber=Lang.isNumber,toArray=Y.Array,keys=Y.Object.keys,Table;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['3']++;Table=Y.namespace('DataTable').Core=function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['2']++;};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['4']++;Table.ATTRS={columns:{validator:isArray,setter:'_setColumns',getter:'_getColumns'},recordType:{getter:'_getRecordType',setter:'_setRecordType'},data:{valueFn:'_initData',setter:'_setData',lazyAdd:false},recordset:{setter:'_setRecordset',getter:'_getRecordset',lazyAdd:false},columnset:{setter:'_setColumnset',getter:'_getColumnset',lazyAdd:false}};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['5']++;Y.mix(Table.prototype,{getColumn:function(name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['3']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['6']++;var col,columns,i,len,cols;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['7']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['2'][0]++,isObject(name))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['2'][1]++,!isArray(name))){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['1'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['8']++;col=name;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['1'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['9']++;col=this.get('columns.'+name);}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['10']++;if(col){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['3'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['11']++;return col;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['3'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['12']++;columns=this.get('columns');__cov_adU3eEuYYFqBLZ6_IZplXQ.s['13']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['5'][0]++,isNumber(name))||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['5'][1]++,isArray(name))){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['4'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['14']++;name=toArray(name);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['15']++;cols=columns;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['16']++;for(i=0,len=name.length-1;(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['6'][0]++,cols)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['6'][1]++,i<len);++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['17']++;cols=(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['7'][0]++,cols[name[i]])&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['7'][1]++,cols[name[i]].children);}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['18']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['8'][0]++,cols)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['8'][1]++,cols[name[i]])||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['8'][2]++,null);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['4'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['19']++;return null;},getRecord:function(seed){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['4']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['20']++;var record=(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['9'][0]++,this.data.getById(seed))||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['9'][1]++,this.data.getByClientId(seed));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['21']++;if(!record){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['10'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['22']++;if(isNumber(seed)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['11'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['23']++;record=this.data.item(seed);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['11'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['24']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['13'][0]++,!record)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['13'][1]++,this.view)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['13'][2]++,this.view.getRecord)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['12'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['25']++;record=this.view.getRecord.apply(this.view,arguments);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['12'][1]++;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['10'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['26']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['14'][0]++,record)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['14'][1]++,null);},_allowAdHocAttrs:true,_afterColumnsChange:function(e){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['5']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['27']++;this._setColumnMap(e.newVal);},_afterDataChange:function(e){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['6']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['28']++;var modelList=e.newVal;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['29']++;this.data=e.newVal;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['30']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['16'][0]++,!this.get('columns'))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['16'][1]++,modelList.size())){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['15'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['31']++;this._initColumns();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['15'][1]++;}},_afterRecordTypeChange:function(e){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['7']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['32']++;var data=this.data.toJSON();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['33']++;this.data.model=e.newVal;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['34']++;this.data.reset(data);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['35']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['18'][0]++,!this.get('columns'))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['18'][1]++,data)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['17'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['36']++;if(data.length){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['19'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['37']++;this._initColumns();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['19'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['38']++;this.set('columns',keys(e.newVal.ATTRS));}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['17'][1]++;}},_createRecordClass:function(attrs){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['8']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['39']++;var ATTRS,i,len;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['40']++;if(isArray(attrs)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['20'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['41']++;ATTRS={};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['42']++;for(i=0,len=attrs.length;i<len;++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['43']++;ATTRS[attrs[i]]={};}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['20'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['44']++;if(isObject(attrs)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['21'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['45']++;ATTRS=attrs;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['21'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['46']++;return Y.Base.create('record',Y.Model,[],null,{ATTRS:ATTRS});},destructor:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['9']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['47']++;new Y.EventHandle(Y.Object.values(this._eventHandles)).detach();},_getColumns:function(columns,name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['10']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['48']++;return name.length>8?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['22'][0]++,this._columnMap):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['22'][1]++,columns);},_getColumnset:function(_,name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['11']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['49']++;return this.get(name.replace(/^columnset/,'columns'));},_getRecordType:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['12']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['50']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['23'][0]++,val)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['23'][1]++,this.data)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['23'][2]++,this.data.model);},_initColumns:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['13']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['51']++;var columns=(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['24'][0]++,this.get('columns'))||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['24'][1]++,[]),item;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['52']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['26'][0]++,!columns.length)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['26'][1]++,this.data.size())){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['25'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['53']++;item=this.data.item(0);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['54']++;if(item.toJSON){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['27'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['55']++;item=item.toJSON();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['27'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['56']++;this.set('columns',keys(item));}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['25'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['57']++;this._setColumnMap(columns);},_initCoreEvents:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['14']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['58']++;this._eventHandles.coreAttrChanges=this.after({columnsChange:Y.bind('_afterColumnsChange',this),recordTypeChange:Y.bind('_afterRecordTypeChange',this),dataChange:Y.bind('_afterDataChange',this)});},_initData:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['15']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['59']++;var recordType=this.get('recordType'),modelList=new Y.ModelList();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['60']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['28'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['61']++;modelList.model=recordType;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['28'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['62']++;return modelList;},_initDataProperty:function(data){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['16']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['63']++;var recordType;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['64']++;if(!this.data){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['29'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['65']++;recordType=this.get('recordType');__cov_adU3eEuYYFqBLZ6_IZplXQ.s['66']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['31'][0]++,data)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['31'][1]++,data.each)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['31'][2]++,data.toJSON)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['30'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['67']++;this.data=data;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['68']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['32'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['69']++;this.data.model=recordType;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['32'][1]++;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['30'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['70']++;this.data=new Y.ModelList();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['71']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['33'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['72']++;this.data.model=recordType;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['33'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['73']++;this.data.addTarget(this);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['29'][1]++;}},initializer:function(config){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['17']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['74']++;var data=config.data,columns=config.columns,recordType;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['75']++;this._initDataProperty(data);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['76']++;if(!columns){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['34'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['77']++;recordType=((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['35'][0]++,config.recordType)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['35'][1]++,config.data===this.data))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['35'][2]++,this.get('recordType'));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['78']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['36'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['79']++;columns=keys(recordType.ATTRS);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['36'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['80']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['38'][0]++,isArray(data))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['38'][1]++,data.length)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['37'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['81']++;columns=keys(data[0]);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['37'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['82']++;if(columns){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['39'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['83']++;this.set('columns',columns);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['39'][1]++;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['34'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['84']++;this._initColumns();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['85']++;this._eventHandles={};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['86']++;this._initCoreEvents();},_setColumnMap:function(columns){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['18']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['87']++;var map={};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['88']++;function process(cols){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['19']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['89']++;var i,len,col,key;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['90']++;for(i=0,len=cols.length;i<len;++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['91']++;col=cols[i];__cov_adU3eEuYYFqBLZ6_IZplXQ.s['92']++;key=col.key;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['93']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['41'][0]++,key)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['41'][1]++,!map[key])){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['40'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['94']++;map[key]=col;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['40'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['95']++;map[col._id]=col;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['96']++;if(col.children){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['42'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['97']++;process(col.children);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['42'][1]++;}}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['98']++;process(columns);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['99']++;this._columnMap=map;},_setColumns:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['20']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['100']++;var keys={},known=[],knownCopies=[],arrayIndex=Y.Array.indexOf;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['101']++;function copyObj(o){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['21']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['102']++;var copy={},key,val,i;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['103']++;known.push(o);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['104']++;knownCopies.push(copy);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['105']++;for(key in o){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['106']++;if(o.hasOwnProperty(key)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['43'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['107']++;val=o[key];__cov_adU3eEuYYFqBLZ6_IZplXQ.s['108']++;if(isArray(val)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['44'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['109']++;copy[key]=val.slice();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['44'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['110']++;if(isObject(val,true)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['45'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['111']++;i=arrayIndex(val,known);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['112']++;copy[key]=i===-1?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['46'][0]++,copyObj(val)):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['46'][1]++,knownCopies[i]);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['45'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['113']++;copy[key]=o[key];}}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['43'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['114']++;return copy;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['115']++;function genId(name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['22']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['116']++;name=name.replace(/\s+/,'-');__cov_adU3eEuYYFqBLZ6_IZplXQ.s['117']++;if(keys[name]){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['47'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['118']++;name+=keys[name]++;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['47'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['119']++;keys[name]=1;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['120']++;return name;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['121']++;function process(cols,parent){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['23']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['122']++;var columns=[],i,len,col,yuid;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['123']++;for(i=0,len=cols.length;i<len;++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['124']++;columns[i]=col=isString(cols[i])?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['48'][0]++,{key:cols[i]}):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['48'][1]++,copyObj(cols[i]));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['125']++;yuid=Y.stamp(col);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['126']++;if(!col.id){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['49'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['127']++;col.id=yuid;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['49'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['128']++;if(col.field){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['50'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['129']++;col.name=col.field;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['50'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['130']++;if(parent){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['51'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['131']++;col._parent=parent;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['51'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['132']++;delete col._parent;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['133']++;col._id=genId((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['52'][0]++,col.name)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['52'][1]++,col.key)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['52'][2]++,col.id));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['134']++;if(isArray(col.children)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['53'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['135']++;col.children=process(col.children,col);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['53'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['136']++;return columns;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['137']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['54'][0]++,val)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['54'][1]++,process(val));},_setColumnset:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['24']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['138']++;this.set('columns',val);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['139']++;return isArray(val)?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['55'][0]++,val):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['55'][1]++,INVALID);},_setData:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['25']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['140']++;if(val===null){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['56'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['141']++;val=[];}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['56'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['142']++;if(isArray(val)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['57'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['143']++;this._initDataProperty();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['144']++;this.data.reset(val,{silent:true});__cov_adU3eEuYYFqBLZ6_IZplXQ.s['145']++;val=this.data;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['57'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['146']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['59'][0]++,!val)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['59'][1]++,!val.each)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['59'][2]++,!val.toJSON)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['58'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['147']++;val=INVALID;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['58'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['148']++;return val;},_setRecordset:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['26']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['149']++;var data;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['150']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['61'][0]++,val)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['61'][1]++,Y.Recordset)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['61'][2]++,val instanceof Y.Recordset)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['60'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['151']++;data=[];__cov_adU3eEuYYFqBLZ6_IZplXQ.s['152']++;val.each(function(record){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['27']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['153']++;data.push(record.get('data'));});__cov_adU3eEuYYFqBLZ6_IZplXQ.s['154']++;val=data;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['60'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['155']++;this.set('data',val);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['156']++;return val;},_setRecordType:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['28']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['157']++;var modelClass;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['158']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['63'][0]++,isFunction(val))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['63'][1]++,val.prototype.toJSON)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['63'][2]++,val.prototype.setAttrs)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['62'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['159']++;modelClass=val;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['62'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['160']++;if(isObject(val)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['64'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['161']++;modelClass=this._createRecordClass(val);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['64'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['162']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['65'][0]++,modelClass)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['65'][1]++,INVALID);}});},'@VERSION@',{'requires':['escape','model-list','node-event-delegate']});
ajax/libs/forerunnerdb/1.3.766/fdb-all.min.js
emmy41124/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/CollectionGroup"),a("../lib/View"),a("../lib/Highchart"),a("../lib/Persist"),a("../lib/Document"),a("../lib/Overview"),a("../lib/Grid"),a("../lib/NodeApiClient"),a("../lib/BinaryLog");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/BinaryLog":4,"../lib/CollectionGroup":8,"../lib/Document":11,"../lib/Grid":13,"../lib/Highchart":14,"../lib/NodeApiClient":30,"../lib/Overview":33,"../lib/Persist":35,"../lib/View":42,"./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":9,"../lib/Shim.IE8":41}],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),0>g&&(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;l>f;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(-1===g.value)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),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},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):!1):!1},g.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},g.prototype.documentKey=function(a){var b,c,e="",f=this._keyArr,g=f.length;for(b=0;g>b;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":34,"./Shared":40}],4:[function(a,b,c){"use strict";var d,e,f,g,h,i,j;d=a("./Shared"),j=function(){this.init.apply(this,arguments)},j.prototype.init=function(a){var b=this;b._logCounter=0,b._parent=a,b.size(1e3)},d.addModule("BinaryLog",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Events"),f=d.modules.Collection,h=d.modules.Db,e=d.modules.ReactorIO,g=f.prototype.init,i=h.prototype.init,d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"size"),j.prototype.attachIO=function(){var a=this;a._io||(a._log=new f(a._parent.name()+"-BinaryLog",{capped:!0,size:a.size()}),a._log.objectId=function(b){return b||(b=++a._logCounter),b},a._io=new e(a._parent,a,function(b){return a._log.insert({type:b.type,data:b.data}),!1}))},j.prototype.detachIO=function(){var a=this;a._io&&(a._log.drop(),a._io.drop(),delete a._log,delete a._io)},f.prototype.init=function(){g.apply(this,arguments),this._binaryLog=new j(this)},d.finishModule("BinaryLog"),b.exports=j},{"./Shared":40}],5:[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):!1},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)):-1===d.value&&(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):-1===b?(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):!1):(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),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},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){var d=this._compareFunc(this._data,a);return c=c||[],0===d&&(this._left&&this._left.lookup(a,b,c),c.push(this._data),this._right&&this._right.lookup(a,b,c)),-1===d&&this._right&&this._right.lookup(a,b,c),1===d&&this._left&&this._left.lookup(a,b,c),c},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 c=c||new RegExp("^"+b),d=d||[],void 0===d._visited&&(d._visited=0),d._visited++,g=this.sortAsc(h,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)),-1===g&&(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&&-1!==j))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":34,"./Shared":40}],6:[function(a,b,c){"use strict";var d,e;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}(),e=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},b.exports=e},{}],7:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n;d=a("./Shared");var o=function(a,b){this.init.apply(this,arguments)};o.prototype.init=function(a,b){this.sharedPathSolver=n,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._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",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Events"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.CRUD"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Triggers"),d.mixin(o.prototype,"Mixin.Sorting"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.Updating"),d.mixin(o.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=new h,d.synthesize(o.prototype,"deferredCalls"),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"metaData"),d.synthesize(o.prototype,"capped"),d.synthesize(o.prototype,"cappedSize"),o.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},o.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")},o.prototype.data=function(){return this._data},o.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},o.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},o.prototype._onInsert=function(a,b){this.emit("insert",a,b)},o.prototype._onUpdate=function(a){this.emit("update",a)},o.prototype._onRemove=function(a){this.emit("remove",a)},o.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=this.serialiser.convert(new Date))},d.synthesize(o.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"mongoEmulation"),o.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}}),o.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.hash(d),i.set(d[k],e),j.set(e,d)}},o.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},o.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.emit("immediateChange",{type:"truncate"}),this.deferEmit("change",{type:"truncate"}),this},o.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),{}},o.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},o.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},o.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=this.transformIn(b),this._handleUpdate(a,b,c,d)},o.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?(i=g.updateObject(d,e,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_AFTER,j,e)):i=!1):i=g.updateObject(d,b,a,c,""),g._updateIndexes(j,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),this.emit("immediateChange",{type:"update",data:f}),this.deferEmit("change",{type:"update",data:f}))),h.stop(),f||[]},o.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},o.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},o.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;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===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;k>j;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(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;k>j;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;k>j;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(0>k)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;B>w;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"$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 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},o.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},o.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},o.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},o.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")},o.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},o.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)},o.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}),this.deferEmit("change",{type:"insert",data:i}),e},o.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"},o.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},o.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},o.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},o.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},o.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)},o.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},o.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},o.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new o,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(o.prototype,"subsetOf"),o.prototype.isSubsetOf=function(a){return this._subsetOf===a},o.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},o.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},o.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new o,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)},o.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},o.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},o.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)},o.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=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&&-1===D.indexOf(o)&&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},o.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},o.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},o.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},o.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},o.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}},o.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},o.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},o.prototype.sort=function(a,b){var c=this,d=n.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(n.get(a,f.path),n.get(b,f.path)):-1===f.value&&(g=c.sortDesc(n.get(a,f.path),n.get(b,f.path))),0!==g)return g;return g}),b},o.prototype.group=function(a,b){var c,d,e,f=n.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},o.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)},o.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=this._primaryIndex.lookup(a,b),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=m.lookup(a,b),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},o.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},o.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},o.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},o.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new o("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;j>e;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},o.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},o.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},o.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()})},o.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},o.prototype.lastOp=function(){return this._metrics.list()},o.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},o.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!"}}),o.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("Db.prototype.collection",{"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof o?"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(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new o(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.emit("create",b._collection[c],"collection",c),this._collection[c]}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=o},{"./Index2d":15,"./IndexBinaryTree":16,"./IndexHashMap":17,"./KeyValueStore":18,"./Metrics":19,"./Overload":32,"./Path":34,"./ReactorIO":38,"./Shared":40}],8:[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&&-1===this._collections.indexOf(a)){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);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data.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.emit("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":7,"./Shared":40}],9:[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):!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.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":10,"./Metrics.js":19,"./Overload":32,"./Shared":40}],10:[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&&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"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Checksum.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.Checksum=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._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;d>b;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;d>b;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;e>c;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 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},{"./Checksum.js":6,"./Collection.js":7,"./Metrics.js":19,"./Overload":32,"./Shared":40}],11:[function(a,b,c){"use strict";var d,e,f;d=a("./Shared");var g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a){this._name=a,this._data={}},d.addModule("Document",g),d.mixin(g.prototype,"Mixin.Common"),d.mixin(g.prototype,"Mixin.Events"),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Constants"),d.mixin(g.prototype,"Mixin.Triggers"),d.mixin(g.prototype,"Mixin.Matching"),d.mixin(g.prototype,"Mixin.Updating"),d.mixin(g.prototype,"Mixin.Tags"),e=a("./Collection"),f=d.modules.Db,d.synthesize(g.prototype,"state"),d.synthesize(g.prototype,"db"),d.synthesize(g.prototype,"name"),g.prototype.setData=function(a,b){var c,d;if(a){if(b=b||{$decouple:!0},b&&b.$decouple===!0&&(a=this.decouple(a)),this._linked){d={};for(c in this._data)"jQuery"!==c.substr(0,6)&&this._data.hasOwnProperty(c)&&void 0===a[c]&&(d[c]=1);a.$unset=d,this.updateObject(this._data,a,{})}else this._data=a;this.deferEmit("change",{type:"setData",data:this.decouple(this._data)})}return this},g.prototype.find=function(a,b){var c;return c=b&&b.$decouple===!1?this._data:this.decouple(this._data)},g.prototype.update=function(a,b,c){var d=this.updateObject(this._data,b,a,c);d&&this.deferEmit("change",{type:"update",data:this.decouple(this._data)})},g.prototype.updateObject=e.prototype.updateObject,g.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},g.prototype._updateProperty=function(a,b,c){this._linked?(window.jQuery.observable(a).setProperty(b,c),this.debug()&&console.log(this.logIdentifier()+' Setting data-bound document property "'+b+'"')):(a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"'))},g.prototype._updateIncrement=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]+c):a[b]+=c},g.prototype._updateSpliceMove=function(a,b,c){this._linked?(window.jQuery.observable(a).move(b,c),this.debug()&&console.log(this.logIdentifier()+' Moving data-bound document array index from "'+b+'" to "'+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+'"'))},g.prototype._updateSplicePush=function(a,b,c){a.length>b?this._linked?window.jQuery.observable(a).insert(b,c):a.splice(b,0,c):this._linked?window.jQuery.observable(a).insert(c):a.push(c)},g.prototype._updatePush=function(a,b){this._linked?window.jQuery.observable(a).insert(b):a.push(b)},g.prototype._updatePull=function(a,b){this._linked?window.jQuery.observable(a).remove(b):a.splice(b,1)},g.prototype._updateMultiply=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]*c):a[b]*=c},g.prototype._updateRename=function(a,b,c){var d=a[b];this._linked?(window.jQuery.observable(a).setProperty(c,d),window.jQuery.observable(a).removeProperty(b)):(a[c]=d,delete a[b])},g.prototype._updateUnset=function(a,b){this._linked?window.jQuery.observable(a).removeProperty(b):delete a[b]},g.prototype.drop=function(a){return this.isDropped()?!0:this._db&&this._name&&this._db&&this._db._document&&this._db._document[this._name]?(this._state="dropped",delete this._db._document[this._name],delete this._data,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0):!1},f.prototype.document=function(a){var b=this;if(a){if(a instanceof g){if("droppped"!==a.state())return a;a=a.name()}return this._document&&this._document[a]?this._document[a]:(this._document=this._document||{},this._document[a]=new g(a).db(this),b.emit("create",b._document[a],"document",a),this._document[a])}return this._document},f.prototype.documents=function(){var a,b,c=[];for(b in this._document)this._document.hasOwnProperty(b)&&(a=this._document[b],c.push({name:b,linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Document"),b.exports=g},{"./Collection":7,"./Shared":40}],12:[function(a,b,c){"use strict";var d,e,f,g;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 h=function(){};h.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},h.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},h.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-1!==g[b][d].indexOf(c)&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},h.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;5>g;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,{latitude:l,longitude:m}},h.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,4>j?j++:(l+=e[k],j=0,k=0);return l},b.exports=h},{}],13:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._selector=a,this._template=b,this._options=c||{},this._debug={},this._id=this.objectId(),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)}},d.addModule("Grid",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Events"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),h=a("./View"),k=a("./ReactorIO"),i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.from=function(a){return void 0!==a&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this)),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this.refresh()),this},d.synthesize(l.prototype,"db",function(a){return a&&this.debug(a.debug()),this.$super.apply(this,arguments)}),l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.drop=function(a){return this.isDropped()?!0:this._from?(this._from.unlink(this._selector,this.template()),this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping grid "+this._selector),this._state="dropped",this._db&&this._selector&&delete this._db._grid[this._selector],this.emit("drop",this),a&&a(!1,!0),delete this._selector,delete this._template,delete this._from,delete this._db,delete this._listeners,!0):!1},l.prototype.template=function(a){return void 0!==a?(this._template=a,this):this._template},l.prototype._sortGridClick=function(a){var b,c=window.jQuery(a.currentTarget),e=c.attr("data-grid-sort")||"",f=-1===parseInt(c.attr("data-grid-dir")||"-1",10)?1:-1,g=e.split(","),h={};for(window.jQuery(this._selector).find("[data-grid-dir]").removeAttr("data-grid-dir"),c.attr("data-grid-dir",f),b=0;b<g.length;b++)h[g]=f;d.mixin(h,this._options.$orderBy),this._from.orderBy(h),this.emit("sort",h)},l.prototype.refresh=function(){if(this._from){if(!this._from.link)throw"Grid requires the AutoBind module in order to operate!";var a=this,b=window.jQuery(this._selector),c=function(){a._sortGridClick.apply(a,arguments)};if(b.html(""),a._from.orderBy&&b.off("click","[data-grid-sort]",c),a._from.query&&b.off("click","[data-grid-filter]",c),a._options.$wrap=a._options.$wrap||"gridRow",a._from.link(a._selector,a.template(),a._options),a._from.orderBy&&b.on("click","[data-grid-sort]",c),a._from.query){var d={};b.find("[data-grid-filter]").each(function(c,e){e=window.jQuery(e);var f,g,h,i,j=e.attr("data-grid-filter"),k=e.attr("data-grid-vartype"),l={},m=e.html(),n=a._db.view("tmpGridFilter_"+a._id+"_"+j);l[j]=1,i={$distinct:l},n.query(i).orderBy(l).from(a._from._from),h=['<div class="dropdown" id="'+a._id+"_"+j+'">','<button class="btn btn-default dropdown-toggle" type="button" id="'+a._id+"_"+j+'_dropdownButton" data-toggle="dropdown" aria-expanded="true">',m+' <span class="caret"></span>',"</button>","</div>"],f=window.jQuery(h.join("")),g=window.jQuery('<ul class="dropdown-menu" role="menu" id="'+a._id+"_"+j+'_dropdownMenu"></ul>'), f.append(g),e.html(f),n.link(g,{template:['<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">','<input type="search" class="form-control gridFilterSearch" placeholder="Search...">','<span class="input-group-btn">','<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',"</span>","</li>",'<li role="presentation" class="divider"></li>','<li role="presentation" data-val="$all">','<a role="menuitem" tabindex="-1">','<input type="checkbox" checked>&nbsp;All',"</a>","</li>",'<li role="presentation" class="divider"></li>',"{^{for options}}",'<li role="presentation" data-link="data-val{:'+j+'}">','<a role="menuitem" tabindex="-1">','<input type="checkbox">&nbsp;{^{:'+j+"}}","</a>","</li>","{{/for}}"].join("")},{$wrap:"options"}),b.on("keyup","#"+a._id+"_"+j+"_dropdownMenu .gridFilterSearch",function(a){var b=window.jQuery(this),c=n.query(),d=b.val();d?c[j]=new RegExp(d,"gi"):delete c[j],n.query(c)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu .gridFilterClearSearch",function(a){window.jQuery(this).parents("li").find(".gridFilterSearch").val("");var b=n.query();delete b[j],n.query(b)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu li",function(b){b.stopPropagation();var c,e,f,g,h,i=$(this),l=i.find('input[type="checkbox"]'),m=!0;if(window.jQuery(b.target).is("input")?(l.prop("checked",l.prop("checked")),e=l.is(":checked")):(l.prop("checked",!l.prop("checked")),e=l.is(":checked")),g=window.jQuery(this),c=g.attr("data-val"),"$all"===c)delete d[j],g.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop("checked",!1);else{switch(g.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop("checked",!1),k){case"integer":c=parseInt(c,10);break;case"float":c=parseFloat(c)}for(d[j]=d[j]||{$in:[]},f=d[j].$in,h=0;h<f.length;h++)if(f[h]===c){e===!1&&f.splice(h,1),m=!1;break}m&&e&&f.push(c),f.length||delete d[j]}a._from.queryData(d),a._from.pageFirst&&a._from.pageFirst()})})}a.emit("refresh")}return this},l.prototype.count=function(){return this._from.count()},f.prototype.grid=h.prototype.grid=function(a,b,c){if(this._db&&this._db._grid){if(void 0!==a){if(void 0!==b){if(this._db._grid[a])throw this.logIdentifier()+" Cannot create a grid because a grid with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._grid=this._grid||[],this._grid.push(d),this._db._grid[a]=d,d}return this._db._grid[a]}return this._db._grid}},f.prototype.unGrid=h.prototype.unGrid=function(a,b,c){var d,e;if(this._db&&this._db._grid){if(a&&b){if(this._db._grid[a])return e=this._db._grid[a],delete this._db._grid[a],e.drop();throw this.logIdentifier()+" Cannot remove grid because a grid with this name does not exist: "+name}for(d in this._db._grid)this._db._grid.hasOwnProperty(d)&&(e=this._db._grid[d],delete this._db._grid[d],e.drop(),this.debug()&&console.log(this.logIdentifier()+' Removed grid binding "'+d+'"'));this._db._grid={}}},f.prototype._addGrid=g.prototype._addGrid=h.prototype._addGrid=function(a){return void 0!==a&&(this._grid=this._grid||[],this._grid.push(a)),this},f.prototype._removeGrid=g.prototype._removeGrid=h.prototype._removeGrid=function(a){if(void 0!==a&&this._grid){var b=this._grid.indexOf(a);b>-1&&this._grid.splice(b,1)}return this},e.prototype.init=function(){this._grid={},j.apply(this,arguments)},e.prototype.gridExists=function(a){return Boolean(this._grid[a])},e.prototype.grid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.unGrid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.grids=function(){var a,b,c=[];for(b in this._grid)this._grid.hasOwnProperty(b)&&(a=this._grid[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Grid"),b.exports=l},{"./Collection":7,"./CollectionGroup":8,"./ReactorIO":38,"./Shared":40,"./View":42}],14:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a,b){this.init.apply(this,arguments)};h.prototype.init=function(a,b){if(this._options=b,this._selector=window.jQuery(this._options.selector),!this._selector[0])throw this.classIdentifier()+' "'+a.name()+'": Chart target element does not exist via selector: '+this._options.selector;this._listeners={},this._collection=a,this._options.series=[],b.chartOptions=b.chartOptions||{},b.chartOptions.credits=!1;var c,d,e;switch(this._options.type){case"pie":this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts(),c=this._collection.find(),d={allowPointSelect:!0,cursor:"pointer",dataLabels:{enabled:!0,format:"<b>{point.name}</b>: {y} ({point.percentage:.0f}%)",style:{color:window.Highcharts.theme&&window.Highcharts.theme.contrastTextColor||"black"}}},e=this.pieDataFromCollectionData(c,this._options.keyField,this._options.valField),window.jQuery.extend(d,this._options.seriesOptions),window.jQuery.extend(d,{name:this._options.seriesName,data:e}),this._chart.addSeries(d,!0,!0);break;case"line":case"area":case"column":case"bar":e=this.seriesDataFromCollectionData(this._options.seriesField,this._options.keyField,this._options.valField,this._options.orderBy,this._options),this._options.chartOptions.xAxis=e.xAxis,this._options.chartOptions.series=e.series,this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts();break;default:throw this.classIdentifier()+' "'+a.name()+'": Chart type specified is not currently supported by ForerunnerDB: '+this._options.type}this._hookEvents()},d.addModule("Highchart",h),e=d.modules.Collection,f=e.prototype.init,d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.Events"),d.synthesize(h.prototype,"state"),h.prototype.pieDataFromCollectionData=function(a,b,c){var d,e=[];for(d=0;d<a.length;d++)e.push([a[d][b],a[d][c]]);return e},h.prototype.seriesDataFromCollectionData=function(a,b,c,d,e){var f,g,h,i,j,k,l,m=this._collection.distinct(a),n=[],o=e&&e.chartOptions&&e.chartOptions.xAxis?e.chartOptions.xAxis:{categories:[]};for(k=0;k<m.length;k++){for(f=m[k],g={},g[a]=f,i=[],h=this._collection.find(g,{orderBy:d}),l=0;l<h.length;l++)o.categories?(o.categories.push(h[l][b]),i.push(h[l][c])):i.push([h[l][b],h[l][c]]);if(j={name:f,data:i},e.seriesOptions)for(l in e.seriesOptions)e.seriesOptions.hasOwnProperty(l)&&(j[l]=e.seriesOptions[l]);n.push(j)}return{xAxis:o,series:n}},h.prototype._hookEvents=function(){var a=this;a._collection.on("change",function(){a._changeListener.apply(a,arguments)}),a._collection.on("drop",function(){a.drop.apply(a)})},h.prototype._changeListener=function(){var a=this;if("undefined"!=typeof a._collection&&a._chart){var b,c=a._collection.find();switch(a._options.type){case"pie":a._chart.series[0].setData(a.pieDataFromCollectionData(c,a._options.keyField,a._options.valField),!0,!0);break;case"bar":case"line":case"area":case"column":var d=a.seriesDataFromCollectionData(a._options.seriesField,a._options.keyField,a._options.valField,a._options.orderBy,a._options);for(d.xAxis.categories&&a._chart.xAxis[0].setCategories(d.xAxis.categories),b=0;b<d.series.length;b++)a._chart.series[b]?a._chart.series[b].setData(d.series[b].data,!0,!0):a._chart.addSeries(d.series[b],!0,!0)}}},h.prototype.drop=function(a){return this.isDropped()?!0:(this._state="dropped",this._chart&&this._chart.destroy(),this._collection&&(this._collection.off("change",this._changeListener),this._collection.off("drop",this.drop),this._collection._highcharts&&delete this._collection._highcharts[this._options.selector]),delete this._chart,delete this._options,delete this._collection,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0)},e.prototype.init=function(){this._highcharts={},f.apply(this,arguments)},e.prototype.pieChart=new g({object:function(a){return a.type="pie",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="pie",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.selector=a,e.keyField=b,e.valField=c,e.seriesName=d,this.pieChart(e)}}),e.prototype.lineChart=new g({string:function(a){return this._highcharts[a]},object:function(a){return a.type="line",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="line",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.lineChart(e)}}),e.prototype.areaChart=new g({object:function(a){return a.type="area",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="area",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.areaChart(e)}}),e.prototype.columnChart=new g({object:function(a){return a.type="column",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="column",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.columnChart(e)}}),e.prototype.barChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.barChart(e)}}),e.prototype.stackedBarChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",a.plotOptions=a.plotOptions||{},a.plotOptions.series=a.plotOptions.series||{},a.plotOptions.series.stacking=a.plotOptions.series.stacking||"normal",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.stackedBarChart(e)}}),e.prototype.dropChart=function(a){this._highcharts&&this._highcharts[a]&&this._highcharts[a].drop()},d.finishModule("Highchart"),b.exports=h},{"./Overload":32,"./Shared":40}],15:[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:!1,this.unique(b&&b.unique?b.unique:!1),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;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}},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):!1},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):!1},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){var c,d,e,f,g=this._btree.keys();for(f=0;f<g.length;f++)if(c=g[f].path,d=h.get(a,c),"object"==typeof d)return d.$near&&(e=[],e=e.concat(this.near(c,d.$near,b))),d.$geoWithin&&(e=[],e=e.concat(this.geoWithin(c,d.$geoWithin,b))),e;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c){var d,e,f,g,k,l,m,n,o,p,q,r=this,s=[],t=this._collection.primaryKey();if("km"===b.$distanceUnits){for(m=b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}else if("miles"===b.$distanceUnits){for(m=1.60934*b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}for(d=i.encode(b.$point[0],b.$point[1],l),e=i.calculateNeighbours(d,{type:"array"}),k=[],f=0,q=0;9>q;q++)g=this._btree.startsWith(a,e[q]),f+=g._visited,k=k.concat(g);if(k=this._collection._primaryIndex.lookup(k),k.length){for(n={},q=0;q<k.length;q++)p=h.get(k[q],a),o=n[k[q][t]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],p[0],p[1]),m>=o&&s.push(k[q]);s.sort(function(a,b){return r.sortAsc(n[a[t]],n[b[t]])})}return s},k.prototype.geoWithin=function(a,b,c){return[]},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":5,"./GeoHash":12,"./Path":34,"./Shared":40}],16:[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:!1,this.unique(b&&b.unique?b.unique:!1),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;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},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):!1},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){return this._btree.lookup(a,b)},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":5,"./Path":34,"./Shared":40}],17:[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._size=0,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.index.hashed=f,d.finishModule("IndexHashMap"),b.exports=f},{"./Path":34,"./Shared":40}],18:[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=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;c>b;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(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):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":40}],19:[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":31,"./Shared":40}],20:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],21:[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)}},chainWillSend:function(){return Boolean(this._chain)},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length,h=this.decouple(b,g);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&&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},{}],22:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,make:function(a){return h.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;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return JSON.parse(a,h.reviver())},jStringify:function(a){return JSON.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},hash:function(a){return JSON.stringify(a)},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"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}},b.exports=d},{"./Overload":32,"./Serialiser":39}],23:[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},{}],24:[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":32}],25:[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 c>b;case"$lte":return c>=b;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;j>h;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;m>k;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"$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;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},{}],26:[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},{}],27:[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},{}],28:[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.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):!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},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):!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._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;h>g;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;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":32}],29:[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)},_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},{}],30:[function(a,b,c){"use strict";var d,e,f,g,h,i=a("./Shared");g=function(){this.init.apply(this,arguments)},g.prototype.init=function(a){var b=this;b._core=a,b.rootPath("/fdb")},i.addModule("NodeApiClient",g),i.mixin(g.prototype,"Mixin.Common"),i.mixin(g.prototype,"Mixin.Events"),i.mixin(g.prototype,"Mixin.ChainReactor"),d=i.modules.Core,e=d.prototype.init,f=i.modules.Collection,h=i.overload,i.synthesize(g.prototype,"rootPath"),g.prototype.server=function(a,b){return void 0!==a?("/"===a.substr(a.length-1,1)&&(a=a.substr(0,a.length-1)),void 0!==b?this._server=a+":"+b:this._server=a,this._host=a,this._port=b,this):void 0!==b?{host:this._host,port:this._port,url:this._server}:this._server},g.prototype.http=function(a,b,c,d,e){var f,g,h,i=this,j=new XMLHttpRequest;switch(a=a.toUpperCase(),j.onreadystatechange=function(){4===j.readyState&&(200===j.status?j.responseText?e(!1,i.jParse(j.responseText)):e(!1,{}):204===j.status?e(!1,{}):(e(j.status,j.responseText),i.emit("httpError",j.status,j.responseText)))},a){case"GET":case"DELETE":case"HEAD":this._sessionData&&(c=void 0!==c?c:{},c[this._sessionData.key]=this._sessionData.obj),f=b+(void 0!==c?"?"+i.jStringify(c):""),h=null;break;case"POST":case"PUT":case"PATCH":this._sessionData&&(g={},g[this._sessionData.key]=this._sessionData.obj),f=b+(void 0!==g?"?"+i.jStringify(g):""),h=void 0!==c?i.jStringify(c):null;break;default:return!1}return j.open(a,f,!0),j.setRequestHeader("Content-Type","application/json;charset=UTF-8"),j.send(h),this},g.prototype.head=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("HEAD",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.get=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("GET",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.put=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("PUT",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.post=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("POST",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.patch=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("PATCH",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.postPatch=function(a,b,c,d,e){var f=this;this.head(a+"/"+b,void 0,{},function(g,h){return g?404===g?f.http("POST",f.server()+f._rootPath+a,c,d,e):void e(g,c):f.http("PATCH",f.server()+f._rootPath+a+"/"+b,c,d,e)})},g.prototype["delete"]=new h({"string, function":function(a,b){return this.$main.call(this,a,void 0,{},b)},"string, *, function":function(a,b,c){return this.$main.call(this,a,b,{},c)},"string, *, object, function":function(a,b,c,d){return this.$main.call(this,a,b,c,d)},$main:function(a,b,c,d){return this.http("DELETE",this.server()+this._rootPath+a,b,c,d)}}),g.prototype.session=function(a,b){return void 0!==a&&void 0!==b?(this._sessionData={key:a,obj:b},this):this._sessionData},g.prototype.sync=function(a,b,c,d,e){var f,g,h,j=this,k="",l=!0;this.debug()&&console.log(this.logIdentifier()+" Connecting to API server "+this.server()+this._rootPath+b),g=this.server()+this._rootPath+b+"/_sync",this._sessionData&&(h=h||{},this._sessionData.key?h[this._sessionData.key]=this._sessionData.obj:i.mixin(h,this._sessionData.obj)),c&&(h=h||{},h.$query=c),d&&(h=h||{},void 0===d.$initialData&&(d.$initialData=!0),h.$options=d),h&&(k=this.jStringify(h),g+="?"+k),f=new EventSource(g),a.__apiConnection=f,f.addEventListener("open",function(c){(!d||d&&d.$initialData)&&j.get(b,h,function(b,c){b||a.upsert(c)})},!1),f.addEventListener("error",function(b){2===f.readyState&&a.unSync(),l&&(l=!1,e(b))},!1),f.addEventListener("insert",function(b){var c=j.jParse(b.data);a.insert(c.dataSet)},!1),f.addEventListener("update",function(b){var c=j.jParse(b.data);a.update(c.query,c.update)},!1),f.addEventListener("remove",function(b){var c=j.jParse(b.data);a.remove(c.query)},!1),e&&f.addEventListener("connected",function(a){l&&(l=!1,e(!1))},!1)},f.prototype.sync=new h({"function":function(a){this.$main.call(this,"/"+this._db.name()+"/collection/"+this.name(),null,null,a)},"string, function":function(a,b){this.$main.call(this,"/"+this._db.name()+"/collection/"+a,null,null,b)},"object, function":function(a,b){this.$main.call(this,"/"+this._db.name()+"/collection/"+this.name(),a,null,b)},"string, string, function":function(a,b,c){this.$main.call(this,"/"+this._db.name()+"/"+a+"/"+b,null,null,c)},"string, object, function":function(a,b,c){this.$main.call(this,"/"+this._db.name()+"/collection/"+a,b,null,c)},"string, string, object, function":function(a,b,c,d){this.$main.call(this,"/"+this._db.name()+"/"+a+"/"+b,c,null,d)},"object, object, function":function(a,b,c){this.$main.call(this,"/"+this._db.name()+"/collection/"+this.name(),a,b,c)},"string, object, object, function":function(a,b,c,d){this.$main.call(this,"/"+this._db.name()+"/collection/"+a,b,c,d)},"string, string, object, object, function":function(a,b,c,d,e){this.$main.call(this,"/"+this._db.name()+"/"+a+"/"+b,c,d,e)},$main:function(a,b,c,d){var e=this;if(!this._db||!this._db._core)throw this.logIdentifier()+" Cannot sync for an anonymous collection! (Collection must be attached to a database)";this.unSync(),this._db._core.api.sync(this,a,b,c,d),this.on("drop",function(){e.unSync()})}}),f.prototype.unSync=function(){return this.__apiConnection?(2!==this.__apiConnection.readyState&&this.__apiConnection.close(),delete this.__apiConnection,!0):!1},f.prototype.http=new h({"string, function":function(a,b){this.$main.call(this,a,"/"+this._db.name()+"/collection/"+this.name(),void 0,void 0,{},b)},$main:function(a,b,c,d,e,f){if(this._db&&this._db._core)return this._db._core.api.http("GET",this._db._core.api.server()+this._rootPath+b,{$query:c,$options:d},e,f);throw this.logIdentifier()+" Cannot do HTTP for an anonymous collection! (Collection must be attached to a database)"}}),f.prototype.autoHttp=new h({"string, function":function(a,b){this.$main.call(this,a,"/"+this._db.name()+"/collection/"+this.name(),void 0,void 0,{},b)},"string, string, function":function(a,b,c){this.$main.call(this,a,"/"+this._db.name()+"/collection/"+b,void 0,void 0,{},c)},"string, string, string, function":function(a,b,c,d){this.$main.call(this,a,"/"+this._db.name()+"/"+b+"/"+c,void 0,void 0,{},d)},"string, string, string, object, function":function(a,b,c,d,e){this.$main.call(this,a,"/"+this._db.name()+"/"+b+"/"+c,d,void 0,{},e)},"string, string, string, object, object, function":function(a,b,c,d,e,f){this.$main.call(this,a,"/"+this._db.name()+"/"+b+"/"+c,d,e,{},f)},$main:function(a,b,c,d,e,f){var g=this;if(this._db&&this._db._core)return this._db._core.api.http("GET",this._db._core.api.server()+this._db._core.api._rootPath+b,{$query:c,$options:d},e,function(b,c){var d;if(!b&&c)switch(a){case"GET":g.insert(c);break;case"POST":c.inserted&&c.inserted.length&&g.insert(c.inserted);break;case"PUT":case"PATCH":if(c instanceof Array)for(d=0;d<c.length;d++)g.updateById(c[d]._id,{$overwrite:c[d]});else g.updateById(c._id,{$overwrite:c});break;case"DELETE":g.remove(c)}f(b,c)});throw this.logIdentifier()+" Cannot do HTTP for an anonymous collection! (Collection must be attached to a database)"}}),d.prototype.init=function(){e.apply(this,arguments),this.api=new g(this)},i.finishModule("NodeApiClient"),b.exports=g},{"./Shared":40}],31:[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":34,"./Shared":40}],32:[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,""),-1===f.indexOf("*"))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;d>c;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},{}],33:[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;this._name=a,this._data=new g("__FDB__dc_data_"+this._name),this._collData=new f,this._sources=[],this._sourceDroppedWrap=function(){b._sourceDropped.apply(b,arguments)}},d.addModule("Overview",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.Events"),d.mixin(h.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./Document"),e=d.modules.Db,d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),d.synthesize(h.prototype,"query",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"queryOptions",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"reduce",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),h.prototype.from=function(a){return void 0!==a?("string"==typeof a&&(a=this._db.collection(a)),this._setFrom(a),this):this._sources},h.prototype.find=function(){return this._collData.find.apply(this._collData,arguments)},h.prototype.exec=function(){var a=this.reduce();return a?a.apply(this):void 0},h.prototype.count=function(){return this._collData.count.apply(this._collData,arguments)},h.prototype._setFrom=function(a){for(;this._sources.length;)this._removeSource(this._sources[0]);return this._addSource(a),this},h.prototype._addSource=function(a){return a&&"View"===a.className&&(a=a.data(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),-1===this._sources.indexOf(a)&&(this._sources.push(a),a.chain(this),a.on("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._removeSource=function(a){a&&"View"===a.className&&(a=a.data(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking'));var b=this._sources.indexOf(a);return b>-1&&(this._sources.splice(a,1),a.unChain(this),a.off("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._sourceDropped=function(a){a&&this._removeSource(a)},h.prototype._refresh=function(){if(!this.isDropped()){if(this._sources&&this._sources[0]){this._collData.primaryKey(this._sources[0].primaryKey());var a,b=[];for(a=0;a<this._sources.length;a++)b=b.concat(this._sources[a].find(this._query,this._queryOptions));this._collData.setData(b)}if(this._reduce){var c=this._reduce.apply(this);this._data.setData(c)}}},h.prototype._chainHandler=function(a){switch(a.type){case"setData":case"insert":case"update":case"remove":this._refresh()}},h.prototype.data=function(){return this._data},h.prototype.drop=function(a){if(!this.isDropped()){for(this._state="dropped",delete this._data,delete this._collData;this._sources.length;)this._removeSource(this._sources[0]);delete this._sources,this._db&&this._name&&delete this._db._overview[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._listeners}return!0},e.prototype.overview=function(a){var b=this;return a?a instanceof h?a:this._overview&&this._overview[a]?this._overview[a]:(this._overview=this._overview||{},this._overview[a]=new h(a).db(this),b.emit("create",b._overview[a],"overview",a),this._overview[a]):this._overview||{}},e.prototype.overviews=function(){var a,b,c=[];for(b in this._overview)this._overview.hasOwnProperty(b)&&(a=this._overview[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Overview"),b.exports=h},{"./Collection":7,"./Document":11,"./Shared":40}],34:[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&&-1===b.indexOf("."))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;f>k;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;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":40}],35:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("async"),o=a("localforage");a("./PersistCompress"),a("./PersistCrypto");k=function(){this.init.apply(this,arguments)},k.prototype.localforage=o,k.prototype.init=function(a){var b=this;this._encodeSteps=[function(){return b._encode.apply(b,arguments)}],this._decodeSteps=[function(){return b._decode.apply(b,arguments)}],a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),o.config({driver:[o.INDEXEDDB,o.WEBSQL,o.LOCALSTORAGE],name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),m.mixin(k.prototype,"Mixin.Common"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,m.synthesize(k.prototype,"auto",function(a){var b=this;return void 0!==a&&(a?(this._db.on("create",function(){b._autoLoad.apply(b,arguments)}),this._db.on("change",function(){b._autoSave.apply(b,arguments)}),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save enabled")):(this._db.off("create",this._autoLoad),this._db.off("change",this._autoSave),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save disbled"))),this.$super.call(this,a)}),k.prototype._autoLoad=function(a,b,c){var d=this;"function"==typeof a.load?(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-loading data for "+b+":",c),a.load(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic load failed:",a),d.emit("load",a,b)})):d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-load for "+b+":",c,"no load method, skipping")},k.prototype._autoSave=function(a,b,c){var d=this;"function"==typeof a.save&&(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-saving data for "+b+":",c),a.save(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic save failed:",a),d.emit("save",a,b)}))},k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":o.setDriver(o.LOCALSTORAGE);break;case"WEBSQL":o.setDriver(o.WEBSQL);break;case"INDEXEDDB":o.setDriver(o.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return o.driver()},k.prototype.decode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._decodeSteps),b)},k.prototype.encode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._encodeSteps),b)},m.synthesize(k.prototype,"encodeSteps"),m.synthesize(k.prototype,"decodeSteps"),k.prototype.addStep=new l({object:function(a){this.$main.call(this,function(){a.encode.apply(a,arguments)},function(){a.decode.apply(a,arguments)},0)},"function, function":function(a,b){this.$main.call(this,a,b,0)},"function, function, number":function(a,b,c){this.$main.call(this,a,b,c)},$main:function(a,b,c){0===c||void 0===c?(this._encodeSteps.push(a),this._decodeSteps.unshift(b)):(this._encodeSteps.splice(c,0,a), this._decodeSteps.splice(this._decodeSteps.length-c,0,b))}}),k.prototype.unwrap=function(a){var b,c=a.split("::fdb::");switch(c[0]){case"json":b=this.jParse(c[1]);break;case"raw":b=c[1]}},k.prototype._decode=function(a,b,c){var d,e;if(a){switch(d=a.split("::fdb::"),d[0]){case"json":e=this.jParse(d[1]);break;case"raw":e=d[1]}e?(b.foundData=!0,b.rowCount=e.length||0):(b.foundData=!1,b.rowCount=0),c&&c(!1,e,b)}else b.foundData=!1,b.rowCount=0,c&&c(!1,a,b)},k.prototype._encode=function(a,b,c){var d=a;a="object"==typeof a?"json::fdb::"+this.jStringify(a):"raw::fdb::"+a,d?(b.foundData=!0,b.rowCount=d.length||0):(b.foundData=!1,b.rowCount=0),c&&c(!1,a,b)},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){b?c(b):o.setItem(a,d).then(function(a){c&&c(!1,a,e)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c=this;switch(this.mode()){case"localforage":o.getItem(a).then(function(a){c.decode(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":o.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){this.isDropped()||this.drop(!0)},"function":function(a){this.isDropped()||this.drop(!0,a)},"boolean":function(a){if(!this.isDropped()){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";this._db&&(this._db.persist.drop(this._db._name+"-"+this._name),this._db.persist.drop(this._db._name+"-"+this._name+"-metaData"))}f.call(this)}},"boolean, function":function(a,b){var c=this;if(!this.isDropped()){if(!a)return f.call(this,b);if(this._name){if(this._db)return this._db.persist.drop(this._db._name+"-"+this._name,function(){c._db.persist.drop(c._db._name+"-"+c._name+"-metaData",b)}),f.call(this);b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!")}else b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")}}}),e.prototype.save=function(a){var b,c=this;c._name?c._db?(b=function(){c._db.persist.save(c._db._name+"-"+c._name,c._data,function(b,d,e){b?a&&a(b):c._db.persist.save(c._db._name+"-"+c._name+"-metaData",c.metaData(),function(b,f,g){a&&a(b,e,g,{tableData:d,metaData:f,tableDataName:c._db._name+"-"+c._name,metaDataName:c._db._name+"-"+c._name+"-metaData"})})})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;b._name?b._db?b._db.persist.load(b._db._name+"-"+b._name,function(c,d,e){c?a&&a(c):b.remove({},function(){d=d||[],b.insert(d,function(){b._db.persist.load(b._db._name+"-"+b._name+"-metaData",function(c,d,f){c||d&&b.metaData(d),a&&a(c,e,f)})})})}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},e.prototype.saveCustom=function(a){var b,c=this,d={};c._name?c._db?(b=function(){c.encode(c._data,function(b,e,f){b?a(b):(d.data={name:c._db._name+"-"+c._name,store:e,tableStats:f},c.encode(c._data,function(b,e,f){b?a(b):(d.metaData={name:c._db._name+"-"+c._name+"-metaData",store:e,tableStats:f},a(!1,d))}))})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.loadCustom=function(a,b){var c=this;c._name?c._db?a.data&&a.data.store?a.metaData&&a.metaData.store?c.decode(a.data.store,function(d,e,f){d?b(d):e&&(c.remove({}),c.insert(e),c.decode(a.metaData.store,function(a,d,e){a?b(a):d&&(c.metaData(d),b&&b(a,f,e))}))}):b('No "metaData" key found in passed object!'):b('No "data" key found in passed object!'):b&&b("Cannot load a collection that is not attached to a database!"):b&&b("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a?e[d].loadCustom(a,c):e[d].load(c))}}),d.prototype.save=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a.custom?e[d].saveCustom(c):e[d].save(c))}}),m.finishModule("Persist"),b.exports=k},{"./Collection":7,"./CollectionGroup":8,"./PersistCompress":36,"./PersistCrypto":37,"./Shared":40,async:43,localforage:78}],36:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("pako"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){},d.mixin(f.prototype,"Mixin.Common"),f.prototype.encode=function(a,b,c){var d,f,g,h={data:a,type:"fdbCompress",enabled:!1};d=a.length,g=e.deflate(a,{to:"string"}),f=g.length,d>f&&(h.data=g,h.enabled=!0),b.compression={enabled:h.enabled,compressedBytes:f,uncompressedBytes:d,effect:Math.round(100/d*f)+"%"},c(!1,this.jStringify(h),b)},f.prototype.decode=function(a,b,c){var d,f=!1;a?(a=this.jParse(a),a.enabled?(d=e.inflate(a.data,{to:"string"}),f=!0):(d=a.data,f=!1),b.compression={enabled:f},c&&c(!1,d,b)):c&&c(!1,d,b)},d.plugins.FdbCompress=f,b.exports=f},{"./Shared":40,pako:79}],37:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("crypto-js"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){if(!a||!a.pass)throw'Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.';this._algo=a.algo||"AES",this._pass=a.pass},d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"pass"),f.prototype.stringify=function(a){var b={ct:a.ciphertext.toString(e.enc.Base64)};return a.iv&&(b.iv=a.iv.toString()),a.salt&&(b.s=a.salt.toString()),this.jStringify(b)},f.prototype.parse=function(a){var b=this.jParse(a),c=e.lib.CipherParams.create({ciphertext:e.enc.Base64.parse(b.ct)});return b.iv&&(c.iv=e.enc.Hex.parse(b.iv)),b.s&&(c.salt=e.enc.Hex.parse(b.s)),c},f.prototype.encode=function(a,b,c){var d,f=this,g={type:"fdbCrypto"};d=e[this._algo].encrypt(a,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}),g.data=d.toString(),g.enabled=!0,b.encryption={enabled:g.enabled},c&&c(!1,this.jStringify(g),b)},f.prototype.decode=function(a,b,c){var d,f=this;a?(a=this.jParse(a),d=e[this._algo].decrypt(a.data,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}).toString(e.enc.Utf8),c&&c(!1,d,b)):c&&c(!1,a,b)},d.plugins.FdbCrypto=f,b.exports=f},{"./Shared":40,"crypto-js":52}],38:[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":40}],39:[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):!1},function(b){return"string"==typeof b&&0===b.indexOf("$date:")?a.convert(new Date(b.substr(6))):void 0}),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):!1},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},{}],40:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.766",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":20,"./Mixin.ChainReactor":21,"./Mixin.Common":22,"./Mixin.Constants":23,"./Mixin.Events":24,"./Mixin.Matching":25,"./Mixin.Sorting":26,"./Mixin.Tags":27,"./Mixin.Triggers":28,"./Mixin.Updating":29,"./Overload":32}],41:[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={}},{}],42:[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.Triggers"),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?!1:(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):!0):!1)},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(){this._from.update.apply(this._from,arguments)},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;c>d;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;c>d;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;c>d;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.drop=function(a){return this.isDropped()?!1:(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._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._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._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,0>d&&(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;c>d;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._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.emit("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():!1}));return c},d.finishModule("View"),b.exports=o},{"./ActiveBucket":3,"./Collection":7,"./CollectionGroup":8,"./Overload":32,"./ReactorIO":38,"./Shared":40}],43:[function(a,b,c){(function(a,c){!function(){function d(){}function e(a){return a}function f(a){return!!a}function g(a){return!a}function h(a){return function(){if(null===a)throw new Error("Callback was already called.");a.apply(this,arguments),a=null}}function i(a){return function(){null!==a&&(a.apply(this,arguments),a=null)}}function j(a){return N(a)||"number"==typeof a.length&&a.length>=0&&a.length%1===0}function k(a,b){for(var c=-1,d=a.length;++c<d;)b(a[c],c,a)}function l(a,b){for(var c=-1,d=a.length,e=Array(d);++c<d;)e[c]=b(a[c],c,a);return e}function m(a){return l(Array(a),function(a,b){return b})}function n(a,b,c){return k(a,function(a,d,e){c=b(c,a,d,e)}),c}function o(a,b){k(P(a),function(c){b(a[c],c)})}function p(a,b){for(var c=0;c<a.length;c++)if(a[c]===b)return c;return-1}function q(a){var b,c,d=-1;return j(a)?(b=a.length,function(){return d++,b>d?d:null}):(c=P(a),b=c.length,function(){return d++,b>d?c[d]:null})}function r(a,b){return b=null==b?a.length-1:+b,function(){for(var c=Math.max(arguments.length-b,0),d=Array(c),e=0;c>e;e++)d[e]=arguments[e+b];switch(b){case 0:return a.call(this,d);case 1:return a.call(this,arguments[0],d)}}}function s(a){return function(b,c,d){return a(b,d)}}function t(a){return function(b,c,e){e=i(e||d),b=b||[];var f=q(b);if(0>=a)return e(null);var g=!1,j=0,k=!1;!function l(){if(g&&0>=j)return e(null);for(;a>j&&!k;){var d=f();if(null===d)return g=!0,void(0>=j&&e(null));j+=1,c(b[d],d,h(function(a){j-=1,a?(e(a),k=!0):l()}))}}()}}function u(a){return function(b,c,d){return a(K.eachOf,b,c,d)}}function v(a){return function(b,c,d,e){return a(t(c),b,d,e)}}function w(a){return function(b,c,d){return a(K.eachOfSeries,b,c,d)}}function x(a,b,c,e){e=i(e||d),b=b||[];var f=j(b)?[]:{};a(b,function(a,b,d){c(a,function(a,c){f[b]=c,d(a)})},function(a){e(a,f)})}function y(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(c){c&&e.push({index:b,value:a}),d()})},function(){d(l(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})}function z(a,b,c,d){y(a,b,function(a,b){c(a,function(a){b(!a)})},d)}function A(a,b,c){return function(d,e,f,g){function h(){g&&g(c(!1,void 0))}function i(a,d,e){return g?void f(a,function(d){g&&b(d)&&(g(c(!0,a)),g=f=!1),e()}):e()}arguments.length>3?a(d,e,i,h):(g=f,f=e,a(d,i,h))}}function B(a,b){return b}function C(a,b,c){c=c||d;var e=j(b)?[]:{};a(b,function(a,b,c){a(r(function(a,d){d.length<=1&&(d=d[0]),e[b]=d,c(a)}))},function(a){c(a,e)})}function D(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(a,b){e=e.concat(b||[]),d(a)})},function(a){d(a,e)})}function E(a,b,c){function e(a,b,c,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length&&a.idle()?K.setImmediate(function(){a.drain()}):(k(b,function(b){var f={data:b,callback:e||d};c?a.tasks.unshift(f):a.tasks.push(f),a.tasks.length===a.concurrency&&a.saturated()}),void K.setImmediate(a.process))}function f(a,b){return function(){g-=1;var c=!1,d=arguments;k(b,function(a){k(i,function(b,d){b!==a||c||(i.splice(d,1),c=!0)}),a.callback.apply(a,d)}),a.tasks.length+g===0&&a.drain(),a.process()}}if(null==b)b=1;else if(0===b)throw new Error("Concurrency must not be zero");var g=0,i=[],j={tasks:[],concurrency:b,payload:c,saturated:d,empty:d,drain:d,started:!1,paused:!1,push:function(a,b){e(j,a,!1,b)},kill:function(){j.drain=d,j.tasks=[]},unshift:function(a,b){e(j,a,!0,b)},process:function(){for(;!j.paused&&g<j.concurrency&&j.tasks.length;){var b=j.payload?j.tasks.splice(0,j.payload):j.tasks.splice(0,j.tasks.length),c=l(b,function(a){return a.data});0===j.tasks.length&&j.empty(),g+=1,i.push(b[0]);var d=h(f(j,b));a(c,d)}},length:function(){return j.tasks.length},running:function(){return g},workersList:function(){return i},idle:function(){return j.tasks.length+g===0},pause:function(){j.paused=!0},resume:function(){if(j.paused!==!1){j.paused=!1;for(var a=Math.min(j.concurrency,j.tasks.length),b=1;a>=b;b++)K.setImmediate(j.process)}}};return j}function F(a){return r(function(b,c){b.apply(null,c.concat([r(function(b,c){"object"==typeof console&&(b?console.error&&console.error(b):console[a]&&k(c,function(b){console[a](b)}))})]))})}function G(a){return function(b,c,d){a(m(b),c,d)}}function H(a){return r(function(b,c){var d=r(function(c){var d=this,e=c.pop();return a(b,function(a,b,e){a.apply(d,c.concat([e]))},e)});return c.length?d.apply(this,c):d})}function I(a){return r(function(b){var c=b.pop();b.push(function(){var a=arguments;d?K.setImmediate(function(){c.apply(null,a)}):c.apply(null,a)});var d=!0;a.apply(this,b),d=!1})}var J,K={},L="object"==typeof self&&self.self===self&&self||"object"==typeof c&&c.global===c&&c||this; null!=L&&(J=L.async),K.noConflict=function(){return L.async=J,K};var M=Object.prototype.toString,N=Array.isArray||function(a){return"[object Array]"===M.call(a)},O=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a},P=Object.keys||function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b},Q="function"==typeof setImmediate&&setImmediate,R=Q?function(a){Q(a)}:function(a){setTimeout(a,0)};"object"==typeof a&&"function"==typeof a.nextTick?K.nextTick=a.nextTick:K.nextTick=R,K.setImmediate=Q?R:K.nextTick,K.forEach=K.each=function(a,b,c){return K.eachOf(a,s(b),c)},K.forEachSeries=K.eachSeries=function(a,b,c){return K.eachOfSeries(a,s(b),c)},K.forEachLimit=K.eachLimit=function(a,b,c,d){return t(b)(a,s(c),d)},K.forEachOf=K.eachOf=function(a,b,c){function e(a){j--,a?c(a):null===f&&0>=j&&c(null)}c=i(c||d),a=a||[];for(var f,g=q(a),j=0;null!=(f=g());)j+=1,b(a[f],f,h(e));0===j&&c(null)},K.forEachOfSeries=K.eachOfSeries=function(a,b,c){function e(){var d=!0;return null===g?c(null):(b(a[g],g,h(function(a){if(a)c(a);else{if(g=f(),null===g)return c(null);d?K.setImmediate(e):e()}})),void(d=!1))}c=i(c||d),a=a||[];var f=q(a),g=f();e()},K.forEachOfLimit=K.eachOfLimit=function(a,b,c,d){t(b)(a,c,d)},K.map=u(x),K.mapSeries=w(x),K.mapLimit=v(x),K.inject=K.foldl=K.reduce=function(a,b,c,d){K.eachOfSeries(a,function(a,d,e){c(b,a,function(a,c){b=c,e(a)})},function(a){d(a,b)})},K.foldr=K.reduceRight=function(a,b,c,d){var f=l(a,e).reverse();K.reduce(f,b,c,d)},K.transform=function(a,b,c,d){3===arguments.length&&(d=c,c=b,b=N(a)?[]:{}),K.eachOf(a,function(a,d,e){c(b,a,d,e)},function(a){d(a,b)})},K.select=K.filter=u(y),K.selectLimit=K.filterLimit=v(y),K.selectSeries=K.filterSeries=w(y),K.reject=u(z),K.rejectLimit=v(z),K.rejectSeries=w(z),K.any=K.some=A(K.eachOf,f,e),K.someLimit=A(K.eachOfLimit,f,e),K.all=K.every=A(K.eachOf,g,g),K.everyLimit=A(K.eachOfLimit,g,g),K.detect=A(K.eachOf,e,B),K.detectSeries=A(K.eachOfSeries,e,B),K.detectLimit=A(K.eachOfLimit,e,B),K.sortBy=function(a,b,c){function d(a,b){var c=a.criteria,d=b.criteria;return d>c?-1:c>d?1:0}K.map(a,function(a,c){b(a,function(b,d){b?c(b):c(null,{value:a,criteria:d})})},function(a,b){return a?c(a):void c(null,l(b.sort(d),function(a){return a.value}))})},K.auto=function(a,b,c){function e(a){s.unshift(a)}function f(a){var b=p(s,a);b>=0&&s.splice(b,1)}function g(){j--,k(s.slice(0),function(a){a()})}"function"==typeof arguments[1]&&(c=b,b=null),c=i(c||d);var h=P(a),j=h.length;if(!j)return c(null);b||(b=j);var l={},m=0,q=!1,s=[];e(function(){j||c(null,l)}),k(h,function(d){function h(){return b>m&&n(t,function(a,b){return a&&l.hasOwnProperty(b)},!0)&&!l.hasOwnProperty(d)}function i(){h()&&(m++,f(i),k[k.length-1](s,l))}if(!q){for(var j,k=N(a[d])?a[d]:[a[d]],s=r(function(a,b){if(m--,b.length<=1&&(b=b[0]),a){var e={};o(l,function(a,b){e[b]=a}),e[d]=b,q=!0,c(a,e)}else l[d]=b,K.setImmediate(g)}),t=k.slice(0,k.length-1),u=t.length;u--;){if(!(j=a[t[u]]))throw new Error("Has nonexistent dependency in "+t.join(", "));if(N(j)&&p(j,d)>=0)throw new Error("Has cyclic dependencies")}h()?(m++,k[k.length-1](s,l)):e(i)}})},K.retry=function(a,b,c){function d(a,b){if("number"==typeof b)a.times=parseInt(b,10)||f;else{if("object"!=typeof b)throw new Error("Unsupported argument type for 'times': "+typeof b);a.times=parseInt(b.times,10)||f,a.interval=parseInt(b.interval,10)||g}}function e(a,b){function c(a,c){return function(d){a(function(a,b){d(!a||c,{err:a,result:b})},b)}}function d(a){return function(b){setTimeout(function(){b(null)},a)}}for(;i.times;){var e=!(i.times-=1);h.push(c(i.task,e)),!e&&i.interval>0&&h.push(d(i.interval))}K.series(h,function(b,c){c=c[c.length-1],(a||i.callback)(c.err,c.result)})}var f=5,g=0,h=[],i={times:f,interval:g},j=arguments.length;if(1>j||j>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=j&&"function"==typeof a&&(c=b,b=a),"function"!=typeof a&&d(i,a),i.callback=c,i.task=b,i.callback?e():e},K.waterfall=function(a,b){function c(a){return r(function(d,e){if(d)b.apply(null,[d].concat(e));else{var f=a.next();f?e.push(c(f)):e.push(b),I(a).apply(null,e)}})}if(b=i(b||d),!N(a)){var e=new Error("First argument to waterfall must be an array of functions");return b(e)}return a.length?void c(K.iterator(a))():b()},K.parallel=function(a,b){C(K.eachOf,a,b)},K.parallelLimit=function(a,b,c){C(t(b),a,c)},K.series=function(a,b){C(K.eachOfSeries,a,b)},K.iterator=function(a){function b(c){function d(){return a.length&&a[c].apply(null,arguments),d.next()}return d.next=function(){return c<a.length-1?b(c+1):null},d}return b(0)},K.apply=r(function(a,b){return r(function(c){return a.apply(null,b.concat(c))})}),K.concat=u(D),K.concatSeries=w(D),K.whilst=function(a,b,c){if(c=c||d,a()){var e=r(function(d,f){d?c(d):a.apply(this,f)?b(e):c.apply(null,[null].concat(f))});b(e)}else c(null)},K.doWhilst=function(a,b,c){var d=0;return K.whilst(function(){return++d<=1||b.apply(this,arguments)},a,c)},K.until=function(a,b,c){return K.whilst(function(){return!a.apply(this,arguments)},b,c)},K.doUntil=function(a,b,c){return K.doWhilst(a,function(){return!b.apply(this,arguments)},c)},K.during=function(a,b,c){c=c||d;var e=r(function(b,d){b?c(b):(d.push(f),a.apply(this,d))}),f=function(a,d){a?c(a):d?b(e):c(null)};a(f)},K.doDuring=function(a,b,c){var d=0;K.during(function(a){d++<1?a(null,!0):b.apply(this,arguments)},a,c)},K.queue=function(a,b){var c=E(function(b,c){a(b[0],c)},b,1);return c},K.priorityQueue=function(a,b){function c(a,b){return a.priority-b.priority}function e(a,b,c){for(var d=-1,e=a.length-1;e>d;){var f=d+(e-d+1>>>1);c(b,a[f])>=0?d=f:e=f-1}return d}function f(a,b,f,g){if(null!=g&&"function"!=typeof g)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length?K.setImmediate(function(){a.drain()}):void k(b,function(b){var h={data:b,priority:f,callback:"function"==typeof g?g:d};a.tasks.splice(e(a.tasks,h,c)+1,0,h),a.tasks.length===a.concurrency&&a.saturated(),K.setImmediate(a.process)})}var g=K.queue(a,b);return g.push=function(a,b,c){f(g,a,b,c)},delete g.unshift,g},K.cargo=function(a,b){return E(a,1,b)},K.log=F("log"),K.dir=F("dir"),K.memoize=function(a,b){var c={},d={},f=Object.prototype.hasOwnProperty;b=b||e;var g=r(function(e){var g=e.pop(),h=b.apply(null,e);f.call(c,h)?K.setImmediate(function(){g.apply(null,c[h])}):f.call(d,h)?d[h].push(g):(d[h]=[g],a.apply(null,e.concat([r(function(a){c[h]=a;var b=d[h];delete d[h];for(var e=0,f=b.length;f>e;e++)b[e].apply(null,a)})])))});return g.memo=c,g.unmemoized=a,g},K.unmemoize=function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},K.times=G(K.map),K.timesSeries=G(K.mapSeries),K.timesLimit=function(a,b,c,d){return K.mapLimit(m(a),b,c,d)},K.seq=function(){var a=arguments;return r(function(b){var c=this,e=b[b.length-1];"function"==typeof e?b.pop():e=d,K.reduce(a,b,function(a,b,d){b.apply(c,a.concat([r(function(a,b){d(a,b)})]))},function(a,b){e.apply(c,[a].concat(b))})})},K.compose=function(){return K.seq.apply(null,Array.prototype.reverse.call(arguments))},K.applyEach=H(K.eachOf),K.applyEachSeries=H(K.eachOfSeries),K.forever=function(a,b){function c(a){return a?e(a):void f(c)}var e=h(b||d),f=I(a);c()},K.ensureAsync=I,K.constant=r(function(a){var b=[null].concat(a);return function(a){return a.apply(this,b)}}),K.wrapSync=K.asyncify=function(a){return r(function(b){var c,d=b.pop();try{c=a.apply(this,b)}catch(e){return d(e)}O(c)&&"function"==typeof c.then?c.then(function(a){d(null,a)})["catch"](function(a){d(a.message?a:new Error(a))}):d(null,c)})},"object"==typeof b&&b.exports?b.exports=K:"function"==typeof define&&define.amd?define([],function(){return K}):L.async=K}()}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:95}],44:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.BlockCipher,e=b.algo,f=[],g=[],h=[],i=[],j=[],k=[],l=[],m=[],n=[],o=[];!function(){for(var a=[],b=0;256>b;b++)128>b?a[b]=b<<1:a[b]=b<<1^283;for(var c=0,d=0,b=0;256>b;b++){var e=d^d<<1^d<<2^d<<3^d<<4;e=e>>>8^255&e^99,f[c]=e,g[e]=c;var p=a[c],q=a[p],r=a[q],s=257*a[e]^16843008*e;h[c]=s<<24|s>>>8,i[c]=s<<16|s>>>16,j[c]=s<<8|s>>>24,k[c]=s;var s=16843009*r^65537*q^257*p^16843008*c;l[e]=s<<24|s>>>8,m[e]=s<<16|s>>>16,n[e]=s<<8|s>>>24,o[e]=s,c?(c=p^a[a[a[r^p]]],d^=a[a[d]]):c=d=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],q=e.AES=d.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes/4,d=this._nRounds=c+6,e=4*(d+1),g=this._keySchedule=[],h=0;e>h;h++)if(c>h)g[h]=b[h];else{var i=g[h-1];h%c?c>6&&h%c==4&&(i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i]):(i=i<<8|i>>>24,i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i],i^=p[h/c|0]<<24),g[h]=g[h-c]^i}for(var j=this._invKeySchedule=[],k=0;e>k;k++){var h=e-k;if(k%4)var i=g[h];else var i=g[h-4];4>k||4>=h?j[k]=i:j[k]=l[f[i>>>24]]^m[f[i>>>16&255]]^n[f[i>>>8&255]]^o[f[255&i]]}},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,h,i,j,k,f)},decryptBlock:function(a,b){var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c,this._doCryptBlock(a,b,this._invKeySchedule,l,m,n,o,g);var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c},_doCryptBlock:function(a,b,c,d,e,f,g,h){for(var i=this._nRounds,j=a[b]^c[0],k=a[b+1]^c[1],l=a[b+2]^c[2],m=a[b+3]^c[3],n=4,o=1;i>o;o++){var p=d[j>>>24]^e[k>>>16&255]^f[l>>>8&255]^g[255&m]^c[n++],q=d[k>>>24]^e[l>>>16&255]^f[m>>>8&255]^g[255&j]^c[n++],r=d[l>>>24]^e[m>>>16&255]^f[j>>>8&255]^g[255&k]^c[n++],s=d[m>>>24]^e[j>>>16&255]^f[k>>>8&255]^g[255&l]^c[n++];j=p,k=q,l=r,m=s}var p=(h[j>>>24]<<24|h[k>>>16&255]<<16|h[l>>>8&255]<<8|h[255&m])^c[n++],q=(h[k>>>24]<<24|h[l>>>16&255]<<16|h[m>>>8&255]<<8|h[255&j])^c[n++],r=(h[l>>>24]<<24|h[m>>>16&255]<<16|h[j>>>8&255]<<8|h[255&k])^c[n++],s=(h[m>>>24]<<24|h[j>>>16&255]<<16|h[k>>>8&255]<<8|h[255&l])^c[n++];a[b]=p,a[b+1]=q,a[b+2]=r,a[b+3]=s},keySize:8});b.AES=d._createHelper(q)}(),a.AES})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],45:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){a.lib.Cipher||function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=d.BufferedBlockAlgorithm,h=c.enc,i=(h.Utf8,h.Base64),j=c.algo,k=j.EvpKDF,l=d.Cipher=g.extend({cfg:e.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c),this._xformMode=a,this._key=b,this.reset()},reset:function(){g.reset.call(this),this._doReset()},process:function(a){return this._append(a),this._process()},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function a(a){return"string"==typeof a?x:u}return function(b){return{encrypt:function(c,d,e){return a(d).encrypt(b,c,d,e)},decrypt:function(c,d,e){return a(d).decrypt(b,c,d,e)}}}}()}),m=(d.StreamCipher=l.extend({_doFinalize:function(){var a=this._process(!0);return a},blockSize:1}),c.mode={}),n=d.BlockCipherMode=e.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a,this._iv=b}}),o=m.CBC=function(){function a(a,c,d){var e=this._iv;if(e){var f=e;this._iv=b}else var f=this._prevBlock;for(var g=0;d>g;g++)a[c+g]^=f[g]}var c=n.extend();return c.Encryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize;a.call(this,b,c,e),d.encryptBlock(b,c),this._prevBlock=b.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize,f=b.slice(c,c+e);d.decryptBlock(b,c),a.call(this,b,c,e),this._prevBlock=f}}),c}(),p=c.pad={},q=p.Pkcs7={pad:function(a,b){for(var c=4*b,d=c-a.sigBytes%c,e=d<<24|d<<16|d<<8|d,g=[],h=0;d>h;h+=4)g.push(e);var i=f.create(g,d);a.concat(i)},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},r=(d.BlockCipher=l.extend({cfg:l.cfg.extend({mode:o,padding:q}),reset:function(){l.reset.call(this);var a=this.cfg,b=a.iv,c=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=c.createEncryptor;else{var d=c.createDecryptor;this._minBufferSize=1}this._mode=d.call(c,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else{var b=this._process(!0);a.unpad(b)}return b},blockSize:4}),d.CipherParams=e.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}})),s=c.format={},t=s.OpenSSL={stringify:function(a){var b=a.ciphertext,c=a.salt;if(c)var d=f.create([1398893684,1701076831]).concat(c).concat(b);else var d=b;return d.toString(i)},parse:function(a){var b=i.parse(a),c=b.words;if(1398893684==c[0]&&1701076831==c[1]){var d=f.create(c.slice(2,4));c.splice(0,4),b.sigBytes-=16}return r.create({ciphertext:b,salt:d})}},u=d.SerializableCipher=e.extend({cfg:e.extend({format:t}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d),f=e.finalize(b),g=e.cfg;return r.create({ciphertext:f,key:c,iv:g.iv,algorithm:a,mode:g.mode,padding:g.padding,blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=a.createDecryptor(c,d).finalize(b.ciphertext);return e},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),v=c.kdf={},w=v.OpenSSL={execute:function(a,b,c,d){d||(d=f.random(8));var e=k.create({keySize:b+c}).compute(a,d),g=f.create(e.words.slice(b),4*c);return e.sigBytes=4*b,r.create({key:e,iv:g,salt:d})}},x=d.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:w}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=e.iv;var f=u.encrypt.call(this,a,b,e.key,d);return f.mixIn(e),f},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=e.iv;var f=u.decrypt.call(this,a,b,e.key,d);return f}})}()})},{"./core":46}],46:[function(a,b,c){!function(a,d){"object"==typeof c?b.exports=c=d():"function"==typeof define&&define.amd?define([],d):a.CryptoJS=d()}(this,function(){var a=a||function(a,b){var c={},d=c.lib={},e=d.Base=function(){function a(){}return{extend:function(b){a.prototype=this;var c=new a;return b&&c.mixIn(b),c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)}),c.init.prototype=c,c.$super=this,c},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),f=d.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var b=this.words,c=a.words,d=this.sigBytes,e=a.sigBytes;if(this.clamp(),d%4)for(var f=0;e>f;f++){var g=c[f>>>2]>>>24-f%4*8&255;b[d+f>>>2]|=g<<24-(d+f)%4*8}else for(var f=0;e>f;f+=4)b[d+f>>>2]=c[f>>>2];return this.sigBytes+=e,this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>2]&=4294967295<<32-c%4*8,b.length=a.ceil(c/4)},clone:function(){var a=e.clone.call(this);return a.words=this.words.slice(0),a},random:function(b){for(var c,d=[],e=function(b){var b=b,c=987654321,d=4294967295;return function(){c=36969*(65535&c)+(c>>16)&d,b=18e3*(65535&b)+(b>>16)&d;var e=(c<<16)+b&d;return e/=4294967296,e+=.5,e*(a.random()>.5?1:-1)}},g=0;b>g;g+=4){var h=e(4294967296*(c||a.random()));c=987654071*h(),d.push(4294967296*h()|0)}return new f.init(d,b)}}),g=c.enc={},h=g.Hex={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push((f>>>4).toString(16)),d.push((15&f).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new f.init(c,b/2)}},i=g.Latin1={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>2]|=(255&a.charCodeAt(d))<<24-d%4*8;return new f.init(c,b)}},j=g.Utf8={stringify:function(a){try{return decodeURIComponent(escape(i.stringify(a)))}catch(b){throw new Error("Malformed UTF-8 data")}},parse:function(a){return i.parse(unescape(encodeURIComponent(a)))}},k=d.BufferedBlockAlgorithm=e.extend({reset:function(){this._data=new f.init,this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,g=this.blockSize,h=4*g,i=e/h;i=b?a.ceil(i):a.max((0|i)-this._minBufferSize,0);var j=i*g,k=a.min(4*j,e);if(j){for(var l=0;j>l;l+=g)this._doProcessBlock(d,l);var m=d.splice(0,j);c.sigBytes-=k}return new f.init(m,k)},clone:function(){var a=e.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0}),l=(d.Hasher=k.extend({cfg:e.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){k.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},blockSize:16,_createHelper:function(a){return function(b,c){return new a.init(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return new l.HMAC.init(a,c).finalize(b)}}}),c.algo={});return c}(Math);return a})},{}],47:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.enc;e.Base64={stringify:function(a){var b=a.words,c=a.sigBytes,d=this._map;a.clamp();for(var e=[],f=0;c>f;f+=3)for(var g=b[f>>>2]>>>24-f%4*8&255,h=b[f+1>>>2]>>>24-(f+1)%4*8&255,i=b[f+2>>>2]>>>24-(f+2)%4*8&255,j=g<<16|h<<8|i,k=0;4>k&&c>f+.75*k;k++)e.push(d.charAt(j>>>6*(3-k)&63));var l=d.charAt(64);if(l)for(;e.length%4;)e.push(l);return e.join("")},parse:function(a){var b=a.length,c=this._map,e=c.charAt(64);if(e){var f=a.indexOf(e);-1!=f&&(b=f)}for(var g=[],h=0,i=0;b>i;i++)if(i%4){var j=c.indexOf(a.charAt(i-1))<<i%4*2,k=c.indexOf(a.charAt(i))>>>6-i%4*2,l=j|k;g[h>>>2]|=l<<24-h%4*8,h++}return d.create(g,h)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64})},{"./core":46}],48:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a){return a<<8&4278255360|a>>>8&16711935}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Utf16=f.Utf16BE={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e+=2){var f=b[e>>>2]>>>16-e%4*8&65535;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>1]|=a.charCodeAt(d)<<16-d%2*16;return e.create(c,2*b)}};f.Utf16LE={stringify:function(a){for(var c=a.words,d=a.sigBytes,e=[],f=0;d>f;f+=2){var g=b(c[f>>>2]>>>16-f%4*8&65535);e.push(String.fromCharCode(g))}return e.join("")},parse:function(a){for(var c=a.length,d=[],f=0;c>f;f++)d[f>>>1]|=b(a.charCodeAt(f)<<16-f%2*16);return e.create(d,2*c)}}}(),a.enc.Utf16})},{"./core":46}],49:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.MD5,h=f.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=c.hasher.create(),f=e.create(),g=f.words,h=c.keySize,i=c.iterations;g.length<h;){j&&d.update(j);var j=d.update(a).finalize(b);d.reset();for(var k=1;i>k;k++)j=d.finalize(j),d.reset();f.concat(j)}return f.sigBytes=4*h,f}});b.EvpKDF=function(a,b,c){return h.create(c).compute(a,b)}}(),a.EvpKDF})},{"./core":46,"./hmac":51,"./sha1":70}],50:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.CipherParams,f=c.enc,g=f.Hex,h=c.format;h.Hex={stringify:function(a){return a.ciphertext.toString(g)},parse:function(a){var b=g.parse(a);return e.create({ciphertext:b})}}}(),a.format.Hex})},{"./cipher-core":45,"./core":46}],51:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){!function(){var b=a,c=b.lib,d=c.Base,e=b.enc,f=e.Utf8,g=b.algo;g.HMAC=d.extend({init:function(a,b){a=this._hasher=new a.init,"string"==typeof b&&(b=f.parse(b));var c=a.blockSize,d=4*c;b.sigBytes>d&&(b=a.finalize(b)),b.clamp();for(var e=this._oKey=b.clone(),g=this._iKey=b.clone(),h=e.words,i=g.words,j=0;c>j;j++)h[j]^=1549556828,i[j]^=909522486;e.sigBytes=g.sigBytes=d,this.reset()},reset:function(){var a=this._hasher;a.reset(),a.update(this._iKey)},update:function(a){return this._hasher.update(a),this},finalize:function(a){var b=this._hasher,c=b.finalize(a);b.reset();var d=b.finalize(this._oKey.clone().concat(c));return d}})}()})},{"./core":46}],52:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./lib-typedarrays"),a("./enc-utf16"),a("./enc-base64"),a("./md5"),a("./sha1"),a("./sha256"),a("./sha224"),a("./sha512"),a("./sha384"),a("./sha3"),a("./ripemd160"),a("./hmac"),a("./pbkdf2"),a("./evpkdf"),a("./cipher-core"),a("./mode-cfb"),a("./mode-ctr"),a("./mode-ctr-gladman"),a("./mode-ofb"),a("./mode-ecb"),a("./pad-ansix923"),a("./pad-iso10126"),a("./pad-iso97971"),a("./pad-zeropadding"),a("./pad-nopadding"),a("./format-hex"),a("./aes"),a("./tripledes"),a("./rc4"),a("./rabbit"),a("./rabbit-legacy")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy"],e):d.CryptoJS=e(d.CryptoJS)}(this,function(a){return a})},{"./aes":44,"./cipher-core":45,"./core":46,"./enc-base64":47,"./enc-utf16":48,"./evpkdf":49,"./format-hex":50,"./hmac":51,"./lib-typedarrays":53,"./md5":54,"./mode-cfb":55,"./mode-ctr":57,"./mode-ctr-gladman":56,"./mode-ecb":58,"./mode-ofb":59,"./pad-ansix923":60,"./pad-iso10126":61,"./pad-iso97971":62,"./pad-nopadding":63,"./pad-zeropadding":64,"./pbkdf2":65,"./rabbit":67,"./rabbit-legacy":66,"./rc4":68,"./ripemd160":69,"./sha1":70,"./sha224":71,"./sha256":72,"./sha3":73,"./sha384":74,"./sha512":75,"./tripledes":76,"./x64-core":77}],53:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){if("function"==typeof ArrayBuffer){var b=a,c=b.lib,d=c.WordArray,e=d.init,f=d.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var b=a.byteLength,c=[],d=0;b>d;d++)c[d>>>2]|=a[d]<<24-d%4*8;e.call(this,c,b)}else e.apply(this,arguments)};f.prototype=d}}(),a.lib.WordArray})},{"./core":46}],54:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c,d,e,f,g){var h=a+(b&c|~b&d)+e+g;return(h<<f|h>>>32-f)+b}function d(a,b,c,d,e,f,g){var h=a+(b&d|c&~d)+e+g;return(h<<f|h>>>32-f)+b}function e(a,b,c,d,e,f,g){var h=a+(b^c^d)+e+g;return(h<<f|h>>>32-f)+b}function f(a,b,c,d,e,f,g){var h=a+(c^(b|~d))+e+g;return(h<<f|h>>>32-f)+b}var g=a,h=g.lib,i=h.WordArray,j=h.Hasher,k=g.algo,l=[];!function(){for(var a=0;64>a;a++)l[a]=4294967296*b.abs(b.sin(a+1))|0}();var m=k.MD5=j.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(a,b){for(var g=0;16>g;g++){var h=b+g,i=a[h];a[h]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var j=this._hash.words,k=a[b+0],m=a[b+1],n=a[b+2],o=a[b+3],p=a[b+4],q=a[b+5],r=a[b+6],s=a[b+7],t=a[b+8],u=a[b+9],v=a[b+10],w=a[b+11],x=a[b+12],y=a[b+13],z=a[b+14],A=a[b+15],B=j[0],C=j[1],D=j[2],E=j[3];B=c(B,C,D,E,k,7,l[0]),E=c(E,B,C,D,m,12,l[1]),D=c(D,E,B,C,n,17,l[2]),C=c(C,D,E,B,o,22,l[3]),B=c(B,C,D,E,p,7,l[4]),E=c(E,B,C,D,q,12,l[5]),D=c(D,E,B,C,r,17,l[6]),C=c(C,D,E,B,s,22,l[7]),B=c(B,C,D,E,t,7,l[8]),E=c(E,B,C,D,u,12,l[9]),D=c(D,E,B,C,v,17,l[10]),C=c(C,D,E,B,w,22,l[11]),B=c(B,C,D,E,x,7,l[12]),E=c(E,B,C,D,y,12,l[13]),D=c(D,E,B,C,z,17,l[14]),C=c(C,D,E,B,A,22,l[15]),B=d(B,C,D,E,m,5,l[16]),E=d(E,B,C,D,r,9,l[17]),D=d(D,E,B,C,w,14,l[18]),C=d(C,D,E,B,k,20,l[19]),B=d(B,C,D,E,q,5,l[20]),E=d(E,B,C,D,v,9,l[21]),D=d(D,E,B,C,A,14,l[22]),C=d(C,D,E,B,p,20,l[23]),B=d(B,C,D,E,u,5,l[24]),E=d(E,B,C,D,z,9,l[25]),D=d(D,E,B,C,o,14,l[26]),C=d(C,D,E,B,t,20,l[27]),B=d(B,C,D,E,y,5,l[28]),E=d(E,B,C,D,n,9,l[29]),D=d(D,E,B,C,s,14,l[30]),C=d(C,D,E,B,x,20,l[31]),B=e(B,C,D,E,q,4,l[32]),E=e(E,B,C,D,t,11,l[33]),D=e(D,E,B,C,w,16,l[34]),C=e(C,D,E,B,z,23,l[35]),B=e(B,C,D,E,m,4,l[36]),E=e(E,B,C,D,p,11,l[37]),D=e(D,E,B,C,s,16,l[38]),C=e(C,D,E,B,v,23,l[39]),B=e(B,C,D,E,y,4,l[40]),E=e(E,B,C,D,k,11,l[41]),D=e(D,E,B,C,o,16,l[42]),C=e(C,D,E,B,r,23,l[43]),B=e(B,C,D,E,u,4,l[44]),E=e(E,B,C,D,x,11,l[45]),D=e(D,E,B,C,A,16,l[46]),C=e(C,D,E,B,n,23,l[47]),B=f(B,C,D,E,k,6,l[48]),E=f(E,B,C,D,s,10,l[49]),D=f(D,E,B,C,z,15,l[50]),C=f(C,D,E,B,q,21,l[51]),B=f(B,C,D,E,x,6,l[52]),E=f(E,B,C,D,o,10,l[53]),D=f(D,E,B,C,v,15,l[54]),C=f(C,D,E,B,m,21,l[55]),B=f(B,C,D,E,t,6,l[56]),E=f(E,B,C,D,A,10,l[57]),D=f(D,E,B,C,r,15,l[58]),C=f(C,D,E,B,y,21,l[59]),B=f(B,C,D,E,p,6,l[60]),E=f(E,B,C,D,w,10,l[61]),D=f(D,E,B,C,n,15,l[62]),C=f(C,D,E,B,u,21,l[63]),j[0]=j[0]+B|0,j[1]=j[1]+C|0,j[2]=j[2]+D|0,j[3]=j[3]+E|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;c[e>>>5]|=128<<24-e%32;var f=b.floor(d/4294967296),g=d;c[(e+64>>>9<<4)+15]=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),c[(e+64>>>9<<4)+14]=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8),a.sigBytes=4*(c.length+1),this._process();for(var h=this._hash,i=h.words,j=0;4>j;j++){var k=i[j];i[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}return h},clone:function(){var a=j.clone.call(this);return a._hash=this._hash.clone(),a}});g.MD5=j._createHelper(m),g.HmacMD5=j._createHmacHelper(m)}(Math),a.MD5})},{"./core":46}],55:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CFB=function(){function b(a,b,c,d){var e=this._iv;if(e){var f=e.slice(0);this._iv=void 0}else var f=this._prevBlock;d.encryptBlock(f,0);for(var g=0;c>g;g++)a[b+g]^=f[g]}var c=a.lib.BlockCipherMode.extend();return c.Encryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize;b.call(this,a,c,e,d),this._prevBlock=a.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize,f=a.slice(c,c+e);b.call(this,a,c,e,d),this._prevBlock=f}}),c}(),a.mode.CFB})},{"./cipher-core":45,"./core":46}],56:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTRGladman=function(){function b(a){if(255===(a>>24&255)){var b=a>>16&255,c=a>>8&255,d=255&a;255===b?(b=0,255===c?(c=0,255===d?d=0:++d):++c):++b,a=0,a+=b<<16,a+=c<<8,a+=d}else a+=1<<24;return a}function c(a){return 0===(a[0]=b(a[0]))&&(a[1]=b(a[1])),a}var d=a.lib.BlockCipherMode.extend(),e=d.Encryptor=d.extend({processBlock:function(a,b){var d=this._cipher,e=d.blockSize,f=this._iv,g=this._counter;f&&(g=this._counter=f.slice(0),this._iv=void 0),c(g);var h=g.slice(0);d.encryptBlock(h,0);for(var i=0;e>i;i++)a[b+i]^=h[i]}});return d.Decryptor=e,d}(),a.mode.CTRGladman})},{"./cipher-core":45,"./core":46}],57:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTR=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._counter;e&&(f=this._counter=e.slice(0),this._iv=void 0);var g=f.slice(0);c.encryptBlock(g,0),f[d-1]=f[d-1]+1|0;for(var h=0;d>h;h++)a[b+h]^=g[h]}});return b.Decryptor=c,b}(),a.mode.CTR})},{"./cipher-core":45,"./core":46}],58:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.ECB=function(){var b=a.lib.BlockCipherMode.extend();return b.Encryptor=b.extend({processBlock:function(a,b){this._cipher.encryptBlock(a,b)}}),b.Decryptor=b.extend({processBlock:function(a,b){this._cipher.decryptBlock(a,b)}}),b}(),a.mode.ECB})},{"./cipher-core":45,"./core":46}],59:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.OFB=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._keystream;e&&(f=this._keystream=e.slice(0),this._iv=void 0),c.encryptBlock(f,0);for(var g=0;d>g;g++)a[b+g]^=f[g]}});return b.Decryptor=c,b}(),a.mode.OFB})},{"./cipher-core":45,"./core":46}],60:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.AnsiX923={pad:function(a,b){var c=a.sigBytes,d=4*b,e=d-c%d,f=c+e-1;a.clamp(),a.words[f>>>2]|=e<<24-f%4*8,a.sigBytes+=e},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Ansix923})},{"./cipher-core":45,"./core":46}],61:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso10126={pad:function(b,c){var d=4*c,e=d-b.sigBytes%d;b.concat(a.lib.WordArray.random(e-1)).concat(a.lib.WordArray.create([e<<24],1))},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Iso10126})},{"./cipher-core":45,"./core":46}],62:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS); }(this,function(a){return a.pad.Iso97971={pad:function(b,c){b.concat(a.lib.WordArray.create([2147483648],1)),a.pad.ZeroPadding.pad(b,c)},unpad:function(b){a.pad.ZeroPadding.unpad(b),b.sigBytes--}},a.pad.Iso97971})},{"./cipher-core":45,"./core":46}],63:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.NoPadding={pad:function(){},unpad:function(){}},a.pad.NoPadding})},{"./cipher-core":45,"./core":46}],64:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.ZeroPadding={pad:function(a,b){var c=4*b;a.clamp(),a.sigBytes+=c-(a.sigBytes%c||c)},unpad:function(a){for(var b=a.words,c=a.sigBytes-1;!(b[c>>>2]>>>24-c%4*8&255);)c--;a.sigBytes=c+1}},a.pad.ZeroPadding})},{"./cipher-core":45,"./core":46}],65:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.SHA1,h=f.HMAC,i=f.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=h.create(c.hasher,a),f=e.create(),g=e.create([1]),i=f.words,j=g.words,k=c.keySize,l=c.iterations;i.length<k;){var m=d.update(b).finalize(g);d.reset();for(var n=m.words,o=n.length,p=m,q=1;l>q;q++){p=d.finalize(p),d.reset();for(var r=p.words,s=0;o>s;s++)n[s]^=r[s]}f.concat(m),j[0]++}return f.sigBytes=4*k,f}});b.PBKDF2=function(a,b,c){return i.create(c).compute(a,b)}}(),a.PBKDF2})},{"./core":46,"./hmac":51,"./sha1":70}],66:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.RabbitLegacy=e.extend({_doReset:function(){var a=this._key.words,c=this.cfg.iv,d=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],e=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var f=0;4>f;f++)b.call(this);for(var f=0;8>f;f++)e[f]^=d[f+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;e[0]^=j,e[1]^=l,e[2]^=k,e[3]^=m,e[4]^=j,e[5]^=l,e[6]^=k,e[7]^=m;for(var f=0;4>f;f++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.RabbitLegacy=e._createHelper(j)}(),a.RabbitLegacy})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],67:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.Rabbit=e.extend({_doReset:function(){for(var a=this._key.words,c=this.cfg.iv,d=0;4>d;d++)a[d]=16711935&(a[d]<<8|a[d]>>>24)|4278255360&(a[d]<<24|a[d]>>>8);var e=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],f=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var d=0;4>d;d++)b.call(this);for(var d=0;8>d;d++)f[d]^=e[d+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;f[0]^=j,f[1]^=l,f[2]^=k,f[3]^=m,f[4]^=j,f[5]^=l,f[6]^=k,f[7]^=m;for(var d=0;4>d;d++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.Rabbit=e._createHelper(j)}(),a.Rabbit})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],68:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._S,b=this._i,c=this._j,d=0,e=0;4>e;e++){b=(b+1)%256,c=(c+a[b])%256;var f=a[b];a[b]=a[c],a[c]=f,d|=a[(a[b]+a[c])%256]<<24-8*e}return this._i=b,this._j=c,d}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=f.RC4=e.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes,d=this._S=[],e=0;256>e;e++)d[e]=e;for(var e=0,f=0;256>e;e++){var g=e%c,h=b[g>>>2]>>>24-g%4*8&255;f=(f+d[e]+h)%256;var i=d[e];d[e]=d[f],d[f]=i}this._i=this._j=0},_doProcessBlock:function(a,c){a[c]^=b.call(this)},keySize:8,ivSize:0});c.RC4=e._createHelper(g);var h=f.RC4Drop=g.extend({cfg:g.cfg.extend({drop:192}),_doReset:function(){g._doReset.call(this);for(var a=this.cfg.drop;a>0;a--)b.call(this)}});c.RC4Drop=e._createHelper(h)}(),a.RC4})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],69:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c){return a^b^c}function d(a,b,c){return a&b|~a&c}function e(a,b,c){return(a|~b)^c}function f(a,b,c){return a&c|b&~c}function g(a,b,c){return a^(b|~c)}function h(a,b){return a<<b|a>>>32-b}var i=a,j=i.lib,k=j.WordArray,l=j.Hasher,m=i.algo,n=k.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=k.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),p=k.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),q=k.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),r=k.create([0,1518500249,1859775393,2400959708,2840853838]),s=k.create([1352829926,1548603684,1836072691,2053994217,0]),t=m.RIPEMD160=l.extend({_doReset:function(){this._hash=k.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var i=0;16>i;i++){var j=b+i,k=a[j];a[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}var l,m,t,u,v,w,x,y,z,A,B=this._hash.words,C=r.words,D=s.words,E=n.words,F=o.words,G=p.words,H=q.words;w=l=B[0],x=m=B[1],y=t=B[2],z=u=B[3],A=v=B[4];for(var I,i=0;80>i;i+=1)I=l+a[b+E[i]]|0,I+=16>i?c(m,t,u)+C[0]:32>i?d(m,t,u)+C[1]:48>i?e(m,t,u)+C[2]:64>i?f(m,t,u)+C[3]:g(m,t,u)+C[4],I=0|I,I=h(I,G[i]),I=I+v|0,l=v,v=u,u=h(t,10),t=m,m=I,I=w+a[b+F[i]]|0,I+=16>i?g(x,y,z)+D[0]:32>i?f(x,y,z)+D[1]:48>i?e(x,y,z)+D[2]:64>i?d(x,y,z)+D[3]:c(x,y,z)+D[4],I=0|I,I=h(I,H[i]),I=I+A|0,w=A,A=z,z=h(y,10),y=x,x=I;I=B[1]+t+z|0,B[1]=B[2]+u+A|0,B[2]=B[3]+v+w|0,B[3]=B[4]+l+x|0,B[4]=B[0]+m+y|0,B[0]=I},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=16711935&(c<<8|c>>>24)|4278255360&(c<<24|c>>>8),a.sigBytes=4*(b.length+1),this._process();for(var e=this._hash,f=e.words,g=0;5>g;g++){var h=f[g];f[g]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return e},clone:function(){var a=l.clone.call(this);return a._hash=this._hash.clone(),a}});i.RIPEMD160=l._createHelper(t),i.HmacRIPEMD160=l._createHmacHelper(t)}(Math),a.RIPEMD160})},{"./core":46}],70:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=c.Hasher,f=b.algo,g=[],h=f.SHA1=e.extend({_doReset:function(){this._hash=new d.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],h=c[3],i=c[4],j=0;80>j;j++){if(16>j)g[j]=0|a[b+j];else{var k=g[j-3]^g[j-8]^g[j-14]^g[j-16];g[j]=k<<1|k>>>31}var l=(d<<5|d>>>27)+i+g[j];l+=20>j?(e&f|~e&h)+1518500249:40>j?(e^f^h)+1859775393:60>j?(e&f|e&h|f&h)-1894007588:(e^f^h)-899497514,i=h,h=f,f=e<<30|e>>>2,e=d,d=l}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+h|0,c[4]=c[4]+i|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;return b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=Math.floor(c/4294967296),b[(d+64>>>9<<4)+15]=c,a.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a}});b.SHA1=e._createHelper(h),b.HmacSHA1=e._createHmacHelper(h)}(),a.SHA1})},{"./core":46}],71:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha256")):"function"==typeof define&&define.amd?define(["./core","./sha256"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.algo,f=e.SHA256,g=e.SHA224=f.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=f._doFinalize.call(this);return a.sigBytes-=4,a}});b.SHA224=f._createHelper(g),b.HmacSHA224=f._createHmacHelper(g)}(),a.SHA224})},{"./core":46,"./sha256":72}],72:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.algo,h=[],i=[];!function(){function a(a){for(var c=b.sqrt(a),d=2;c>=d;d++)if(!(a%d))return!1;return!0}function c(a){return 4294967296*(a-(0|a))|0}for(var d=2,e=0;64>e;)a(d)&&(8>e&&(h[e]=c(b.pow(d,.5))),i[e]=c(b.pow(d,1/3)),e++),d++}();var j=[],k=g.SHA256=f.extend({_doReset:function(){this._hash=new e.init(h.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],m=c[7],n=0;64>n;n++){if(16>n)j[n]=0|a[b+n];else{var o=j[n-15],p=(o<<25|o>>>7)^(o<<14|o>>>18)^o>>>3,q=j[n-2],r=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;j[n]=p+j[n-7]+r+j[n-16]}var s=h&k^~h&l,t=d&e^d&f^e&f,u=(d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22),v=(h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25),w=m+v+s+i[n]+j[n],x=u+t;m=l,l=k,k=h,h=g+w|0,g=f,f=e,e=d,d=w+x|0}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+g|0,c[4]=c[4]+h|0,c[5]=c[5]+k|0,c[6]=c[6]+l|0,c[7]=c[7]+m|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;return c[e>>>5]|=128<<24-e%32,c[(e+64>>>9<<4)+14]=b.floor(d/4294967296),c[(e+64>>>9<<4)+15]=d,a.sigBytes=4*c.length,this._process(),this._hash},clone:function(){var a=f.clone.call(this);return a._hash=this._hash.clone(),a}});c.SHA256=f._createHelper(k),c.HmacSHA256=f._createHmacHelper(k)}(Math),a.SHA256})},{"./core":46}],73:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.x64,h=g.Word,i=c.algo,j=[],k=[],l=[];!function(){for(var a=1,b=0,c=0;24>c;c++){j[a+5*b]=(c+1)*(c+2)/2%64;var d=b%5,e=(2*a+3*b)%5;a=d,b=e}for(var a=0;5>a;a++)for(var b=0;5>b;b++)k[a+5*b]=b+(2*a+3*b)%5*5;for(var f=1,g=0;24>g;g++){for(var i=0,m=0,n=0;7>n;n++){if(1&f){var o=(1<<n)-1;32>o?m^=1<<o:i^=1<<o-32}128&f?f=f<<1^113:f<<=1}l[g]=h.create(i,m)}}();var m=[];!function(){for(var a=0;25>a;a++)m[a]=h.create()}();var n=i.SHA3=f.extend({cfg:f.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=[],b=0;25>b;b++)a[b]=new h.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var c=this._state,d=this.blockSize/2,e=0;d>e;e++){var f=a[b+2*e],g=a[b+2*e+1];f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),g=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8);var h=c[e];h.high^=g,h.low^=f}for(var i=0;24>i;i++){for(var n=0;5>n;n++){for(var o=0,p=0,q=0;5>q;q++){var h=c[n+5*q];o^=h.high,p^=h.low}var r=m[n];r.high=o,r.low=p}for(var n=0;5>n;n++)for(var s=m[(n+4)%5],t=m[(n+1)%5],u=t.high,v=t.low,o=s.high^(u<<1|v>>>31),p=s.low^(v<<1|u>>>31),q=0;5>q;q++){var h=c[n+5*q];h.high^=o,h.low^=p}for(var w=1;25>w;w++){var h=c[w],x=h.high,y=h.low,z=j[w];if(32>z)var o=x<<z|y>>>32-z,p=y<<z|x>>>32-z;else var o=y<<z-32|x>>>64-z,p=x<<z-32|y>>>64-z;var A=m[k[w]];A.high=o,A.low=p}var B=m[0],C=c[0];B.high=C.high,B.low=C.low;for(var n=0;5>n;n++)for(var q=0;5>q;q++){var w=n+5*q,h=c[w],D=m[w],E=m[(n+1)%5+5*q],F=m[(n+2)%5+5*q];h.high=D.high^~E.high&F.high,h.low=D.low^~E.low&F.low}var h=c[0],G=l[i];h.high^=G.high,h.low^=G.low}},_doFinalize:function(){var a=this._data,c=a.words,d=(8*this._nDataBytes,8*a.sigBytes),f=32*this.blockSize;c[d>>>5]|=1<<24-d%32,c[(b.ceil((d+1)/f)*f>>>5)-1]|=128,a.sigBytes=4*c.length,this._process();for(var g=this._state,h=this.cfg.outputLength/8,i=h/8,j=[],k=0;i>k;k++){var l=g[k],m=l.high,n=l.low;m=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),n=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),j.push(n),j.push(m)}return new e.init(j,h)},clone:function(){for(var a=f.clone.call(this),b=a._state=this._state.slice(0),c=0;25>c;c++)b[c]=b[c].clone();return a}});c.SHA3=f._createHelper(n),c.HmacSHA3=f._createHmacHelper(n)}(Math),a.SHA3})},{"./core":46,"./x64-core":77}],74:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./sha512")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./sha512"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.x64,d=c.Word,e=c.WordArray,f=b.algo,g=f.SHA512,h=f.SHA384=g.extend({_doReset:function(){this._hash=new e.init([new d.init(3418070365,3238371032),new d.init(1654270250,914150663),new d.init(2438529370,812702999),new d.init(355462360,4144912697),new d.init(1731405415,4290775857),new d.init(2394180231,1750603025),new d.init(3675008525,1694076839),new d.init(1203062813,3204075428)])},_doFinalize:function(){var a=g._doFinalize.call(this);return a.sigBytes-=16,a}});b.SHA384=g._createHelper(h),b.HmacSHA384=g._createHmacHelper(h)}(),a.SHA384})},{"./core":46,"./sha512":75,"./x64-core":77}],75:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){return g.create.apply(g,arguments)}var c=a,d=c.lib,e=d.Hasher,f=c.x64,g=f.Word,h=f.WordArray,i=c.algo,j=[b(1116352408,3609767458),b(1899447441,602891725),b(3049323471,3964484399),b(3921009573,2173295548),b(961987163,4081628472),b(1508970993,3053834265),b(2453635748,2937671579),b(2870763221,3664609560),b(3624381080,2734883394),b(310598401,1164996542),b(607225278,1323610764),b(1426881987,3590304994),b(1925078388,4068182383),b(2162078206,991336113),b(2614888103,633803317),b(3248222580,3479774868),b(3835390401,2666613458),b(4022224774,944711139),b(264347078,2341262773),b(604807628,2007800933),b(770255983,1495990901),b(1249150122,1856431235),b(1555081692,3175218132),b(1996064986,2198950837),b(2554220882,3999719339),b(2821834349,766784016),b(2952996808,2566594879),b(3210313671,3203337956),b(3336571891,1034457026),b(3584528711,2466948901),b(113926993,3758326383),b(338241895,168717936),b(666307205,1188179964),b(773529912,1546045734),b(1294757372,1522805485),b(1396182291,2643833823),b(1695183700,2343527390),b(1986661051,1014477480),b(2177026350,1206759142),b(2456956037,344077627),b(2730485921,1290863460),b(2820302411,3158454273),b(3259730800,3505952657),b(3345764771,106217008),b(3516065817,3606008344),b(3600352804,1432725776),b(4094571909,1467031594),b(275423344,851169720),b(430227734,3100823752),b(506948616,1363258195),b(659060556,3750685593),b(883997877,3785050280),b(958139571,3318307427),b(1322822218,3812723403),b(1537002063,2003034995),b(1747873779,3602036899),b(1955562222,1575990012),b(2024104815,1125592928),b(2227730452,2716904306),b(2361852424,442776044),b(2428436474,593698344),b(2756734187,3733110249),b(3204031479,2999351573),b(3329325298,3815920427),b(3391569614,3928383900),b(3515267271,566280711),b(3940187606,3454069534),b(4118630271,4000239992),b(116418474,1914138554),b(174292421,2731055270),b(289380356,3203993006),b(460393269,320620315),b(685471733,587496836),b(852142971,1086792851),b(1017036298,365543100),b(1126000580,2618297676),b(1288033470,3409855158),b(1501505948,4234509866),b(1607167915,987167468),b(1816402316,1246189591)],k=[];!function(){for(var a=0;80>a;a++)k[a]=b()}();var l=i.SHA512=e.extend({_doReset:function(){this._hash=new h.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],l=c[6],m=c[7],n=d.high,o=d.low,p=e.high,q=e.low,r=f.high,s=f.low,t=g.high,u=g.low,v=h.high,w=h.low,x=i.high,y=i.low,z=l.high,A=l.low,B=m.high,C=m.low,D=n,E=o,F=p,G=q,H=r,I=s,J=t,K=u,L=v,M=w,N=x,O=y,P=z,Q=A,R=B,S=C,T=0;80>T;T++){var U=k[T];if(16>T)var V=U.high=0|a[b+2*T],W=U.low=0|a[b+2*T+1];else{var X=k[T-15],Y=X.high,Z=X.low,$=(Y>>>1|Z<<31)^(Y>>>8|Z<<24)^Y>>>7,_=(Z>>>1|Y<<31)^(Z>>>8|Y<<24)^(Z>>>7|Y<<25),aa=k[T-2],ba=aa.high,ca=aa.low,da=(ba>>>19|ca<<13)^(ba<<3|ca>>>29)^ba>>>6,ea=(ca>>>19|ba<<13)^(ca<<3|ba>>>29)^(ca>>>6|ba<<26),fa=k[T-7],ga=fa.high,ha=fa.low,ia=k[T-16],ja=ia.high,ka=ia.low,W=_+ha,V=$+ga+(_>>>0>W>>>0?1:0),W=W+ea,V=V+da+(ea>>>0>W>>>0?1:0),W=W+ka,V=V+ja+(ka>>>0>W>>>0?1:0);U.high=V,U.low=W}var la=L&N^~L&P,ma=M&O^~M&Q,na=D&F^D&H^F&H,oa=E&G^E&I^G&I,pa=(D>>>28|E<<4)^(D<<30|E>>>2)^(D<<25|E>>>7),qa=(E>>>28|D<<4)^(E<<30|D>>>2)^(E<<25|D>>>7),ra=(L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9),sa=(M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9),ta=j[T],ua=ta.high,va=ta.low,wa=S+sa,xa=R+ra+(S>>>0>wa>>>0?1:0),wa=wa+ma,xa=xa+la+(ma>>>0>wa>>>0?1:0),wa=wa+va,xa=xa+ua+(va>>>0>wa>>>0?1:0),wa=wa+W,xa=xa+V+(W>>>0>wa>>>0?1:0),ya=qa+oa,za=pa+na+(qa>>>0>ya>>>0?1:0);R=P,S=Q,P=N,Q=O,N=L,O=M,M=K+wa|0,L=J+xa+(K>>>0>M>>>0?1:0)|0,J=H,K=I,H=F,I=G,F=D,G=E,E=wa+ya|0,D=xa+za+(wa>>>0>E>>>0?1:0)|0}o=d.low=o+E,d.high=n+D+(E>>>0>o>>>0?1:0),q=e.low=q+G,e.high=p+F+(G>>>0>q>>>0?1:0),s=f.low=s+I,f.high=r+H+(I>>>0>s>>>0?1:0),u=g.low=u+K,g.high=t+J+(K>>>0>u>>>0?1:0),w=h.low=w+M,h.high=v+L+(M>>>0>w>>>0?1:0),y=i.low=y+O,i.high=x+N+(O>>>0>y>>>0?1:0),A=l.low=A+Q,l.high=z+P+(Q>>>0>A>>>0?1:0),C=m.low=C+S,m.high=B+R+(S>>>0>C>>>0?1:0)},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+128>>>10<<5)+30]=Math.floor(c/4294967296),b[(d+128>>>10<<5)+31]=c,a.sigBytes=4*b.length,this._process();var e=this._hash.toX32();return e},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a},blockSize:32});c.SHA512=e._createHelper(l),c.HmacSHA512=e._createHmacHelper(l)}(),a.SHA512})},{"./core":46,"./x64-core":77}],76:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b){var c=(this._lBlock>>>a^this._rBlock)&b;this._rBlock^=c,this._lBlock^=c<<a}function c(a,b){var c=(this._rBlock>>>a^this._lBlock)&b;this._lBlock^=c,this._rBlock^=c<<a}var d=a,e=d.lib,f=e.WordArray,g=e.BlockCipher,h=d.algo,i=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],j=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],k=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],l=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],m=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],n=h.DES=g.extend({_doReset:function(){for(var a=this._key,b=a.words,c=[],d=0;56>d;d++){var e=i[d]-1;c[d]=b[e>>>5]>>>31-e%32&1}for(var f=this._subKeys=[],g=0;16>g;g++){for(var h=f[g]=[],l=k[g],d=0;24>d;d++)h[d/6|0]|=c[(j[d]-1+l)%28]<<31-d%6,h[4+(d/6|0)]|=c[28+(j[d+24]-1+l)%28]<<31-d%6;h[0]=h[0]<<1|h[0]>>>31;for(var d=1;7>d;d++)h[d]=h[d]>>>4*(d-1)+3;h[7]=h[7]<<5|h[7]>>>27}for(var m=this._invSubKeys=[],d=0;16>d;d++)m[d]=f[15-d]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._subKeys)},decryptBlock:function(a,b){this._doCryptBlock(a,b,this._invSubKeys)},_doCryptBlock:function(a,d,e){this._lBlock=a[d],this._rBlock=a[d+1],b.call(this,4,252645135),b.call(this,16,65535),c.call(this,2,858993459),c.call(this,8,16711935),b.call(this,1,1431655765);for(var f=0;16>f;f++){for(var g=e[f],h=this._lBlock,i=this._rBlock,j=0,k=0;8>k;k++)j|=l[k][((i^g[k])&m[k])>>>0];this._lBlock=i,this._rBlock=h^j}var n=this._lBlock;this._lBlock=this._rBlock,this._rBlock=n,b.call(this,1,1431655765),c.call(this,8,16711935),c.call(this,2,858993459),b.call(this,16,65535),b.call(this,4,252645135), a[d]=this._lBlock,a[d+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});d.DES=g._createHelper(n);var o=h.TripleDES=g.extend({_doReset:function(){var a=this._key,b=a.words;this._des1=n.createEncryptor(f.create(b.slice(0,2))),this._des2=n.createEncryptor(f.create(b.slice(2,4))),this._des3=n.createEncryptor(f.create(b.slice(4,6)))},encryptBlock:function(a,b){this._des1.encryptBlock(a,b),this._des2.decryptBlock(a,b),this._des3.encryptBlock(a,b)},decryptBlock:function(a,b){this._des3.decryptBlock(a,b),this._des2.encryptBlock(a,b),this._des1.decryptBlock(a,b)},keySize:6,ivSize:2,blockSize:2});d.TripleDES=g._createHelper(o)}(),a.TripleDES})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],77:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=c.x64={};g.Word=e.extend({init:function(a,b){this.high=a,this.low=b}}),g.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=8*a.length},toX32:function(){for(var a=this.words,b=a.length,c=[],d=0;b>d;d++){var e=a[d];c.push(e.high),c.push(e.low)}return f.create(c,this.sigBytes)},clone:function(){for(var a=e.clone.call(this),b=a.words=this.words.slice(0),c=b.length,d=0;c>d;d++)b[d]=b[d].clone();return a}})}(),a})},{"./core":46}],78:[function(a,b,c){(function(a,d){!function(){var b,c,e,f;!function(){var a={},d={};b=function(b,c,d){a[b]={deps:c,callback:d}},f=e=c=function(b){function e(a){if("."!==a.charAt(0))return a;for(var c=a.split("/"),d=b.split("/").slice(0,-1),e=0,f=c.length;f>e;e++){var g=c[e];if(".."===g)d.pop();else{if("."===g)continue;d.push(g)}}return d.join("/")}if(f._eak_seen=a,d[b])return d[b];if(d[b]={},!a[b])throw new Error("Could not find module "+b);for(var g,h=a[b],i=h.deps,j=h.callback,k=[],l=0,m=i.length;m>l;l++)"exports"===i[l]?k.push(g={}):k.push(c(e(i[l])));var n=j.apply(this,k);return d[b]=g||n}}(),b("promise/all",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to all.");return new b(function(b,c){function d(a){return function(b){f(a,b)}}function f(a,c){h[a]=c,0===--i&&b(h)}var g,h=[],i=a.length;0===i&&b([]);for(var j=0;j<a.length;j++)g=a[j],g&&e(g.then)?g.then(d(j),c):f(j,g)})}var d=a.isArray,e=a.isFunction;b.all=c}),b("promise/asap",["exports"],function(b){"use strict";function c(){return function(){a.nextTick(g)}}function e(){var a=0,b=new k(g),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){c.data=a=++a%2}}function f(){return function(){l.setTimeout(g,1)}}function g(){for(var a=0;a<m.length;a++){var b=m[a],c=b[0],d=b[1];c(d)}m=[]}function h(a,b){var c=m.push([a,b]);1===c&&i()}var i,j="undefined"!=typeof window?window:{},k=j.MutationObserver||j.WebKitMutationObserver,l="undefined"!=typeof d?d:void 0===this?window:this,m=[];i="undefined"!=typeof a&&"[object process]"==={}.toString.call(a)?c():k?e():f(),b.asap=h}),b("promise/config",["exports"],function(a){"use strict";function b(a,b){return 2!==arguments.length?c[a]:void(c[a]=b)}var c={instrument:!1};a.config=c,a.configure=b}),b("promise/polyfill",["./promise","./utils","exports"],function(a,b,c){"use strict";function e(){var a;a="undefined"!=typeof d?d:"undefined"!=typeof window&&window.document?window:self;var b="Promise"in a&&"resolve"in a.Promise&&"reject"in a.Promise&&"all"in a.Promise&&"race"in a.Promise&&function(){var b;return new a.Promise(function(a){b=a}),g(b)}();b||(a.Promise=f)}var f=a.Promise,g=b.isFunction;c.polyfill=e}),b("promise/promise",["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"],function(a,b,c,d,e,f,g,h){"use strict";function i(a){if(!v(a))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof i))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this._subscribers=[],j(a,this)}function j(a,b){function c(a){o(b,a)}function d(a){q(b,a)}try{a(c,d)}catch(e){d(e)}}function k(a,b,c,d){var e,f,g,h,i=v(c);if(i)try{e=c(d),g=!0}catch(j){h=!0,f=j}else e=d,g=!0;n(b,e)||(i&&g?o(b,e):h?q(b,f):a===D?o(b,e):a===E&&q(b,e))}function l(a,b,c,d){var e=a._subscribers,f=e.length;e[f]=b,e[f+D]=c,e[f+E]=d}function m(a,b){for(var c,d,e=a._subscribers,f=a._detail,g=0;g<e.length;g+=3)c=e[g],d=e[g+b],k(b,c,d,f);a._subscribers=null}function n(a,b){var c,d=null;try{if(a===b)throw new TypeError("A promises callback cannot return that same promise.");if(u(b)&&(d=b.then,v(d)))return d.call(b,function(d){return c?!0:(c=!0,void(b!==d?o(a,d):p(a,d)))},function(b){return c?!0:(c=!0,void q(a,b))}),!0}catch(e){return c?!0:(q(a,e),!0)}return!1}function o(a,b){a===b?p(a,b):n(a,b)||p(a,b)}function p(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(r,a))}function q(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(s,a))}function r(a){m(a,a._state=D)}function s(a){m(a,a._state=E)}var t=a.config,u=(a.configure,b.objectOrFunction),v=b.isFunction,w=(b.now,c.all),x=d.race,y=e.resolve,z=f.reject,A=g.asap;t.async=A;var B=void 0,C=0,D=1,E=2;i.prototype={constructor:i,_state:void 0,_detail:void 0,_subscribers:void 0,then:function(a,b){var c=this,d=new this.constructor(function(){});if(this._state){var e=arguments;t.async(function(){k(c._state,d,e[c._state-1],c._detail)})}else l(this,d,a,b);return d},"catch":function(a){return this.then(null,a)}},i.all=w,i.race=x,i.resolve=y,i.reject=z,h.Promise=i}),b("promise/race",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to race.");return new b(function(b,c){for(var d,e=0;e<a.length;e++)d=a[e],d&&"function"==typeof d.then?d.then(b,c):b(d)})}var d=a.isArray;b.race=c}),b("promise/reject",["exports"],function(a){"use strict";function b(a){var b=this;return new b(function(b,c){c(a)})}a.reject=b}),b("promise/resolve",["exports"],function(a){"use strict";function b(a){if(a&&"object"==typeof a&&a.constructor===this)return a;var b=this;return new b(function(b){b(a)})}a.resolve=b}),b("promise/utils",["exports"],function(a){"use strict";function b(a){return c(a)||"object"==typeof a&&null!==a}function c(a){return"function"==typeof a}function d(a){return"[object Array]"===Object.prototype.toString.call(a)}var e=Date.now||function(){return(new Date).getTime()};a.objectOrFunction=b,a.isFunction=c,a.isArray=d,a.now=e}),c("promise/polyfill").polyfill()}(),function(a,d){"object"==typeof c&&"object"==typeof b?b.exports=d():"function"==typeof define&&define.amd?define([],d):"object"==typeof c?c.localforage=d():a.localforage=d()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}b.__esModule=!0;var e=function(a){function b(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function e(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(m(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function f(a){for(var b in h)if(h.hasOwnProperty(b)&&h[b]===a)return!0;return!1}var g={},h={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},i=[h.INDEXEDDB,h.WEBSQL,h.LOCALSTORAGE],j=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],k={description:"",driver:i.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},l=function(a){var b={};return b[h.INDEXEDDB]=!!function(){try{var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB;return"undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent)?!1:b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),b[h.WEBSQL]=!!function(){try{return a.openDatabase}catch(b){return!1}}(),b[h.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),b}(a),m=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},n=function(){function a(b){d(this,a),this.INDEXEDDB=h.INDEXEDDB,this.LOCALSTORAGE=h.LOCALSTORAGE,this.WEBSQL=h.WEBSQL,this._defaultConfig=e({},k),this._config=e({},this._defaultConfig,b),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver)}return a.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},a.prototype.defineDriver=function(a,b,c){var d=new Promise(function(b,c){try{var d=a._driver,e=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),h=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(e);if(f(a._driver))return void c(h);for(var i=j.concat("_initStorage"),k=0;k<i.length;k++){var m=i[k];if(!m||!a[m]||"function"!=typeof a[m])return void c(e)}var n=Promise.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():Promise.resolve(!!a._support)),n.then(function(c){l[d]=c,g[d]=a,b()},c)}catch(o){c(o)}});return d.then(b,c),d},a.prototype.driver=function(){return this._driver||null},a.prototype.getDriver=function(a,b,d){var e=this,h=function(){if(f(a))switch(a){case e.INDEXEDDB:return new Promise(function(a,b){a(c(1))});case e.LOCALSTORAGE:return new Promise(function(a,b){a(c(2))});case e.WEBSQL:return new Promise(function(a,b){a(c(4))})}else if(g[a])return Promise.resolve(g[a]);return Promise.reject(new Error("Driver not found."))}();return h.then(b,d),h},a.prototype.getSerializer=function(a){var b=new Promise(function(a,b){a(c(3))});return a&&"function"==typeof a&&b.then(function(b){a(b)}),b},a.prototype.ready=function(a){var b=this,c=b._driverSet.then(function(){return null===b._ready&&(b._ready=b._initDriver()),b._ready});return c.then(a,a),c},a.prototype.setDriver=function(a,b,c){function d(){f._config.driver=f.driver()}function e(a){return function(){function b(){for(;c<a.length;){var e=a[c];return c++,f._dbInfo=null,f._ready=null,f.getDriver(e).then(function(a){return f._extend(a),d(),f._ready=f._initStorage(f._config),f._ready})["catch"](b)}d();var g=new Error("No available storage method found.");return f._driverSet=Promise.reject(g),f._driverSet}var c=0;return b()}}var f=this;m(a)||(a=[a]);var g=this._getSupportedDrivers(a),h=null!==this._driverSet?this._driverSet["catch"](function(){return Promise.resolve()}):Promise.resolve();return this._driverSet=h.then(function(){var a=g[0];return f._dbInfo=null,f._ready=null,f.getDriver(a).then(function(a){f._driver=a._driver,d(),f._wrapLibraryMethodsWithReady(),f._initDriver=e(g)})})["catch"](function(){d();var a=new Error("No available storage method found.");return f._driverSet=Promise.reject(a),f._driverSet}),this._driverSet.then(b,c),this._driverSet},a.prototype.supports=function(a){return!!l[a]},a.prototype._extend=function(a){e(this,a)},a.prototype._getSupportedDrivers=function(a){for(var b=[],c=0,d=a.length;d>c;c++){var e=a[c];this.supports(e)&&b.push(e)}return b},a.prototype._wrapLibraryMethodsWithReady=function(){for(var a=0;a<j.length;a++)b(this,j[a])},a.prototype.createInstance=function(b){return new a(b)},a}();return new n}("undefined"!=typeof window?window:self);b["default"]=e,a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0;var c=function(a){function b(b,c){b=b||[],c=c||{};try{return new Blob(b,c)}catch(d){if("TypeError"!==d.name)throw d;for(var e=a.BlobBuilder||a.MSBlobBuilder||a.MozBlobBuilder||a.WebKitBlobBuilder,f=new e,g=0;g<b.length;g+=1)f.append(b[g]);return f.getBlob(c.type)}}function c(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;b>e;e++)d[e]=a.charCodeAt(e);return c}function d(a){return new Promise(function(b,c){var d=new XMLHttpRequest;d.open("GET",a),d.withCredentials=!0,d.responseType="arraybuffer",d.onreadystatechange=function(){return 4===d.readyState?200===d.status?b({response:d.response,type:d.getResponseHeader("Content-Type")}):void c({status:d.status,response:d.response}):void 0},d.send()})}function e(a){return new Promise(function(c,e){var f=b([""],{type:"image/png"}),g=a.transaction([D],"readwrite");g.objectStore(D).put(f,"key"),g.oncomplete=function(){var b=a.transaction([D],"readwrite"),f=b.objectStore(D).get("key");f.onerror=e,f.onsuccess=function(a){var b=a.target.result,e=URL.createObjectURL(b);d(e).then(function(a){c(!(!a||"image/png"!==a.type))},function(){c(!1)}).then(function(){URL.revokeObjectURL(e)})}},g.onerror=g.onabort=e})["catch"](function(){return!1})}function f(a){return"boolean"==typeof B?Promise.resolve(B):e(a).then(function(a){return B=a})}function g(a){return new Promise(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function h(a){var d=c(atob(a.data));return b([d],{type:a.type})}function i(a){return a&&a.__local_forage_encoded_blob}function j(a){var b=this,c=b._initReady().then(function(){var a=C[b._dbInfo.name];return a&&a.dbReady?a.dbReady:void 0});return c.then(a,a),c}function k(a){var b=C[a.name],c={};c.promise=new Promise(function(a){c.resolve=a}),b.deferredOperations.push(c),b.dbReady?b.dbReady=b.dbReady.then(function(){return c.promise}):b.dbReady=c.promise}function l(a){var b=C[a.name],c=b.deferredOperations.pop();c&&c.resolve()}function m(a){function b(){return Promise.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];C||(C={});var f=C[d.name];f||(f={forages:[],db:null,dbReady:null,deferredOperations:[]},C[d.name]=f),f.forages.push(c),c._initReady||(c._initReady=c.ready,c.ready=j);for(var g=[],h=0;h<f.forages.length;h++){var i=f.forages[h];i!==c&&g.push(i._initReady()["catch"](b))}var k=f.forages.slice(0);return Promise.all(g).then(function(){return d.db=f.db,n(d)}).then(function(a){return d.db=a,q(d,c._defaultConfig.version)?o(d):a}).then(function(a){d.db=f.db=a,c._dbInfo=d;for(var b=0;b<k.length;b++){var e=k[b];e!==c&&(e._dbInfo.db=d.db,e._dbInfo.version=d.version)}})}function n(a){return p(a,!1)}function o(a){return p(a,!0)}function p(b,c){return new Promise(function(d,e){if(b.db){if(!c)return d(b.db);k(b),b.db.close()}var f=[b.name];c&&f.push(b.version);var g=A.open.apply(A,f);c&&(g.onupgradeneeded=function(c){var d=g.result;try{d.createObjectStore(b.storeName),c.oldVersion<=1&&d.createObjectStore(D)}catch(e){if("ConstraintError"!==e.name)throw e;a.console.warn('The database "'+b.name+'" has been upgraded from version '+c.oldVersion+" to version "+c.newVersion+', but the storage "'+b.storeName+'" already exists.')}}),g.onerror=function(){e(g.error)},g.onsuccess=function(){d(g.result),l(b)}})}function q(b,c){if(!b.db)return!0;var d=!b.db.objectStoreNames.contains(b.storeName),e=b.version<b.db.version,f=b.version>b.db.version;if(e&&(b.version!==c&&a.console.warn('The database "'+b.name+"\" can't be downgraded from version "+b.db.version+" to version "+b.version+"."),b.version=b.db.version),f||d){if(d){var g=b.db.version+1;g>b.version&&(b.version=g)}return!0}return!1}function r(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=new Promise(function(a,c){d.ready().then(function(){var e=d._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(b);g.onsuccess=function(){var b=g.result;void 0===b&&(b=null),i(b)&&(b=h(b)),a(b)},g.onerror=function(){c(g.error)}})["catch"](c)});return z(e,c),e}function s(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),j=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;i(d)&&(d=h(d));var e=a(d,c.key,j++);void 0!==e?b(e):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return z(d,b),d}function t(b,c,d){var e=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var h=new Promise(function(a,d){var h;e.ready().then(function(){return h=e._dbInfo,c instanceof Blob?f(h.db).then(function(a){return a?c:g(c)}):c}).then(function(c){var e=h.db.transaction(h.storeName,"readwrite"),f=e.objectStore(h.storeName);null===c&&(c=void 0),e.oncomplete=function(){void 0===c&&(c=null),a(c)},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;d(a)};var g=f.put(c,b)})["catch"](d)});return z(h,d),h}function u(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=new Promise(function(a,c){d.ready().then(function(){var e=d._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](b);f.oncomplete=function(){a()},f.onerror=function(){c(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;c(a)}})["catch"](c)});return z(e,c),e}function v(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return z(c,a),c}function w(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return z(c,a),c}function x(a,b){var c=this,d=new Promise(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return z(d,b),d}function y(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return z(c,a),c}function z(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var A=A||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB;if(A){var B,C,D="local-forage-detect-blob-support",E={_driver:"asyncStorage",_initStorage:m,iterate:s,getItem:r,setItem:t,removeItem:u,clear:v,length:w,key:x,keys:y};return E}}("undefined"!=typeof window?window:self);b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=function(a){function b(a){var b=this,d={};if(a)for(var e in a)d[e]=a[e];return d.keyPrefix=d.name+"/",d.storeName!==b._defaultConfig.storeName&&(d.keyPrefix+=d.storeName+"/"),b._dbInfo=d,new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,Promise.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=m.length-1;c>=0;c--){var d=m.key(c);0===d.indexOf(a)&&m.removeItem(d)}});return l(c,a),c}function e(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=d.ready().then(function(){var a=d._dbInfo,c=m.getItem(a.keyPrefix+b);return c&&(c=a.serializer.deserialize(c)),c});return l(e,c),e}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo,d=b.keyPrefix,e=d.length,f=m.length,g=1,h=0;f>h;h++){var i=m.key(h);if(0===i.indexOf(d)){var j=m.getItem(i);if(j&&(j=b.serializer.deserialize(j)),j=a(j,i.substring(e),g++),void 0!==j)return j}}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=m.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=m.length,d=[],e=0;c>e;e++)0===m.key(e).indexOf(a.keyPrefix)&&d.push(m.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=d.ready().then(function(){var a=d._dbInfo;m.removeItem(a.keyPrefix+b)});return l(e,c),e}function k(b,c,d){var e=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var f=e.ready().then(function(){void 0===c&&(c=null);var a=c;return new Promise(function(d,f){var g=e._dbInfo;g.serializer.serialize(c,function(c,e){if(e)f(e);else try{m.setItem(g.keyPrefix+b,c),d(a)}catch(h){"QuotaExceededError"!==h.name&&"NS_ERROR_DOM_QUOTA_REACHED"!==h.name||f(h),f(h)}})})});return l(f,d),f}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=null;try{if(!(a.localStorage&&"setItem"in a.localStorage))return;m=a.localStorage}catch(n){return}var o={_driver:"localStorageWrapper",_initStorage:b,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};return o}("undefined"!=typeof window?window:self);b["default"]=d,a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0;var c=function(a){function b(b,c){b=b||[],c=c||{};try{return new Blob(b,c)}catch(d){if("TypeError"!==d.name)throw d;for(var e=a.BlobBuilder||a.MSBlobBuilder||a.MozBlobBuilder||a.WebKitBlobBuilder,f=new e,g=0;g<b.length;g+=1)f.append(b[g]);return f.getBlob(c.type)}}function c(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=j;a instanceof ArrayBuffer?(d=a,e+=l):(d=a.buffer,"[object Int8Array]"===c?e+=n:"[object Uint8Array]"===c?e+=o:"[object Uint8ClampedArray]"===c?e+=p:"[object Int16Array]"===c?e+=q:"[object Uint16Array]"===c?e+=s:"[object Int32Array]"===c?e+=r:"[object Uint32Array]"===c?e+=t:"[object Float32Array]"===c?e+=u:"[object Float64Array]"===c?e+=v:b(new Error("Failed to get type for BinaryArray"))),b(e+f(d))}else if("[object Blob]"===c){var g=new FileReader;g.onload=function(){var c=h+a.type+"~"+f(this.result);b(j+m+c)},g.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(i){console.error("Couldn't convert value into a JSON string: ",a),b(null,i)}}function d(a){if(a.substring(0,k)!==j)return JSON.parse(a);var c,d=a.substring(w),f=a.substring(k,w);if(f===m&&i.test(d)){var g=d.match(i);c=g[1],d=d.substring(g[0].length)}var h=e(d);switch(f){case l:return h;case m:return b([h],{type:c});case n:return new Int8Array(h);case o:return new Uint8Array(h);case p:return new Uint8ClampedArray(h);case q:return new Int16Array(h);case s:return new Uint16Array(h);case r:return new Int32Array(h);case t:return new Uint32Array(h);case u:return new Float32Array(h);case v:return new Float64Array(h);default:throw new Error("Unkown type: "+f)}}function e(a){var b,c,d,e,f,h=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(h--,"="===a[a.length-2]&&h--);var k=new ArrayBuffer(h),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=g.indexOf(a[b]),d=g.indexOf(a[b+1]),e=g.indexOf(a[b+2]),f=g.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&f;return k}function f(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=g[c[b]>>2],d+=g[(3&c[b])<<4|c[b+1]>>4],d+=g[(15&c[b+1])<<2|c[b+2]>>6],d+=g[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h="~~local_forage_type~",i=/^~~local_forage_type~([^~]+)~/,j="__lfsc__:",k=j.length,l="arbf",m="blob",n="si08",o="ui08",p="uic8",q="si16",r="si32",s="ur16",t="ui32",u="fl32",v="fl64",w=k+l.length,x={serialize:c,deserialize:d,stringToBuffer:e,bufferToString:f};return x}("undefined"!=typeof window?window:self);b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=function(a){function b(a){var b=this,d={db:null};if(a)for(var e in a)d[e]="string"!=typeof a[e]?a[e].toString():a[e];var f=new Promise(function(a,c){try{d.db=m(d.name,String(d.version),d.description,d.size)}catch(e){return c(e)}d.db.transaction(function(e){e.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=d,a()},function(a,b){c(b)})})});return new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,f})}function d(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=new Promise(function(a,c){d.ready().then(function(){var e=d._dbInfo;e.db.transaction(function(d){d.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[b],function(b,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.deserialize(d)),a(d)},function(a,b){c(b)})})})["catch"](c)});return l(e,c),e}function e(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var f=d.rows,g=f.length,h=0;g>h;h++){var i=f.item(h),j=i.value;if(j&&(j=e.serializer.deserialize(j)),j=a(j,i.key,h+1),void 0!==j)return void b(j)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(b,c,d){var e=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var f=new Promise(function(a,d){e.ready().then(function(){void 0===c&&(c=null);var f=c,g=e._dbInfo;g.serializer.serialize(c,function(c,e){e?d(e):g.db.transaction(function(e){e.executeSql("INSERT OR REPLACE INTO "+g.storeName+" (key, value) VALUES (?, ?)",[b,c],function(){a(f)},function(a,b){d(b)})},function(a){a.code===a.QUOTA_ERR&&d(a)})})})["catch"](d)});return l(f,d),f}function g(b,c){var d=this;"string"!=typeof b&&(a.console.warn(b+" used as a key, but it is not a string."),b=String(b));var e=new Promise(function(a,c){d.ready().then(function(){var e=d._dbInfo;e.db.transaction(function(d){d.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[b],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(e,c),e}function h(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=a.openDatabase;if(m){var n={_driver:"webSQLStorage",_initStorage:b,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};return n}}("undefined"!=typeof window?window:self);b["default"]=d,a.exports=b["default"]}])})}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:95}],79:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":80,"./lib/inflate":81,"./lib/utils/common":82,"./lib/zlib/constants":85}],80:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=i.assign({level:s,method:u,chunkSize:16384,windowBits:15,memLevel:8,strategy:t,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=h.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==p)throw new Error(k[c]);b.header&&h.deflateSetHeader(this.strm,b.header)}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}function g(a,b){return b=b||{},b.gzip=!0,e(a,b)}var h=a("./zlib/deflate"),i=a("./utils/common"),j=a("./utils/strings"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=Object.prototype.toString,n=0,o=4,p=0,q=1,r=2,s=-1,t=0,u=8;d.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?o:n,"string"==typeof a?e.input=j.string2buf(a):"[object ArrayBuffer]"===m.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new i.Buf8(f),e.next_out=0,e.avail_out=f),c=h.deflate(e,d),c!==q&&c!==p)return this.onEnd(c),this.ended=!0,!1;0!==e.avail_out&&(0!==e.avail_in||d!==o&&d!==r)||("string"===this.options.to?this.onData(j.buf2binstring(i.shrinkBuf(e.output,e.next_out))):this.onData(i.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==q);return d===o?(c=h.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===p):d===r?(this.onEnd(p),e.avail_out=0,!0):!0},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===p&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=d,c.deflate=e,c.deflateRaw=f,c.gzip=g},{"./utils/common":82,"./utils/strings":83,"./zlib/deflate":87,"./zlib/messages":92,"./zlib/zstream":94}],81:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=h.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=g.inflateInit2(this.strm,b.windowBits);if(c!==j.Z_OK)throw new Error(k[c]);this.header=new m,g.inflateGetHeader(this.strm,this.header)}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}var g=a("./zlib/inflate"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/constants"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=a("./zlib/gzheader"),n=Object.prototype.toString;d.prototype.push=function(a,b){var c,d,e,f,k,l=this.strm,m=this.options.chunkSize,o=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?j.Z_FINISH:j.Z_NO_FLUSH, "string"==typeof a?l.input=i.binstring2buf(a):"[object ArrayBuffer]"===n.call(a)?l.input=new Uint8Array(a):l.input=a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new h.Buf8(m),l.next_out=0,l.avail_out=m),c=g.inflate(l,j.Z_NO_FLUSH),c===j.Z_BUF_ERROR&&o===!0&&(c=j.Z_OK,o=!1),c!==j.Z_STREAM_END&&c!==j.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0!==l.avail_out&&c!==j.Z_STREAM_END&&(0!==l.avail_in||d!==j.Z_FINISH&&d!==j.Z_SYNC_FLUSH)||("string"===this.options.to?(e=i.utf8border(l.output,l.next_out),f=l.next_out-e,k=i.buf2string(l.output,e),l.next_out=f,l.avail_out=m-f,f&&h.arraySet(l.output,l.output,e,f,0),this.onData(k)):this.onData(h.shrinkBuf(l.output,l.next_out)))),0===l.avail_in&&0===l.avail_out&&(o=!0)}while((l.avail_in>0||0===l.avail_out)&&c!==j.Z_STREAM_END);return c===j.Z_STREAM_END&&(d=j.Z_FINISH),d===j.Z_FINISH?(c=g.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===j.Z_OK):d===j.Z_SYNC_FLUSH?(this.onEnd(j.Z_OK),l.avail_out=0,!0):!0},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===j.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=d,c.inflate=e,c.inflateRaw=f,c.ungzip=e},{"./utils/common":82,"./utils/strings":83,"./zlib/constants":85,"./zlib/gzheader":88,"./zlib/inflate":90,"./zlib/messages":92,"./zlib/zstream":94}],82:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],83:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":82}],84:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=d},{}],85:[function(a,b,c){"use strict";b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],86:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a^=-1;for(var h=d;g>h;h++)a=a>>>8^e[255&(a^b[h])];return-1^a}var f=d();b.exports=e},{}],87:[function(a,b,c){"use strict";function d(a,b){return a.msg=H[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(D.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){E._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,D.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=F(a.adler,b,e,c):2===a.state.wrap&&(a.adler=G(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-ka?a.strstart-(a.w_size-ka):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ja,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ja-(m-f),f=m-ja,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-ka)){D.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ia)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ia-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ia)););}while(a.lookahead<ka&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===I)return ta;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return ta;if(a.strstart-a.block_start>=a.w_size-ka&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=0,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?ta:ta}function o(a,b){for(var c,d;;){if(a.lookahead<ka){if(m(a),a.lookahead<ka&&b===I)return ta;if(0===a.lookahead)break}if(c=0,a.lookahead>=ia&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-ka&&(a.match_length=l(a,c)),a.match_length>=ia)if(d=E._tr_tally(a,a.strstart-a.match_start,a.match_length-ia),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ia){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=E._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=a.strstart<ia-1?a.strstart:ia-1,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function p(a,b){for(var c,d,e;;){if(a.lookahead<ka){if(m(a),a.lookahead<ka&&b===I)return ta;if(0===a.lookahead)break}if(c=0,a.lookahead>=ia&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ia-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-ka&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===T||a.match_length===ia&&a.strstart-a.match_start>4096)&&(a.match_length=ia-1)),a.prev_length>=ia&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ia,d=E._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ia),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ia-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return ta}else if(a.match_available){if(d=E._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return ta}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=E._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ia-1?a.strstart:ia-1,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ja){if(m(a),a.lookahead<=ja&&b===I)return ta;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ia&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ja;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ja-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ia?(c=E._tr_tally(a,1,a.match_length-ia),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=E._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=0,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===I)return ta;break}if(a.match_length=0,c=E._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=0,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function s(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e}function t(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=C[a.level].max_lazy,a.good_match=C[a.level].good_length,a.nice_match=C[a.level].nice_length,a.max_chain_length=C[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ia-1,a.match_available=0,a.ins_h=0}function u(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new D.Buf16(2*ga),this.dyn_dtree=new D.Buf16(2*(2*ea+1)),this.bl_tree=new D.Buf16(2*(2*fa+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new D.Buf16(ha+1),this.heap=new D.Buf16(2*da+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new D.Buf16(2*da+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function v(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=Y,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?ma:ra,a.adler=2===b.wrap?0:1,b.last_flush=I,E._tr_init(b),N):d(a,P)}function w(a){var b=v(a);return b===N&&t(a.state),b}function x(a,b){return a&&a.state?2!==a.state.wrap?P:(a.state.gzhead=b,N):P}function y(a,b,c,e,f,g){if(!a)return P;var h=1;if(b===S&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>$||c!==Z||8>e||e>15||0>b||b>9||0>g||g>W)return d(a,P);8===e&&(e=9);var i=new u;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ia-1)/ia),i.window=new D.Buf8(2*i.w_size),i.head=new D.Buf16(i.hash_size),i.prev=new D.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new D.Buf8(i.pending_buf_size),i.d_buf=i.lit_bufsize>>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,w(a)}function z(a,b){return y(a,b,Z,_,aa,X)}function A(a,b){var c,h,k,l;if(!a||!a.state||b>M||0>b)return a?d(a,P):P;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===sa&&b!==L)return d(a,0===a.avail_out?R:P);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===ma)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=U||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=G(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=na):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=U||h.level<2?4:0),i(h,xa),h.status=ra);else{var m=Z+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=U||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=la),m+=31-m%31,h.status=ra,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===na)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=oa)}else h.status=oa;if(h.status===oa)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=pa)}else h.status=pa;if(h.status===pa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=qa)}else h.status=qa;if(h.status===qa&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=ra)):h.status=ra),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,N}else if(0===a.avail_in&&e(b)<=e(c)&&b!==L)return d(a,R);if(h.status===sa&&0!==a.avail_in)return d(a,R);if(0!==a.avail_in||0!==h.lookahead||b!==I&&h.status!==sa){var o=h.strategy===U?r(h,b):h.strategy===V?q(h,b):C[h.level].func(h,b);if(o!==va&&o!==wa||(h.status=sa),o===ta||o===va)return 0===a.avail_out&&(h.last_flush=-1),N;if(o===ua&&(b===J?E._tr_align(h):b!==M&&(E._tr_stored_block(h,0,0,!1),b===K&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,N}return b!==L?N:h.wrap<=0?O:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?N:O)}function B(a){var b;return a&&a.state?(b=a.state.status,b!==ma&&b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra&&b!==sa?d(a,P):(a.state=null,b===ra?d(a,Q):N)):P}var C,D=a("../utils/common"),E=a("./trees"),F=a("./adler32"),G=a("./crc32"),H=a("./messages"),I=0,J=1,K=3,L=4,M=5,N=0,O=1,P=-2,Q=-3,R=-5,S=-1,T=1,U=2,V=3,W=4,X=0,Y=2,Z=8,$=9,_=15,aa=8,ba=29,ca=256,da=ca+1+ba,ea=30,fa=19,ga=2*da+1,ha=15,ia=3,ja=258,ka=ja+ia+1,la=32,ma=42,na=69,oa=73,pa=91,qa=103,ra=113,sa=666,ta=1,ua=2,va=3,wa=4,xa=3;C=[new s(0,0,0,0,n),new s(4,4,8,4,o),new s(4,5,16,8,o),new s(4,6,32,32,o),new s(4,4,16,16,p),new s(8,16,32,32,p),new s(8,16,128,128,p),new s(8,32,128,256,p),new s(32,128,258,1024,p),new s(32,258,258,4096,p)],c.deflateInit=z,c.deflateInit2=y,c.deflateReset=w,c.deflateResetKeep=v,c.deflateSetHeader=x,c.deflate=A,c.deflateEnd=B,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":82,"./adler32":84,"./crc32":86,"./messages":92,"./trees":93}],88:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],89:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(w>q&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,w>q&&(p+=B[f++]<<q,q+=8,w>q&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=g>f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],90:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(oa),b.distcode=b.distdyn=new r.Buf32(pa),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,ra)}function k(a){if(sa){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sa=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new r.Buf8(f.wsize)),d>=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,oa,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new r.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return F;c=a.state,c.mode===V&&(c.mode=W),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=C;a:for(;;)switch(c.mode){case K:if(0===c.wrap){c.mode=W;break}for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=la;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=la;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=la;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?T:V,m=0,n=0;break;case L:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==J){a.msg="unknown compression method",c.mode=la;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=la;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=t(c.check,Ba,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=la;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=U;case U:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,E;a.adler=c.check=1,c.mode=V;case V:if(b===A||b===B)break a;case W:if(c.last){m>>>=7&n,n-=7&n,c.mode=ia;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=ba,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=la}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=la;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=la;break}c.have=0,c.mode=_;case _:for(;c.have<c.ncode;){for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=v(w,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=la;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(16>sa)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=la;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=la;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===la)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=la;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=la;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=la;break}if(c.mode=ba,b===B)break a;case ba:c.mode=ca;case ca:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ha;break}if(32&ra){c.back=-1,c.mode=V;break}if(64&ra){a.msg="invalid literal/length code",c.mode=la;break}c.extra=15&ra,c.mode=da;case da:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=ea;case ea:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=la;break}c.offset=sa,c.extra=15&ra,c.mode=fa;case fa:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=la;break}c.mode=ga;case ga:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=la;break}q>c.wnext?(q-=c.wnext,oa=c.wsize-q):oa=c.wnext-q,q>c.length&&(q=c.length),pa=c.window}else pa=f,oa=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[oa++];while(--q);0===c.length&&(c.mode=ca);break;case ha:if(0===j)break a;f[h++]=c.length,j--,c.mode=ca;break;case ia:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?t(c.check,f,p,h-p):s(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=la;break}m=0,n=0}c.mode=ja;case ja:if(c.wrap&&c.flags){for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=la;break}m=0,n=0}c.mode=ka;case ka:xa=D;break a;case la:xa=G;break a;case ma:return H;case na:default:return F}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<la&&(c.mode<ia||b!==z))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=ma,H):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?t(c.check,f,p,a.next_out-p):s(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===V?128:0)+(c.mode===ba||c.mode===Y?256:0),(0===o&&0===p||b===z)&&xa===C&&(xa=I),xa)}function n(a){if(!a||!a.state)return F;var b=a.state;return b.window&&(b.window=null),a.state=null,C}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?F:(c.head=b,b.done=!1,C)):F}var p,q,r=a("../utils/common"),s=a("./adler32"),t=a("./crc32"),u=a("./inffast"),v=a("./inftrees"),w=0,x=1,y=2,z=4,A=5,B=6,C=0,D=1,E=2,F=-2,G=-3,H=-4,I=-5,J=8,K=1,L=2,M=3,N=4,O=5,P=6,Q=7,R=8,S=9,T=10,U=11,V=12,W=13,X=14,Y=15,Z=16,$=17,_=18,aa=19,ba=20,ca=21,da=22,ea=23,fa=24,ga=25,ha=26,ia=27,ja=28,ka=29,la=30,ma=31,na=32,oa=852,pa=592,qa=15,ra=qa,sa=!0; c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":82,"./adler32":84,"./crc32":86,"./inffast":89,"./inftrees":91}],91:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;e>=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;e>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;e>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;G>I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":82}],92:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],93:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length}function f(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b}function g(a){return 256>a?ia[a]:ia[256+(a>>>7)]}function h(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function i(a,b,c){a.bi_valid>X-c?(a.bi_buf|=b<<a.bi_valid&65535,h(a,a.bi_buf),a.bi_buf=b>>X-a.bi_valid,a.bi_valid+=c-X):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function j(a,b,c){i(a,c[2*b],c[2*b+1])}function k(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function l(a){16===a.bi_valid?(h(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function m(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;W>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;V>c;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function n(a,b,c){var d,e,f=new Array(W+1),g=0;for(d=1;W>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=k(f[h]++,h))}}function o(){var a,b,c,d,f,g=new Array(W+1);for(c=0,d=0;Q-1>d;d++)for(ka[d]=c,a=0;a<1<<ba[d];a++)ja[c++]=d;for(ja[c-1]=d,f=0,d=0;16>d;d++)for(la[d]=f,a=0;a<1<<ca[d];a++)ia[f++]=d;for(f>>=7;T>d;d++)for(la[d]=f<<7,a=0;a<1<<ca[d]-7;a++)ia[256+f++]=d;for(b=0;W>=b;b++)g[b]=0;for(a=0;143>=a;)ga[2*a+1]=8,a++,g[8]++;for(;255>=a;)ga[2*a+1]=9,a++,g[9]++;for(;279>=a;)ga[2*a+1]=7,a++,g[7]++;for(;287>=a;)ga[2*a+1]=8,a++,g[8]++;for(n(ga,S+1,g),a=0;T>a;a++)ha[2*a+1]=5,ha[2*a]=k(a,5);ma=new e(ga,ba,R+1,S,W),na=new e(ha,ca,0,T,W),oa=new e(new Array(0),da,0,U,Y)}function p(a){var b;for(b=0;S>b;b++)a.dyn_ltree[2*b]=0;for(b=0;T>b;b++)a.dyn_dtree[2*b]=0;for(b=0;U>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*Z]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function q(a){a.bi_valid>8?h(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function r(a,b,c,d){q(a),d&&(h(a,c),h(a,~c)),G.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function s(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function t(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&s(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!s(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function u(a,b,c){var d,e,f,h,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],e=a.pending_buf[a.l_buf+k],k++,0===d?j(a,e,b):(f=ja[e],j(a,f+R+1,b),h=ba[f],0!==h&&(e-=ka[f],i(a,e,h)),d--,f=g(d),j(a,f,c),h=ca[f],0!==h&&(d-=la[f],i(a,d,h)));while(k<a.last_lit);j(a,Z,b)}function v(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=V,c=0;i>c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)t(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],t(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,t(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],m(a,b),n(f,j,a.bl_count)}function w(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(j>h?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*$]++):10>=h?a.bl_tree[2*_]++:a.bl_tree[2*aa]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function x(a,b,c){var d,e,f=-1,g=b[1],h=0,k=7,l=4;for(0===g&&(k=138,l=3),d=0;c>=d;d++)if(e=g,g=b[2*(d+1)+1],!(++h<k&&e===g)){if(l>h){do j(a,e,a.bl_tree);while(0!==--h)}else 0!==e?(e!==f&&(j(a,e,a.bl_tree),h--),j(a,$,a.bl_tree),i(a,h-3,2)):10>=h?(j(a,_,a.bl_tree),i(a,h-3,3)):(j(a,aa,a.bl_tree),i(a,h-11,7));h=0,f=e,0===g?(k=138,l=3):e===g?(k=6,l=3):(k=7,l=4)}}function y(a){var b;for(w(a,a.dyn_ltree,a.l_desc.max_code),w(a,a.dyn_dtree,a.d_desc.max_code),v(a,a.bl_desc),b=U-1;b>=3&&0===a.bl_tree[2*ea[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function z(a,b,c,d){var e;for(i(a,b-257,5),i(a,c-1,5),i(a,d-4,4),e=0;d>e;e++)i(a,a.bl_tree[2*ea[e]+1],3);x(a,a.dyn_ltree,b-1),x(a,a.dyn_dtree,c-1)}function A(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return I;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return J;for(b=32;R>b;b++)if(0!==a.dyn_ltree[2*b])return J;return I}function B(a){pa||(o(),pa=!0),a.l_desc=new f(a.dyn_ltree,ma),a.d_desc=new f(a.dyn_dtree,na),a.bl_desc=new f(a.bl_tree,oa),a.bi_buf=0,a.bi_valid=0,p(a)}function C(a,b,c,d){i(a,(L<<1)+(d?1:0),3),r(a,b,c,!0)}function D(a){i(a,M<<1,3),j(a,Z,ga),l(a)}function E(a,b,c,d){var e,f,g=0;a.level>0?(a.strm.data_type===K&&(a.strm.data_type=A(a)),v(a,a.l_desc),v(a,a.d_desc),g=y(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?C(a,b,c,d):a.strategy===H||f===e?(i(a,(M<<1)+(d?1:0),3),u(a,ga,ha)):(i(a,(N<<1)+(d?1:0),3),z(a,a.l_desc.max_code+1,a.d_desc.max_code+1,g+1),u(a,a.dyn_ltree,a.dyn_dtree)),p(a),d&&q(a)}function F(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ja[c]+R+1)]++,a.dyn_dtree[2*g(b)]++),a.last_lit===a.lit_bufsize-1}var G=a("../utils/common"),H=4,I=0,J=1,K=2,L=0,M=1,N=2,O=3,P=258,Q=29,R=256,S=R+1+Q,T=30,U=19,V=2*S+1,W=15,X=16,Y=7,Z=256,$=16,_=17,aa=18,ba=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],ca=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],da=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ea=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],fa=512,ga=new Array(2*(S+2));d(ga);var ha=new Array(2*T);d(ha);var ia=new Array(fa);d(ia);var ja=new Array(P-O+1);d(ja);var ka=new Array(Q);d(ka);var la=new Array(T);d(la);var ma,na,oa,pa=!1;c._tr_init=B,c._tr_stored_block=C,c._tr_flush_block=E,c._tr_tally=F,c._tr_align=D},{"../utils/common":82}],94:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}],95:[function(a,b,c){function d(){k=!1,h.length?j=h.concat(j):l=-1,j.length&&e()}function e(){if(!k){var a=setTimeout(d);k=!0;for(var b=j.length;b;){for(h=j,j=[];++l<b;)h&&h[l].run();l=-1,b=j.length}h=null,k=!1,clearTimeout(a)}}function f(a,b){this.fun=a,this.array=b}function g(){}var h,i=b.exports={},j=[],k=!1,l=-1;i.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];j.push(new f(a,b)),1!==j.length||k||setTimeout(e,0)},f.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=g,i.addListener=g,i.once=g,i.off=g,i.removeListener=g,i.removeAllListeners=g,i.emit=g,i.binding=function(a){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(a){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}]},{},[1]);
ajax/libs/yui/3.11.0/event-focus/event-focus-coverage.js
StoneCypher/cdnjs
if (typeof __coverage__ === 'undefined') { __coverage__ = {}; } if (!__coverage__['build/event-focus/event-focus.js']) { __coverage__['build/event-focus/event-focus.js'] = {"path":"build/event-focus/event-focus.js","s":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"80":0,"81":0,"82":0,"83":0,"84":0,"85":0,"86":0,"87":0,"88":0,"89":0,"90":0},"b":{"1":[0,0],"2":[0,0],"3":[0,0],"4":[0,0],"5":[0,0],"6":[0,0],"7":[0,0],"8":[0,0],"9":[0,0],"10":[0,0],"11":[0,0],"12":[0,0],"13":[0,0],"14":[0,0],"15":[0,0],"16":[0,0],"17":[0,0],"18":[0,0],"19":[0,0],"20":[0,0],"21":[0,0],"22":[0,0],"23":[0,0],"24":[0,0],"25":[0,0],"26":[0,0],"27":[0,0],"28":[0,0],"29":[0,0],"30":[0,0]},"f":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":23},"end":{"line":1,"column":42}}},"2":{"name":"(anonymous_2)","line":17,"loc":{"start":{"line":17,"column":19},"end":{"line":17,"column":30}}},"3":{"name":"define","line":45,"loc":{"start":{"line":45,"column":0},"end":{"line":45,"column":42}}},"4":{"name":"(anonymous_4)","line":52,"loc":{"start":{"line":52,"column":17},"end":{"line":52,"column":51}}},"5":{"name":"(anonymous_5)","line":54,"loc":{"start":{"line":54,"column":44},"end":{"line":54,"column":57}}},"6":{"name":"(anonymous_6)","line":64,"loc":{"start":{"line":64,"column":16},"end":{"line":64,"column":49}}},"7":{"name":"(anonymous_7)","line":113,"loc":{"start":{"line":113,"column":17},"end":{"line":113,"column":41}}},"8":{"name":"(anonymous_8)","line":143,"loc":{"start":{"line":143,"column":31},"end":{"line":143,"column":47}}},"9":{"name":"(anonymous_9)","line":231,"loc":{"start":{"line":231,"column":12},"end":{"line":231,"column":43}}},"10":{"name":"(anonymous_10)","line":235,"loc":{"start":{"line":235,"column":16},"end":{"line":235,"column":37}}},"11":{"name":"(anonymous_11)","line":239,"loc":{"start":{"line":239,"column":18},"end":{"line":239,"column":57}}},"12":{"name":"(anonymous_12)","line":241,"loc":{"start":{"line":241,"column":29},"end":{"line":241,"column":47}}},"13":{"name":"(anonymous_13)","line":250,"loc":{"start":{"line":250,"column":24},"end":{"line":250,"column":45}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":273,"column":51}},"2":{"start":{"line":9,"column":0},"end":{"line":43,"column":9}},"3":{"start":{"line":23,"column":8},"end":{"line":25,"column":14}},"4":{"start":{"line":27,"column":8},"end":{"line":40,"column":9}},"5":{"start":{"line":29,"column":12},"end":{"line":29,"column":39}},"6":{"start":{"line":30,"column":12},"end":{"line":30,"column":52}},"7":{"start":{"line":39,"column":12},"end":{"line":39,"column":59}},"8":{"start":{"line":42,"column":8},"end":{"line":42,"column":25}},"9":{"start":{"line":45,"column":0},"end":{"line":254,"column":1}},"10":{"start":{"line":46,"column":4},"end":{"line":46,"column":47}},"11":{"start":{"line":48,"column":4},"end":{"line":253,"column":13}},"12":{"start":{"line":53,"column":12},"end":{"line":61,"column":13}},"13":{"start":{"line":54,"column":16},"end":{"line":56,"column":24}},"14":{"start":{"line":55,"column":20},"end":{"line":55,"column":37}},"15":{"start":{"line":58,"column":16},"end":{"line":60,"column":39}},"16":{"start":{"line":65,"column":12},"end":{"line":70,"column":26}},"17":{"start":{"line":72,"column":12},"end":{"line":72,"column":73}},"18":{"start":{"line":73,"column":12},"end":{"line":73,"column":71}},"19":{"start":{"line":79,"column":12},"end":{"line":100,"column":13}},"20":{"start":{"line":80,"column":16},"end":{"line":80,"column":31}},"21":{"start":{"line":81,"column":16},"end":{"line":81,"column":55}},"22":{"start":{"line":85,"column":16},"end":{"line":89,"column":17}},"23":{"start":{"line":86,"column":20},"end":{"line":87,"column":71}},"24":{"start":{"line":88,"column":20},"end":{"line":88,"column":42}},"25":{"start":{"line":99,"column":16},"end":{"line":99,"column":29}},"26":{"start":{"line":102,"column":12},"end":{"line":104,"column":13}},"27":{"start":{"line":103,"column":16},"end":{"line":103,"column":37}},"28":{"start":{"line":106,"column":12},"end":{"line":106,"column":43}},"29":{"start":{"line":108,"column":12},"end":{"line":110,"column":13}},"30":{"start":{"line":109,"column":16},"end":{"line":109,"column":32}},"31":{"start":{"line":114,"column":12},"end":{"line":124,"column":80}},"32":{"start":{"line":127,"column":12},"end":{"line":127,"column":49}},"33":{"start":{"line":130,"column":12},"end":{"line":130,"column":42}},"34":{"start":{"line":133,"column":12},"end":{"line":135,"column":13}},"35":{"start":{"line":134,"column":16},"end":{"line":134,"column":39}},"36":{"start":{"line":138,"column":12},"end":{"line":138,"column":39}},"37":{"start":{"line":140,"column":12},"end":{"line":160,"column":13}},"38":{"start":{"line":142,"column":16},"end":{"line":142,"column":28}},"39":{"start":{"line":143,"column":16},"end":{"line":158,"column":19}},"40":{"start":{"line":144,"column":20},"end":{"line":146,"column":31}},"41":{"start":{"line":148,"column":20},"end":{"line":155,"column":21}},"42":{"start":{"line":149,"column":24},"end":{"line":149,"column":32}},"43":{"start":{"line":150,"column":24},"end":{"line":154,"column":25}},"44":{"start":{"line":151,"column":28},"end":{"line":153,"column":29}},"45":{"start":{"line":152,"column":32},"end":{"line":152,"column":61}},"46":{"start":{"line":157,"column":20},"end":{"line":157,"column":34}},"47":{"start":{"line":159,"column":16},"end":{"line":159,"column":28}},"48":{"start":{"line":164,"column":12},"end":{"line":228,"column":13}},"49":{"start":{"line":165,"column":16},"end":{"line":165,"column":39}},"50":{"start":{"line":167,"column":16},"end":{"line":167,"column":47}},"51":{"start":{"line":169,"column":16},"end":{"line":201,"column":17}},"52":{"start":{"line":170,"column":20},"end":{"line":197,"column":21}},"53":{"start":{"line":171,"column":24},"end":{"line":171,"column":48}},"54":{"start":{"line":172,"column":24},"end":{"line":172,"column":55}},"55":{"start":{"line":173,"column":24},"end":{"line":173,"column":40}},"56":{"start":{"line":175,"column":24},"end":{"line":175,"column":49}},"57":{"start":{"line":177,"column":24},"end":{"line":186,"column":25}},"58":{"start":{"line":178,"column":28},"end":{"line":179,"column":68}},"59":{"start":{"line":184,"column":28},"end":{"line":185,"column":68}},"60":{"start":{"line":188,"column":24},"end":{"line":192,"column":25}},"61":{"start":{"line":190,"column":28},"end":{"line":190,"column":61}},"62":{"start":{"line":191,"column":28},"end":{"line":191,"column":51}},"63":{"start":{"line":194,"column":24},"end":{"line":196,"column":25}},"64":{"start":{"line":195,"column":28},"end":{"line":195,"column":34}},"65":{"start":{"line":199,"column":20},"end":{"line":199,"column":43}},"66":{"start":{"line":200,"column":20},"end":{"line":200,"column":28}},"67":{"start":{"line":203,"column":16},"end":{"line":223,"column":17}},"68":{"start":{"line":207,"column":20},"end":{"line":222,"column":21}},"69":{"start":{"line":208,"column":24},"end":{"line":208,"column":48}},"70":{"start":{"line":209,"column":24},"end":{"line":209,"column":50}},"71":{"start":{"line":211,"column":24},"end":{"line":217,"column":25}},"72":{"start":{"line":214,"column":28},"end":{"line":214,"column":61}},"73":{"start":{"line":215,"column":28},"end":{"line":215,"column":53}},"74":{"start":{"line":216,"column":28},"end":{"line":216,"column":51}},"75":{"start":{"line":219,"column":24},"end":{"line":221,"column":25}},"76":{"start":{"line":220,"column":28},"end":{"line":220,"column":34}},"77":{"start":{"line":225,"column":16},"end":{"line":227,"column":17}},"78":{"start":{"line":226,"column":20},"end":{"line":226,"column":26}},"79":{"start":{"line":232,"column":12},"end":{"line":232,"column":60}},"80":{"start":{"line":236,"column":12},"end":{"line":236,"column":32}},"81":{"start":{"line":240,"column":12},"end":{"line":245,"column":13}},"82":{"start":{"line":241,"column":16},"end":{"line":244,"column":18}},"83":{"start":{"line":242,"column":20},"end":{"line":243,"column":61}},"84":{"start":{"line":247,"column":12},"end":{"line":247,"column":66}},"85":{"start":{"line":251,"column":12},"end":{"line":251,"column":32}},"86":{"start":{"line":263,"column":0},"end":{"line":270,"column":1}},"87":{"start":{"line":265,"column":4},"end":{"line":265,"column":51}},"88":{"start":{"line":266,"column":4},"end":{"line":266,"column":52}},"89":{"start":{"line":268,"column":4},"end":{"line":268,"column":38}},"90":{"start":{"line":269,"column":4},"end":{"line":269,"column":37}}},"branchMap":{"1":{"line":27,"type":"if","locations":[{"start":{"line":27,"column":8},"end":{"line":27,"column":8}},{"start":{"line":27,"column":8},"end":{"line":27,"column":8}}]},"2":{"line":53,"type":"if","locations":[{"start":{"line":53,"column":12},"end":{"line":53,"column":12}},{"start":{"line":53,"column":12},"end":{"line":53,"column":12}}]},"3":{"line":69,"type":"binary-expr","locations":[{"start":{"line":69,"column":33},"end":{"line":69,"column":44}},{"start":{"line":69,"column":48},"end":{"line":69,"column":72}}]},"4":{"line":72,"type":"cond-expr","locations":[{"start":{"line":72,"column":50},"end":{"line":72,"column":56}},{"start":{"line":72,"column":59},"end":{"line":72,"column":72}}]},"5":{"line":73,"type":"cond-expr","locations":[{"start":{"line":73,"column":50},"end":{"line":73,"column":63}},{"start":{"line":73,"column":66},"end":{"line":73,"column":70}}]},"6":{"line":79,"type":"if","locations":[{"start":{"line":79,"column":12},"end":{"line":79,"column":12}},{"start":{"line":79,"column":12},"end":{"line":79,"column":12}}]},"7":{"line":85,"type":"if","locations":[{"start":{"line":85,"column":16},"end":{"line":85,"column":16}},{"start":{"line":85,"column":16},"end":{"line":85,"column":16}}]},"8":{"line":102,"type":"if","locations":[{"start":{"line":102,"column":12},"end":{"line":102,"column":12}},{"start":{"line":102,"column":12},"end":{"line":102,"column":12}}]},"9":{"line":108,"type":"if","locations":[{"start":{"line":108,"column":12},"end":{"line":108,"column":12}},{"start":{"line":108,"column":12},"end":{"line":108,"column":12}}]},"10":{"line":121,"type":"cond-expr","locations":[{"start":{"line":122,"column":36},"end":{"line":122,"column":70}},{"start":{"line":123,"column":36},"end":{"line":123,"column":37}}]},"11":{"line":133,"type":"if","locations":[{"start":{"line":133,"column":12},"end":{"line":133,"column":12}},{"start":{"line":133,"column":12},"end":{"line":133,"column":12}}]},"12":{"line":140,"type":"if","locations":[{"start":{"line":140,"column":12},"end":{"line":140,"column":12}},{"start":{"line":140,"column":12},"end":{"line":140,"column":12}}]},"13":{"line":148,"type":"if","locations":[{"start":{"line":148,"column":20},"end":{"line":148,"column":20}},{"start":{"line":148,"column":20},"end":{"line":148,"column":20}}]},"14":{"line":151,"type":"if","locations":[{"start":{"line":151,"column":28},"end":{"line":151,"column":28}},{"start":{"line":151,"column":28},"end":{"line":151,"column":28}}]},"15":{"line":164,"type":"binary-expr","locations":[{"start":{"line":164,"column":19},"end":{"line":164,"column":24}},{"start":{"line":164,"column":29},"end":{"line":164,"column":55}}]},"16":{"line":169,"type":"if","locations":[{"start":{"line":169,"column":16},"end":{"line":169,"column":16}},{"start":{"line":169,"column":16},"end":{"line":169,"column":16}}]},"17":{"line":177,"type":"if","locations":[{"start":{"line":177,"column":24},"end":{"line":177,"column":24}},{"start":{"line":177,"column":24},"end":{"line":177,"column":24}}]},"18":{"line":179,"type":"binary-expr","locations":[{"start":{"line":179,"column":51},"end":{"line":179,"column":59}},{"start":{"line":179,"column":63},"end":{"line":179,"column":65}}]},"19":{"line":188,"type":"if","locations":[{"start":{"line":188,"column":24},"end":{"line":188,"column":24}},{"start":{"line":188,"column":24},"end":{"line":188,"column":24}}]},"20":{"line":194,"type":"if","locations":[{"start":{"line":194,"column":24},"end":{"line":194,"column":24}},{"start":{"line":194,"column":24},"end":{"line":194,"column":24}}]},"21":{"line":194,"type":"binary-expr","locations":[{"start":{"line":194,"column":28},"end":{"line":194,"column":41}},{"start":{"line":194,"column":45},"end":{"line":194,"column":60}}]},"22":{"line":203,"type":"if","locations":[{"start":{"line":203,"column":16},"end":{"line":203,"column":16}},{"start":{"line":203,"column":16},"end":{"line":203,"column":16}}]},"23":{"line":211,"type":"if","locations":[{"start":{"line":211,"column":24},"end":{"line":211,"column":24}},{"start":{"line":211,"column":24},"end":{"line":211,"column":24}}]},"24":{"line":212,"type":"binary-expr","locations":[{"start":{"line":212,"column":47},"end":{"line":212,"column":55}},{"start":{"line":212,"column":59},"end":{"line":212,"column":61}}]},"25":{"line":219,"type":"if","locations":[{"start":{"line":219,"column":24},"end":{"line":219,"column":24}},{"start":{"line":219,"column":24},"end":{"line":219,"column":24}}]},"26":{"line":219,"type":"binary-expr","locations":[{"start":{"line":219,"column":28},"end":{"line":219,"column":41}},{"start":{"line":219,"column":45},"end":{"line":219,"column":60}}]},"27":{"line":225,"type":"if","locations":[{"start":{"line":225,"column":16},"end":{"line":225,"column":16}},{"start":{"line":225,"column":16},"end":{"line":225,"column":16}}]},"28":{"line":240,"type":"if","locations":[{"start":{"line":240,"column":12},"end":{"line":240,"column":12}},{"start":{"line":240,"column":12},"end":{"line":240,"column":12}}]},"29":{"line":243,"type":"cond-expr","locations":[{"start":{"line":243,"column":42},"end":{"line":243,"column":46}},{"start":{"line":243,"column":49},"end":{"line":243,"column":59}}]},"30":{"line":263,"type":"if","locations":[{"start":{"line":263,"column":0},"end":{"line":263,"column":0}},{"start":{"line":263,"column":0},"end":{"line":263,"column":0}}]}},"code":["(function () { YUI.add('event-focus', function (Y, NAME) {","","/**"," * Adds bubbling and delegation support to DOM events focus and blur."," *"," * @module event"," * @submodule event-focus"," */","var Event = Y.Event,",""," YLang = Y.Lang,",""," isString = YLang.isString,",""," arrayIndex = Y.Array.indexOf,",""," useActivate = (function() {",""," // Changing the structure of this test, so that it doesn't use inline JS in HTML,"," // which throws an exception in Win8 packaged apps, due to additional security restrictions:"," // http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences",""," var supported = false,"," doc = Y.config.doc,"," p;",""," if (doc) {",""," p = doc.createElement(\"p\");"," p.setAttribute(\"onbeforeactivate\", \";\");",""," // onbeforeactivate is a function in IE8+."," // onbeforeactivate is a string in IE6,7 (unfortunate, otherwise we could have just checked for function below)."," // onbeforeactivate is a function in IE10, in a Win8 App environment (no exception running the test).",""," // onbeforeactivate is undefined in Webkit/Gecko."," // onbeforeactivate is a function in Webkit/Gecko if it's a supported event (e.g. onclick).",""," supported = (p.onbeforeactivate !== undefined);"," }",""," return supported;"," }());","","function define(type, proxy, directEvent) {"," var nodeDataKey = '_' + type + 'Notifiers';",""," Y.Event.define(type, {",""," _useActivate : useActivate,",""," _attach: function (el, notifier, delegate) {"," if (Y.DOM.isWindow(el)) {"," return Event._attach([type, function (e) {"," notifier.fire(e);"," }, el]);"," } else {"," return Event._attach("," [proxy, this._proxy, el, this, notifier, delegate],"," { capture: true });"," }"," },",""," _proxy: function (e, notifier, delegate) {"," var target = e.target,"," currentTarget = e.currentTarget,"," notifiers = target.getData(nodeDataKey),"," yuid = Y.stamp(currentTarget._node),"," defer = (useActivate || target !== currentTarget),"," directSub;",""," notifier.currentTarget = (delegate) ? target : currentTarget;"," notifier.container = (delegate) ? currentTarget : null;",""," // Maintain a list to handle subscriptions from nested"," // containers div#a>div#b>input #a.on(focus..) #b.on(focus..),"," // use one focus or blur subscription that fires notifiers from"," // #b then #a to emulate bubble sequence."," if (!notifiers) {"," notifiers = {};"," target.setData(nodeDataKey, notifiers);",""," // only subscribe to the element's focus if the target is"," // not the current target ("," if (defer) {"," directSub = Event._attach("," [directEvent, this._notify, target._node]).sub;"," directSub.once = true;"," }"," } else {"," // In old IE, defer is always true. In capture-phase browsers,"," // The delegate subscriptions will be encountered first, which"," // will establish the notifiers data and direct subscription"," // on the node. If there is also a direct subscription to the"," // node's focus/blur, it should not call _notify because the"," // direct subscription from the delegate sub(s) exists, which"," // will call _notify. So this avoids _notify being called"," // twice, unnecessarily."," defer = true;"," }",""," if (!notifiers[yuid]) {"," notifiers[yuid] = [];"," }",""," notifiers[yuid].push(notifier);",""," if (!defer) {"," this._notify(e);"," }"," },",""," _notify: function (e, container) {"," var currentTarget = e.currentTarget,"," notifierData = currentTarget.getData(nodeDataKey),"," axisNodes = currentTarget.ancestors(),"," doc = currentTarget.get('ownerDocument'),"," delegates = [],"," // Used to escape loops when there are no more"," // notifiers to consider"," count = notifierData ?"," Y.Object.keys(notifierData).length :"," 0,"," target, notifiers, notifier, yuid, match, tmp, i, len, sub, ret;",""," // clear the notifications list (mainly for delegation)"," currentTarget.clearData(nodeDataKey);",""," // Order the delegate subs by their placement in the parent axis"," axisNodes.push(currentTarget);"," // document.get('ownerDocument') returns null"," // which we'll use to prevent having duplicate Nodes in the list"," if (doc) {"," axisNodes.unshift(doc);"," }",""," // ancestors() returns the Nodes from top to bottom"," axisNodes._nodes.reverse();",""," if (count) {"," // Store the count for step 2"," tmp = count;"," axisNodes.some(function (node) {"," var yuid = Y.stamp(node),"," notifiers = notifierData[yuid],"," i, len;",""," if (notifiers) {"," count--;"," for (i = 0, len = notifiers.length; i < len; ++i) {"," if (notifiers[i].handle.sub.filter) {"," delegates.push(notifiers[i]);"," }"," }"," }",""," return !count;"," });"," count = tmp;"," }",""," // Walk up the parent axis, notifying direct subscriptions and"," // testing delegate filters."," while (count && (target = axisNodes.shift())) {"," yuid = Y.stamp(target);",""," notifiers = notifierData[yuid];",""," if (notifiers) {"," for (i = 0, len = notifiers.length; i < len; ++i) {"," notifier = notifiers[i];"," sub = notifier.handle.sub;"," match = true;",""," e.currentTarget = target;",""," if (sub.filter) {"," match = sub.filter.apply(target,"," [target, e].concat(sub.args || []));",""," // No longer necessary to test against this"," // delegate subscription for the nodes along"," // the parent axis."," delegates.splice("," arrayIndex(delegates, notifier), 1);"," }",""," if (match) {"," // undefined for direct subs"," e.container = notifier.container;"," ret = notifier.fire(e);"," }",""," if (ret === false || e.stopped === 2) {"," break;"," }"," }",""," delete notifiers[yuid];"," count--;"," }",""," if (e.stopped !== 2) {"," // delegates come after subs targeting this specific node"," // because they would not normally report until they'd"," // bubbled to the container node."," for (i = 0, len = delegates.length; i < len; ++i) {"," notifier = delegates[i];"," sub = notifier.handle.sub;",""," if (sub.filter.apply(target,"," [target, e].concat(sub.args || []))) {",""," e.container = notifier.container;"," e.currentTarget = target;"," ret = notifier.fire(e);"," }",""," if (ret === false || e.stopped === 2) {"," break;"," }"," }"," }",""," if (e.stopped) {"," break;"," }"," }"," },",""," on: function (node, sub, notifier) {"," sub.handle = this._attach(node._node, notifier);"," },",""," detach: function (node, sub) {"," sub.handle.detach();"," },",""," delegate: function (node, sub, notifier, filter) {"," if (isString(filter)) {"," sub.filter = function (target) {"," return Y.Selector.test(target._node, filter,"," node === target ? null : node._node);"," };"," }",""," sub.handle = this._attach(node._node, notifier, true);"," },",""," detachDelegate: function (node, sub) {"," sub.handle.detach();"," }"," }, true);","}","","// For IE, we need to defer to focusin rather than focus because","// `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate,","// el.onfocusin, doSomething, then el.onfocus. All others support capture","// phase focus, which executes before doSomething. To guarantee consistent","// behavior for this use case, IE's direct subscriptions are made against","// focusin so subscribers will be notified before js following el.focus() is","// executed.","if (useActivate) {"," // name capture phase direct subscription"," define(\"focus\", \"beforeactivate\", \"focusin\");"," define(\"blur\", \"beforedeactivate\", \"focusout\");","} else {"," define(\"focus\", \"focus\", \"focus\");"," define(\"blur\", \"blur\", \"blur\");","}","","","}, '@VERSION@', {\"requires\": [\"event-synthetic\"]});","","}());"]}; } var __cov_6QPN5D0gRV5cd0sDuZmrgw = __coverage__['build/event-focus/event-focus.js']; __cov_6QPN5D0gRV5cd0sDuZmrgw.s['1']++;YUI.add('event-focus',function(Y,NAME){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['1']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['2']++;var Event=Y.Event,YLang=Y.Lang,isString=YLang.isString,arrayIndex=Y.Array.indexOf,useActivate=function(){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['2']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['3']++;var supported=false,doc=Y.config.doc,p;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['4']++;if(doc){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['1'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['5']++;p=doc.createElement('p');__cov_6QPN5D0gRV5cd0sDuZmrgw.s['6']++;p.setAttribute('onbeforeactivate',';');__cov_6QPN5D0gRV5cd0sDuZmrgw.s['7']++;supported=p.onbeforeactivate!==undefined;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['1'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['8']++;return supported;}();__cov_6QPN5D0gRV5cd0sDuZmrgw.s['9']++;function define(type,proxy,directEvent){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['3']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['10']++;var nodeDataKey='_'+type+'Notifiers';__cov_6QPN5D0gRV5cd0sDuZmrgw.s['11']++;Y.Event.define(type,{_useActivate:useActivate,_attach:function(el,notifier,delegate){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['4']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['12']++;if(Y.DOM.isWindow(el)){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['2'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['13']++;return Event._attach([type,function(e){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['5']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['14']++;notifier.fire(e);},el]);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['2'][1]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['15']++;return Event._attach([proxy,this._proxy,el,this,notifier,delegate],{capture:true});}},_proxy:function(e,notifier,delegate){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['6']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['16']++;var target=e.target,currentTarget=e.currentTarget,notifiers=target.getData(nodeDataKey),yuid=Y.stamp(currentTarget._node),defer=(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['3'][0]++,useActivate)||(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['3'][1]++,target!==currentTarget),directSub;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['17']++;notifier.currentTarget=delegate?(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['4'][0]++,target):(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['4'][1]++,currentTarget);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['18']++;notifier.container=delegate?(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['5'][0]++,currentTarget):(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['5'][1]++,null);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['19']++;if(!notifiers){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['6'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['20']++;notifiers={};__cov_6QPN5D0gRV5cd0sDuZmrgw.s['21']++;target.setData(nodeDataKey,notifiers);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['22']++;if(defer){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['7'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['23']++;directSub=Event._attach([directEvent,this._notify,target._node]).sub;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['24']++;directSub.once=true;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['7'][1]++;}}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['6'][1]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['25']++;defer=true;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['26']++;if(!notifiers[yuid]){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['8'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['27']++;notifiers[yuid]=[];}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['8'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['28']++;notifiers[yuid].push(notifier);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['29']++;if(!defer){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['9'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['30']++;this._notify(e);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['9'][1]++;}},_notify:function(e,container){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['7']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['31']++;var currentTarget=e.currentTarget,notifierData=currentTarget.getData(nodeDataKey),axisNodes=currentTarget.ancestors(),doc=currentTarget.get('ownerDocument'),delegates=[],count=notifierData?(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['10'][0]++,Y.Object.keys(notifierData).length):(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['10'][1]++,0),target,notifiers,notifier,yuid,match,tmp,i,len,sub,ret;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['32']++;currentTarget.clearData(nodeDataKey);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['33']++;axisNodes.push(currentTarget);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['34']++;if(doc){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['11'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['35']++;axisNodes.unshift(doc);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['11'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['36']++;axisNodes._nodes.reverse();__cov_6QPN5D0gRV5cd0sDuZmrgw.s['37']++;if(count){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['12'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['38']++;tmp=count;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['39']++;axisNodes.some(function(node){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['8']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['40']++;var yuid=Y.stamp(node),notifiers=notifierData[yuid],i,len;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['41']++;if(notifiers){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['13'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['42']++;count--;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['43']++;for(i=0,len=notifiers.length;i<len;++i){__cov_6QPN5D0gRV5cd0sDuZmrgw.s['44']++;if(notifiers[i].handle.sub.filter){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['14'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['45']++;delegates.push(notifiers[i]);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['14'][1]++;}}}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['13'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['46']++;return!count;});__cov_6QPN5D0gRV5cd0sDuZmrgw.s['47']++;count=tmp;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['12'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['48']++;while((__cov_6QPN5D0gRV5cd0sDuZmrgw.b['15'][0]++,count)&&(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['15'][1]++,target=axisNodes.shift())){__cov_6QPN5D0gRV5cd0sDuZmrgw.s['49']++;yuid=Y.stamp(target);__cov_6QPN5D0gRV5cd0sDuZmrgw.s['50']++;notifiers=notifierData[yuid];__cov_6QPN5D0gRV5cd0sDuZmrgw.s['51']++;if(notifiers){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['16'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['52']++;for(i=0,len=notifiers.length;i<len;++i){__cov_6QPN5D0gRV5cd0sDuZmrgw.s['53']++;notifier=notifiers[i];__cov_6QPN5D0gRV5cd0sDuZmrgw.s['54']++;sub=notifier.handle.sub;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['55']++;match=true;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['56']++;e.currentTarget=target;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['57']++;if(sub.filter){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['17'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['58']++;match=sub.filter.apply(target,[target,e].concat((__cov_6QPN5D0gRV5cd0sDuZmrgw.b['18'][0]++,sub.args)||(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['18'][1]++,[])));__cov_6QPN5D0gRV5cd0sDuZmrgw.s['59']++;delegates.splice(arrayIndex(delegates,notifier),1);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['17'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['60']++;if(match){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['19'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['61']++;e.container=notifier.container;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['62']++;ret=notifier.fire(e);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['19'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['63']++;if((__cov_6QPN5D0gRV5cd0sDuZmrgw.b['21'][0]++,ret===false)||(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['21'][1]++,e.stopped===2)){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['20'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['64']++;break;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['20'][1]++;}}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['65']++;delete notifiers[yuid];__cov_6QPN5D0gRV5cd0sDuZmrgw.s['66']++;count--;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['16'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['67']++;if(e.stopped!==2){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['22'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['68']++;for(i=0,len=delegates.length;i<len;++i){__cov_6QPN5D0gRV5cd0sDuZmrgw.s['69']++;notifier=delegates[i];__cov_6QPN5D0gRV5cd0sDuZmrgw.s['70']++;sub=notifier.handle.sub;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['71']++;if(sub.filter.apply(target,[target,e].concat((__cov_6QPN5D0gRV5cd0sDuZmrgw.b['24'][0]++,sub.args)||(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['24'][1]++,[])))){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['23'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['72']++;e.container=notifier.container;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['73']++;e.currentTarget=target;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['74']++;ret=notifier.fire(e);}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['23'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['75']++;if((__cov_6QPN5D0gRV5cd0sDuZmrgw.b['26'][0]++,ret===false)||(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['26'][1]++,e.stopped===2)){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['25'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['76']++;break;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['25'][1]++;}}}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['22'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['77']++;if(e.stopped){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['27'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['78']++;break;}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['27'][1]++;}}},on:function(node,sub,notifier){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['9']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['79']++;sub.handle=this._attach(node._node,notifier);},detach:function(node,sub){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['10']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['80']++;sub.handle.detach();},delegate:function(node,sub,notifier,filter){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['11']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['81']++;if(isString(filter)){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['28'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['82']++;sub.filter=function(target){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['12']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['83']++;return Y.Selector.test(target._node,filter,node===target?(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['29'][0]++,null):(__cov_6QPN5D0gRV5cd0sDuZmrgw.b['29'][1]++,node._node));};}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['28'][1]++;}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['84']++;sub.handle=this._attach(node._node,notifier,true);},detachDelegate:function(node,sub){__cov_6QPN5D0gRV5cd0sDuZmrgw.f['13']++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['85']++;sub.handle.detach();}},true);}__cov_6QPN5D0gRV5cd0sDuZmrgw.s['86']++;if(useActivate){__cov_6QPN5D0gRV5cd0sDuZmrgw.b['30'][0]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['87']++;define('focus','beforeactivate','focusin');__cov_6QPN5D0gRV5cd0sDuZmrgw.s['88']++;define('blur','beforedeactivate','focusout');}else{__cov_6QPN5D0gRV5cd0sDuZmrgw.b['30'][1]++;__cov_6QPN5D0gRV5cd0sDuZmrgw.s['89']++;define('focus','focus','focus');__cov_6QPN5D0gRV5cd0sDuZmrgw.s['90']++;define('blur','blur','blur');}},'@VERSION@',{'requires':['event-synthetic']});
lib/option.js
ghiden/react-autocomplete
var React = require('react'); var addClass = require('./add-class'); module.exports = React.createClass({ propTypes: { /** * The value that will be send to the `onSelect` handler of the * parent Combobox. */ value: React.PropTypes.any.isRequired, /** * What value to put into the input element when this option is * selected, defaults to its children coerced to a string. */ label: React.PropTypes.string }, getDefaultProps: function() { return { role: 'option', tabIndex: '-1', className: 'rf-combobox-option', isSelected: false }; }, render: function() { var props = this.props; if (props.isSelected) props.className = addClass(props.className, 'rf-combobox-selected'); return React.DOM.div(props); } });
lib/yuilib/3.17.2/event-focus/event-focus-min.js
cdsmith-umn/moodle
/* YUI 3.17.2 (build 9c3c78e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add("event-focus",function(e,t){function u(t,r,u){var a="_"+t+"Notifiers";e.Event.define(t,{_useActivate:o,_attach:function(i,s,o){return e.DOM.isWindow(i)?n._attach([t,function(e){s.fire(e)},i]):n._attach([r,this._proxy,i,this,s,o],{capture:!0})},_proxy:function(t,r,i){var s=t.target,f=t.currentTarget,l=s.getData(a),c=e.stamp(f._node),h=o||s!==f,p;r.currentTarget=i?s:f,r.container=i?f:null,l?h=!0:(l={},s.setData(a,l),h&&(p=n._attach([u,this._notify,s._node]).sub,p.once=!0)),l[c]||(l[c]=[]),l[c].push(r),h||this._notify(t)},_notify:function(t,n){var r=t.currentTarget,i=r.getData(a),o=r.ancestors(),u=r.get("ownerDocument"),f=[],l=i?e.Object.keys(i).length:0,c,h,p,d,v,m,g,y,b,w;r.clearData(a),o.push(r),u&&o.unshift(u),o._nodes.reverse(),l&&(m=l,o.some(function(t){var n=e.stamp(t),r=i[n],s,o;if(r){l--;for(s=0,o=r.length;s<o;++s)r[s].handle.sub.filter&&f.push(r[s])}return!l}),l=m);while(l&&(c=o.shift())){d=e.stamp(c),h=i[d];if(h){for(g=0,y=h.length;g<y;++g){p=h[g],b=p.handle.sub,v=!0,t.currentTarget=c,b.filter&&(v=b.filter.apply(c,[c,t].concat(b.args||[])),f.splice(s(f,p),1)),v&&(t.container=p.container,w=p.fire(t));if(w===!1||t.stopped===2)break}delete h[d],l--}if(t.stopped!==2)for(g=0,y=f.length;g<y;++g){p=f[g],b=p.handle.sub,b.filter.apply(c,[c,t].concat(b.args||[]))&&(t.container=p.container,t.currentTarget=c,w=p.fire(t));if(w===!1||t.stopped===2||t.stopped&&f[g+1]&&f[g+1].container!==p.container)break}if(t.stopped)break}},on:function(e,t,n){t.handle=this._attach(e._node,n)},detach:function(e,t){t.handle.detach()},delegate:function(t,n,r,s){i(s)&&(n.filter=function(n){return e.Selector.test(n._node,s,t===n?null:t._node)}),n.handle=this._attach(t._node,r,!0)},detachDelegate:function(e,t){t.handle.detach()}},!0)}var n=e.Event,r=e.Lang,i=r.isString,s=e.Array.indexOf,o=function(){var t=!1,n=e.config.doc,r;return n&&(r=n.createElement("p"),r.setAttribute("onbeforeactivate",";"),t=r.onbeforeactivate!==undefined),t}();o?(u("focus","beforeactivate","focusin"),u("blur","beforedeactivate","focusout")):(u("focus","focus","focus"),u("blur","blur","blur"))},"3.17.2",{requires:["event-synthetic"]});
src/routes/stock-correlation/components/stock-correlation-input.js
ArcQ/stocks-on-stats
import React, { PropTypes } from 'react'; import { Button, section, DatePicker } from 'react-toolbox'; import TagsInput from 'react-tagsinput'; import 'react-tagsinput/react-tagsinput.css'; import './stock-correlation.scss'; // TODO when user goes beyond 1 year on date picker, show dialog alerting user of limitation export const StockCorrelationInput = props => ( <div> <TagsInput value={props.taggedStocks} addKeys={props.keyCodesForAdd} onChange={props.handleTagInput} inputProps={{ className: 'react-tagsinput-input', placeholder: 'eg. GOOG;AAPL;AMZN;', }} onlyUnique /> <section> <DatePicker label='Start Date' onChange={props.handleStartDateInput} value={props.interval.startDate} minDate={props.interval.min} maxDate={props.interval.max} sundayFirstDayOfWeek /> <DatePicker label='End Date' onChange={props.handleEndDateInput} value={props.interval.endDate} minDate={props.interval.min} maxDate={props.interval.max} sundayFirstDayOfWeek /> </section> <Button className='btn btn-default' onClick={() => props.makeCalc(props.getFormattedInterval(), ...props.taggedStocks)} raised primary > Calculate </Button> </div> ); StockCorrelationInput.propTypes = { keyCodesForAdd: PropTypes.arrayOf(PropTypes.number), taggedStocks: PropTypes.arrayOf(PropTypes.string).isRequired, interval: PropTypes.shape({ startDate: PropTypes.instanceOf(Date).isRequired, endDate: PropTypes.instanceOf(Date).isRequired, min: PropTypes.instanceOf(Date).isRequired, max: PropTypes.instanceOf(Date).isRequired, }).isRequired, handleStartDateInput: PropTypes.func.isRequired, handleEndDateInput: PropTypes.func.isRequired, handleTagInput: PropTypes.func.isRequired, makeCalc: PropTypes.func.isRequired, getFormattedInterval: PropTypes.func.isRequired, }; export default StockCorrelationInput;
src/client/components/Comments/HiddenCommentMessage.js
busyorg/busy
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; const HiddenCommentMessage = ({ onClick }) => ( <div className="Comment__hidden__message Body"> <FormattedMessage id="comment_hidden_message" defaultMessage="This comment is currently hidden due to the author's low reputation or low comment rating." /> <br /> <a role="presentation" onClick={onClick}> <FormattedMessage id="reveal_comment" defaultMessage="Reveal comment" /> </a> </div> ); HiddenCommentMessage.propTypes = { onClick: PropTypes.func, }; HiddenCommentMessage.defaultProps = { onClick: () => {}, }; export default HiddenCommentMessage;
packages/generator-electron/template/__tests__/renderer/components/App.js
abouthiroppy/dish
import React from 'react'; import { shallow } from 'enzyme'; import App from '../../../src/renderer/components/App'; describe('Label component', () => { const createDOM = (props = {}) => shallow(<App {...props} />); it('should render self and subcomponents', () => { const wrapper = createDOM(); expect(wrapper).toMatchSnapshot(); }); it('should render children', () => { const wrapper = createDOM({ children: <h1>hello</h1> }); expect(wrapper).toMatchSnapshot(); }); });
ajax/libs/material-ui/4.10.1/es/SvgIcon/SvgIcon.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import capitalize from '../utils/capitalize'; export const styles = theme => ({ /* Styles applied to the root element. */ root: { userSelect: 'none', width: '1em', height: '1em', display: 'inline-block', fill: 'currentColor', flexShrink: 0, fontSize: theme.typography.pxToRem(24), transition: theme.transitions.create('fill', { duration: theme.transitions.duration.shorter }) }, /* Styles applied to the root element if `color="primary"`. */ colorPrimary: { color: theme.palette.primary.main }, /* Styles applied to the root element if `color="secondary"`. */ colorSecondary: { color: theme.palette.secondary.main }, /* Styles applied to the root element if `color="action"`. */ colorAction: { color: theme.palette.action.active }, /* Styles applied to the root element if `color="error"`. */ colorError: { color: theme.palette.error.main }, /* Styles applied to the root element if `color="disabled"`. */ colorDisabled: { color: theme.palette.action.disabled }, /* Styles applied to the root element if `fontSize="inherit"`. */ fontSizeInherit: { fontSize: 'inherit' }, /* Styles applied to the root element if `fontSize="small"`. */ fontSizeSmall: { fontSize: theme.typography.pxToRem(20) }, /* Styles applied to the root element if `fontSize="large"`. */ fontSizeLarge: { fontSize: theme.typography.pxToRem(35) } }); const SvgIcon = React.forwardRef(function SvgIcon(props, ref) { const { children, classes, className, color = 'inherit', component: Component = 'svg', fontSize = 'default', htmlColor, titleAccess, viewBox = '0 0 24 24' } = props, other = _objectWithoutPropertiesLoose(props, ["children", "classes", "className", "color", "component", "fontSize", "htmlColor", "titleAccess", "viewBox"]); return /*#__PURE__*/React.createElement(Component, _extends({ className: clsx(classes.root, className, color !== 'inherit' && classes[`color${capitalize(color)}`], fontSize !== 'default' && classes[`fontSize${capitalize(fontSize)}`]), focusable: "false", viewBox: viewBox, color: htmlColor, "aria-hidden": titleAccess ? undefined : true, role: titleAccess ? 'img' : undefined, ref: ref }, other), children, titleAccess ? /*#__PURE__*/React.createElement("title", null, titleAccess) : null); }); process.env.NODE_ENV !== "production" ? SvgIcon.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * Node passed into the SVG element. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The color of the component. It supports those theme colors that make sense for this component. * You can use the `htmlColor` prop to apply a color attribute to the SVG element. */ color: PropTypes.oneOf(['action', 'disabled', 'error', 'inherit', 'primary', 'secondary']), /** * The component used for the root node. * Either a string to use a HTML element or a component. */ component: PropTypes.elementType, /** * The fontSize applied to the icon. Defaults to 24px, but can be configure to inherit font size. */ fontSize: PropTypes.oneOf(['default', 'inherit', 'large', 'small']), /** * Applies a color attribute to the SVG element. */ htmlColor: PropTypes.string, /** * The shape-rendering attribute. The behavior of the different options is described on the * [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/shape-rendering). * If you are having issues with blurry icons you should investigate this property. */ shapeRendering: PropTypes.string, /** * Provides a human-readable title for the element that contains it. * https://www.w3.org/TR/SVG-access/#Equivalent */ titleAccess: PropTypes.string, /** * Allows you to redefine what the coordinates without units mean inside an SVG element. * For example, if the SVG element is 500 (width) by 200 (height), * and you pass viewBox="0 0 50 20", * this means that the coordinates inside the SVG will go from the top left corner (0,0) * to bottom right (50,20) and each unit will be worth 10px. */ viewBox: PropTypes.string } : void 0; SvgIcon.muiName = 'SvgIcon'; export default withStyles(styles, { name: 'MuiSvgIcon' })(SvgIcon);
src/web/client/src/components/shared/modal.js
devmynd/cloud-access-manager
import React from 'react' export default class Modal extends React.Component { componentDidMount = () => { this.props.onMounted && this.props.onMounted() } render () { return ( <div className='modal is-active'> <div className='modal-background' onClick={this.props.closeHandler} /> <div className='modal-card'> <header className='modal-card-head'> <p className='modal-card-title'>{this.props.title}</p> <button className='delete' onClick={this.props.closeHandler} /> </header> <section className='modal-card-body'> {this.props.children} </section> </div> </div> ) } }
senic_hub/frontend/src/index.js
grunskis/senic-hub
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
app/javascript/mastodon/features/generic_not_found/index.js
Ryanaka/mastodon
import React from 'react'; import Column from '../ui/components/column'; import MissingIndicator from '../../components/missing_indicator'; const GenericNotFound = () => ( <Column> <MissingIndicator fullPage /> </Column> ); export default GenericNotFound;
packages/mui-icons-material/lib/esm/Vrpano.js
oliviertassinari/material-ui
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M20.69 4.05C18.66 4.73 15.86 5.5 12 5.5c-3.89 0-6.95-.84-8.69-1.43-.64-.22-1.31.26-1.31.95V19c0 .68.66 1.17 1.31.95C5.36 19.26 8.1 18.5 12 18.5c3.87 0 6.66.76 8.69 1.45.65.21 1.31-.27 1.31-.95V5c0-.68-.66-1.16-1.31-.95zM12 15c-2.34 0-4.52.15-6.52.41l3.69-4.42 2 2.4L14 10l4.51 5.4c-1.99-.25-4.21-.4-6.51-.4z" }), 'Vrpano');
src/routes/about/index.js
ADourgarian/Syscoin-Payroll
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Layout from '../../components/Layout'; import Page from '../../components/Page'; export default { path: '/about', async action() { const data = await require.ensure([], require => require('./about.md'), 'about'); return { title: data.title, component: <Layout><Page {...data} /></Layout>, }; }, };
src/scenes/home/header/topNav/topNav.js
tskuse/operationcode_frontend
import React from 'react'; import PropTypes from 'prop-types'; import styles from './topNav.css'; const TopNav = ({ children }) => ( <div className={styles.topNav} > {children} </div> ); TopNav.propTypes = { children: PropTypes.node.isRequired }; export default TopNav;
src/Row.js
Lucifier129/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import elementType from 'react-prop-types/lib/elementType'; const Row = React.createClass({ propTypes: { /** * You can use a custom element for this component */ componentClass: elementType }, getDefaultProps() { return { componentClass: 'div' }; }, render() { let ComponentClass = this.props.componentClass; return ( <ComponentClass {...this.props} className={classNames(this.props.className, 'row')}> {this.props.children} </ComponentClass> ); } }); export default Row;
protocol-designer/src/steplist/formLevel/errors.js
Opentrons/labware
// @flow import * as React from 'react' import { getWellRatio } from '../utils' import { canPipetteUseLabware } from '../../utils' import { MAGNETIC_MODULE_V1, MAGNETIC_MODULE_V2 } from '@opentrons/shared-data' import { MIN_ENGAGE_HEIGHT_V1, MAX_ENGAGE_HEIGHT_V1, MIN_ENGAGE_HEIGHT_V2, MAX_ENGAGE_HEIGHT_V2, PAUSE_UNTIL_RESUME, PAUSE_UNTIL_TIME, PAUSE_UNTIL_TEMP, THERMOCYCLER_PROFILE, } from '../../constants' import type { StepFieldName } from '../../form-types' /******************* ** Error Messages ** ********************/ export type FormErrorKey = | 'INCOMPATIBLE_ASPIRATE_LABWARE' | 'INCOMPATIBLE_DISPENSE_LABWARE' | 'INCOMPATIBLE_LABWARE' | 'WELL_RATIO_MOVE_LIQUID' | 'PAUSE_TYPE_REQUIRED' | 'TIME_PARAM_REQUIRED' | 'PAUSE_TEMP_PARAM_REQUIRED' | 'MAGNET_ACTION_TYPE_REQUIRED' | 'ENGAGE_HEIGHT_MIN_EXCEEDED' | 'ENGAGE_HEIGHT_MAX_EXCEEDED' | 'ENGAGE_HEIGHT_REQUIRED' | 'MODULE_ID_REQUIRED' | 'TARGET_TEMPERATURE_REQUIRED' | 'BLOCK_TEMPERATURE_REQUIRED' | 'LID_TEMPERATURE_REQUIRED' | 'PROFILE_VOLUME_REQUIRED' | 'PROFILE_LID_TEMPERATURE_REQUIRED' | 'BLOCK_TEMPERATURE_HOLD_REQUIRED' | 'LID_TEMPERATURE_HOLD_REQUIRED' export type FormError = { title: string, body?: React.Node, dependentFields: Array<StepFieldName>, } const FORM_ERRORS: { [FormErrorKey]: FormError } = { INCOMPATIBLE_ASPIRATE_LABWARE: { title: 'Selected aspirate labware is incompatible with selected pipette', dependentFields: ['aspirate_labware', 'pipette'], }, INCOMPATIBLE_DISPENSE_LABWARE: { title: 'Selected dispense labware is incompatible with selected pipette', dependentFields: ['dispense_labware', 'pipette'], }, INCOMPATIBLE_LABWARE: { title: 'Selected labware is incompatible with selected pipette', dependentFields: ['labware', 'pipette'], }, PAUSE_TYPE_REQUIRED: { title: 'Must either pause for amount of time, until told to resume, or until temperature reached', dependentFields: ['pauseAction'], }, TIME_PARAM_REQUIRED: { title: 'Must include hours, minutes, or seconds', dependentFields: ['pauseAction', 'pauseHour', 'pauseMinute', 'pauseSecond'], }, PAUSE_TEMP_PARAM_REQUIRED: { title: 'Temperature is required', dependentFields: ['pauseAction', 'pauseTemperature'], }, WELL_RATIO_MOVE_LIQUID: { title: 'Well selection must be 1 to many, many to 1, or N to N', dependentFields: ['aspirate_wells', 'dispense_wells'], }, MAGNET_ACTION_TYPE_REQUIRED: { title: 'Action type must be either engage or disengage', dependentFields: ['magnetAction'], }, ENGAGE_HEIGHT_REQUIRED: { title: 'Engage height is required', dependentFields: ['magnetAction', 'engageHeight'], }, ENGAGE_HEIGHT_MIN_EXCEEDED: { title: 'Specified distance is below module minimum', dependentFields: ['magnetAction', 'engageHeight'], }, ENGAGE_HEIGHT_MAX_EXCEEDED: { title: 'Specified distance is above module maximum', dependentFields: ['magnetAction', 'engageHeight'], }, MODULE_ID_REQUIRED: { title: 'Module is required. Ensure the appropriate module is present on the deck and selected for this step', dependentFields: ['moduleId'], }, TARGET_TEMPERATURE_REQUIRED: { title: 'Temperature is required', dependentFields: ['setTemperature', 'targetTemperature'], }, PROFILE_VOLUME_REQUIRED: { title: 'Volume is required', dependentFields: ['thermocyclerFormType', 'profileVolume'], }, PROFILE_LID_TEMPERATURE_REQUIRED: { title: 'Temperature is required', dependentFields: ['thermocyclerFormType', 'profileTargetLidTemp'], }, LID_TEMPERATURE_REQUIRED: { title: 'Temperature is required', dependentFields: ['lidIsActive', 'lidTargetTemp'], }, BLOCK_TEMPERATURE_REQUIRED: { title: 'Temperature is required', dependentFields: ['blockIsActive', 'blockTargetTemp'], }, BLOCK_TEMPERATURE_HOLD_REQUIRED: { title: 'Temperature is required', dependentFields: ['blockIsActiveHold', 'blockTargetTempHold'], }, LID_TEMPERATURE_HOLD_REQUIRED: { title: 'Temperature is required', dependentFields: ['lidIsActiveHold', 'lidTargetTempHold'], }, } export type FormErrorChecker = mixed => ?FormError // TODO: test these /******************* ** Error Checkers ** ********************/ // TODO: real HydratedFormData type type HydratedFormData = any export const incompatibleLabware = (fields: HydratedFormData): ?FormError => { const { labware, pipette } = fields if (!labware || !pipette) return null return !canPipetteUseLabware(pipette.spec, labware.def) ? FORM_ERRORS.INCOMPATIBLE_LABWARE : null } export const incompatibleDispenseLabware = ( fields: HydratedFormData ): ?FormError => { const { dispense_labware, pipette } = fields if (!dispense_labware || !pipette) return null return !canPipetteUseLabware(pipette.spec, dispense_labware.def) ? FORM_ERRORS.INCOMPATIBLE_DISPENSE_LABWARE : null } export const incompatibleAspirateLabware = ( fields: HydratedFormData ): ?FormError => { const { aspirate_labware, pipette } = fields if (!aspirate_labware || !pipette) return null return !canPipetteUseLabware(pipette.spec, aspirate_labware.def) ? FORM_ERRORS.INCOMPATIBLE_ASPIRATE_LABWARE : null } export const pauseForTimeOrUntilTold = ( fields: HydratedFormData ): ?FormError => { const { pauseAction, pauseHour, pauseMinute, pauseSecond, moduleId, pauseTemperature, } = fields if (pauseAction === PAUSE_UNTIL_TIME) { // user selected pause for amount of time const hours = parseFloat(pauseHour) || 0 const minutes = parseFloat(pauseMinute) || 0 const seconds = parseFloat(pauseSecond) || 0 const totalSeconds = hours * 3600 + minutes * 60 + seconds return totalSeconds <= 0 ? FORM_ERRORS.TIME_PARAM_REQUIRED : null } else if (pauseAction === PAUSE_UNTIL_TEMP) { // user selected pause until temperature reached if (moduleId == null) { // missing module field (reached by deleting a module from deck) return FORM_ERRORS.MODULE_ID_REQUIRED } if (!pauseTemperature) { // missing temperature field return FORM_ERRORS.PAUSE_TEMP_PARAM_REQUIRED } return null } else if (pauseAction === PAUSE_UNTIL_RESUME) { // user selected pause until resume return null } else { // user did not select a pause type return FORM_ERRORS.PAUSE_TYPE_REQUIRED } } export const wellRatioMoveLiquid = ( fields: HydratedFormData ): FormError | null => { const { aspirate_wells, dispense_wells } = fields if (!aspirate_wells || !dispense_wells) return null return getWellRatio(aspirate_wells, dispense_wells) ? null : FORM_ERRORS.WELL_RATIO_MOVE_LIQUID } export const magnetActionRequired = ( fields: HydratedFormData ): FormError | null => { const { magnetAction } = fields if (!magnetAction) return FORM_ERRORS.MAGNET_ACTION_TYPE_REQUIRED return null } export const engageHeightRequired = ( fields: HydratedFormData ): FormError | null => { const { magnetAction, engageHeight } = fields return magnetAction === 'engage' && !engageHeight ? FORM_ERRORS.ENGAGE_HEIGHT_REQUIRED : null } export const moduleIdRequired = ( fields: HydratedFormData ): FormError | null => { const { moduleId } = fields if (moduleId == null) return FORM_ERRORS.MODULE_ID_REQUIRED return null } export const targetTemperatureRequired = ( fields: HydratedFormData ): FormError | null => { const { setTemperature, targetTemperature } = fields return setTemperature === 'true' && !targetTemperature ? FORM_ERRORS.TARGET_TEMPERATURE_REQUIRED : null } export const profileVolumeRequired = ( fields: HydratedFormData ): FormError | null => { const { thermocyclerFormType, profileVolume } = fields return thermocyclerFormType === THERMOCYCLER_PROFILE && !profileVolume ? FORM_ERRORS.PROFILE_VOLUME_REQUIRED : null } export const profileTargetLidTempRequired = ( fields: HydratedFormData ): FormError | null => { const { thermocyclerFormType, profileTargetLidTemp } = fields return thermocyclerFormType === THERMOCYCLER_PROFILE && !profileTargetLidTemp ? FORM_ERRORS.PROFILE_LID_TEMPERATURE_REQUIRED : null } export const blockTemperatureRequired = ( fields: HydratedFormData ): FormError | null => { const { blockIsActive, blockTargetTemp } = fields return blockIsActive === true && !blockTargetTemp ? FORM_ERRORS.BLOCK_TEMPERATURE_REQUIRED : null } export const lidTemperatureRequired = ( fields: HydratedFormData ): FormError | null => { const { lidIsActive, lidTargetTemp } = fields return lidIsActive === true && !lidTargetTemp ? FORM_ERRORS.LID_TEMPERATURE_REQUIRED : null } export const blockTemperatureHoldRequired = ( fields: HydratedFormData ): FormError | null => { const { blockIsActiveHold, blockTargetTempHold } = fields return blockIsActiveHold === true && !blockTargetTempHold ? FORM_ERRORS.BLOCK_TEMPERATURE_HOLD_REQUIRED : null } export const lidTemperatureHoldRequired = ( fields: HydratedFormData ): FormError | null => { const { lidIsActiveHold, lidTargetTempHold } = fields return lidIsActiveHold === true && !lidTargetTempHold ? FORM_ERRORS.LID_TEMPERATURE_HOLD_REQUIRED : null } export const engageHeightRangeExceeded = ( fields: HydratedFormData ): FormError | null => { const { magnetAction, engageHeight } = fields const moduleEntity = fields.meta?.module const model = moduleEntity?.model if (magnetAction === 'engage') { if (model === MAGNETIC_MODULE_V1) { if (engageHeight < MIN_ENGAGE_HEIGHT_V1) { return FORM_ERRORS.ENGAGE_HEIGHT_MIN_EXCEEDED } else if (engageHeight > MAX_ENGAGE_HEIGHT_V1) { return FORM_ERRORS.ENGAGE_HEIGHT_MAX_EXCEEDED } } else if (model === MAGNETIC_MODULE_V2) { if (engageHeight < MIN_ENGAGE_HEIGHT_V2) { return FORM_ERRORS.ENGAGE_HEIGHT_MIN_EXCEEDED } else if (engageHeight > MAX_ENGAGE_HEIGHT_V2) { return FORM_ERRORS.ENGAGE_HEIGHT_MAX_EXCEEDED } } else { console.warn(`unhandled model for engageHeightRangeExceeded: ${model}`) } } return null } /******************* ** Helpers ** ********************/ type ComposeErrors = ( ...errorCheckers: Array<FormErrorChecker> ) => mixed => Array<FormError> export const composeErrors: ComposeErrors = ( ...errorCheckers: Array<FormErrorChecker> ) => value => errorCheckers.reduce((acc, errorChecker) => { const possibleError = errorChecker(value) return possibleError ? [...acc, possibleError] : acc }, [])
src/app/components/share-panel-embed-code.js
pashist/soundcloud-like-player
import React from 'react'; export default class SharePanelEmbedCode extends React.Component { render() { if (!this.props.track) return null; return ( <div className="share-link"> <div className="right"> <input type="checkbox" id="embed-code-wordpress" onClick={this.props.toggleWP} checked={this.props.isEmbedCodeWordpress}/> <label htmlFor="embed-code-wordpress">WordPress</label> <button className="share-embed-code-button" onClick={this.props.onClick}>Link</button> </div> <div className="input-wrapper"> <input className="share-link-input" type="text" readOnly="readonly" value={this.buildEmbedCode()}/> </div> </div> ) } buildEmbedCode() { return this.props.isEmbedCodeWordpress ? `[soundcloud url="${this.props.track.uri}" params="color=ff5500" width="100%" height="166" iframe="true" /]` : `<iframe width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=${this.props.track.permalink_url}&amp;color=ff5500"></iframe>` } }
src/index.js
HurricaneJames/react-simple-nav
import React from 'react'; import ReactDOM from 'react-dom' import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
src/svg-icons/action/settings-phone.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsPhone = (props) => ( <SvgIcon {...props}> <path d="M13 9h-2v2h2V9zm4 0h-2v2h2V9zm3 6.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.58l2.2-2.21c.28-.27.36-.66.25-1.01C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 9v2h2V9h-2z"/> </SvgIcon> ); ActionSettingsPhone = pure(ActionSettingsPhone); ActionSettingsPhone.displayName = 'ActionSettingsPhone'; export default ActionSettingsPhone;
ui/src/components/DeviceProfileForm.js
jcampanell-cablelabs/lora-app-server
import React, { Component } from 'react'; import Select from "react-select"; import NetworkServerStore from "../stores/NetworkServerStore"; import SessionStore from "../stores/SessionStore"; class DeviceProfileForm extends Component { static contextTypes = { router: React.PropTypes.object.isRequired }; constructor() { super(); this.state = { deviceProfile: { deviceProfile: {}, }, networkServers: [], update: false, activeTab: "general", isAdmin: false, }; this.handleSubmit = this.handleSubmit.bind(this); this.changeTab = this.changeTab.bind(this); } componentDidMount() { NetworkServerStore.getAllForOrganizationID(this.props.organizationID, 9999, 0, (totalCount, networkServers) => { this.setState({ deviceProfile: this.props.deviceProfile, networkServers: networkServers, isAdmin: SessionStore.isAdmin(), }); }); } componentWillReceiveProps(nextProps) { this.setState({ deviceProfile: nextProps.deviceProfile, update: nextProps.deviceProfile.deviceProfile.deviceProfileID !== undefined, }); } handleSubmit(e) { e.preventDefault(); this.props.onSubmit(this.state.deviceProfile); } onChange(fieldLookup, e) { let lookup = fieldLookup.split("."); const fieldName = lookup[lookup.length-1]; lookup.pop(); // remove last item let deviceProfile = this.state.deviceProfile; let obj = deviceProfile; for (const f of lookup) { obj = obj[f]; } if (fieldName === "factoryPresetFreqsStr") { let freqsStr = e.target.value.split(","); obj[fieldName] = e.target.value; obj["factoryPresetFreqs"] = freqsStr.map((c, i) => parseInt(c, 10)); } else if (e.target.type === "number") { obj[fieldName] = parseInt(e.target.value, 10); } else if (e.target.type === "checkbox") { obj[fieldName] = e.target.checked; } else { obj[fieldName] = e.target.value; } this.setState({ deviceProfile: deviceProfile, }); } onSelectChange(fieldLookup, val) { let lookup = fieldLookup.split("."); const fieldName = lookup[lookup.length-1]; lookup.pop(); // remove last item let deviceProfile = this.state.deviceProfile; let obj = deviceProfile; for (const f of lookup) { obj = obj[f]; } obj[fieldName] = val.value; this.setState({ deviceProfile: deviceProfile, }); } changeTab(e) { e.preventDefault(); this.setState({ activeTab: e.target.getAttribute("aria-controls"), }); } render() { const networkServerOptions = this.state.networkServers.map((networkServer, i) => { return { value: networkServer.id, label: networkServer.name, }; }); const macVersionOptions = [ {value: "1.0.0", label: "1.0.0"}, {value: "1.0.1", label: "1.0.1"}, {value: "1.0.2", label: "1.0.2"}, {value: "1.1.0", label: "1.1.0"}, ]; const regParamsOptions = [ {value: "A", label: "A"}, {value: "B", label: "B"}, ]; return( <div> <ul className="nav nav-tabs"> <li role="presentation" className={(this.state.activeTab === "general" ? "active" : "")}><a onClick={this.changeTab} href="#general" aria-controls="general">General</a></li> <li role="presentation" className={(this.state.activeTab === "join" ? "active" : "")}><a onClick={this.changeTab} href="#join" aria-controls="join">Join (OTAA / ABP)</a></li> <li role="presentation" className={(this.state.activeTab === "classC" ? "active" : "")}><a onClick={this.changeTab} href="#classC" aria-controls="classC">Class-C</a></li> </ul> <hr /> <form onSubmit={this.handleSubmit}> <fieldset disabled={!this.state.isAdmin}> <div className={(this.state.activeTab === "general" ? "" : "hidden")}> <div className="form-group"> <label className="control-label" htmlFor="name">Device-profile name</label> <input className="form-control" id="name" type="text" placeholder="e.g. my device-profile" required value={this.state.deviceProfile.name || ''} onChange={this.onChange.bind(this, 'name')} /> <p className="help-block"> A memorable name for the device-profile. </p> </div> <div className="form-group"> <label className="control-label" htmlFor="networkServerID">Network-server</label> <Select name="networkServerID" options={networkServerOptions} value={this.state.deviceProfile.networkServerID} onChange={this.onSelectChange.bind(this, 'networkServerID')} disabled={this.state.update} /> <p className="help-block"> The network-server on which this device-profile will be provisioned. After creating the device-profile, this value can't be changed. </p> </div> <div className="form-group"> <label className="control-label" htmlFor="macVersion">LoRaWAN MAC version</label> <Select name="macVersion" options={macVersionOptions} value={this.state.deviceProfile.deviceProfile.macVersion} onChange={this.onSelectChange.bind(this, 'deviceProfile.macVersion')} /> <p className="help-block"> Version of the LoRaWAN supported by the End-Device. </p> </div> <div className="form-group"> <label className="control-label" htmlFor="macVersion">LoRaWAN Regional Parameters revision</label> <Select name="regParamsRevision" options={regParamsOptions} value={this.state.deviceProfile.deviceProfile.regParamsRevision} onChange={this.onSelectChange.bind(this, 'deviceProfile.regParamsRevision')} /> <p className="help-block"> Revision of the Regional Parameters document supported by the End-Device. </p> </div> <div className="form-group"> <label className="control-label" htmlFor="maxEIRP">Max EIRP</label> <input className="form-control" name="maxEIRP" id="maxEIRP" type="number" value={this.state.deviceProfile.deviceProfile.maxEIRP || 0} onChange={this.onChange.bind(this, 'deviceProfile.maxEIRP')} /> <p className="help-block"> Maximum EIRP supported by the End-Device. </p> </div> </div> <div className={(this.state.activeTab === "join" ? "" : "hidden")}> <div className="form-group"> <label className="control-label" htmlFor="supportsJoin">Supports join (OTAA)</label> <div className="checkbox"> <label> <input type="checkbox" name="supportsJoin" id="supportsJoin" checked={this.state.deviceProfile.deviceProfile.supportsJoin} onChange={this.onChange.bind(this, 'deviceProfile.supportsJoin')} /> Supports join </label> </div> <p className="help-block"> End-Device supports Join (OTAA) or not (ABP). </p> </div> <div className={"form-group " + (this.state.deviceProfile.deviceProfile.supportsJoin === true ? "hidden" : "")}> <label className="control-label" htmlFor="rxDelay1">RX1 delay</label> <input className="form-control" name="rxDelay1" id="rxDelay1" type="number" value={this.state.deviceProfile.deviceProfile.rxDelay1 || 0} onChange={this.onChange.bind(this, 'deviceProfile.rxDelay1')} /> <p className="help-block"> Class A RX1 delay (mandatory for ABP). </p> </div> <div className={"form-group " + (this.state.deviceProfile.deviceProfile.supportsJoin === true ? "hidden" : "")}> <label className="control-label" htmlFor="rxDROffset1">RX1 data-rate offset</label> <input className="form-control" name="rxDROffset1" id="rxDROffset1" type="number" value={this.state.deviceProfile.deviceProfile.rxDROffset1 || 0} onChange={this.onChange.bind(this, 'deviceProfile.rxDROffset1')} /> <p className="help-block"> RX1 data rate offset (mandatory for ABP). </p> </div> <div className={"form-group " + (this.state.deviceProfile.deviceProfile.supportsJoin === true ? "hidden" : "")}> <label className="control-label" htmlFor="rxDataRate2">RX2 data-rate</label> <input className="form-control" name="rxDataRate2" id="rxDataRate2" type="number" value={this.state.deviceProfile.deviceProfile.rxDataRate2 || 0} onChange={this.onChange.bind(this, 'deviceProfile.rxDataRate2')} /> <p className="help-block"> RX2 data rate (mandatory for ABP). </p> </div> <div className={"form-group " + (this.state.deviceProfile.deviceProfile.supportsJoin === true ? "hidden" : "")}> <label className="control-label" htmlFor="rxFreq2">RX2 channel frequency</label> <input className="form-control" name="rxFreq2" id="rxFreq2" type="number" value={this.state.deviceProfile.deviceProfile.rxFreq2 || 0} onChange={this.onChange.bind(this, 'deviceProfile.rxFreq2')} /> <p className="help-block"> RX2 channel frequency (mandatory for ABP). </p> </div> <div className={"form-group " + (this.state.deviceProfile.deviceProfile.supportsJoin === true ? "hidden" : "")}> <label className="control-label" htmlFor="factoryPresetFreqsStr">Factory-present frequencies</label> <input className="form-control" id="factoryPresetFreqsStr" type="text" placeholder="e.g. 860100000, 868300000, 868500000" value={this.state.deviceProfile.deviceProfile.factoryPresetFreqsStr || ''} onChange={this.onChange.bind(this, 'deviceProfile.factoryPresetFreqsStr')} /> <p className="help-block"> List of factory-preset frequencies (mandatory for ABP). </p> </div> </div> <div className={(this.state.activeTab === "classC" ? "" : "hidden")}> <div className="form-group"> <label className="control-label" htmlFor="supportsClassC">Supports Class-C</label> <div className="checkbox"> <label> <input type="checkbox" name="supportsClassC" id="supportsClassC" checked={this.state.deviceProfile.deviceProfile.supportsClassC} onChange={this.onChange.bind(this, 'deviceProfile.supportsClassC')} /> Supports Class-C </label> </div> <p className="help-block"> End-Device supports Class C. </p> </div> <div className={"form-group " + (this.state.deviceProfile.deviceProfile.supportsClassC === true ? "" : "hidden")}> <label className="control-label" htmlFor="classCTimeout">Class-C confirmed downlink timeout</label> <input className="form-control" name="classCTimeout" id="classCTimeout" type="number" value={this.state.deviceProfile.deviceProfile.classCTimeout || 0} onChange={this.onChange.bind(this, 'deviceProfile.classCTimeout')} /> <p className="help-block"> Class-C timeout (in seconds) for confirmed downlink transmissions. </p> </div> </div> </fieldset> <hr /> <div className={"btn-toolbar pull-right " + (this.state.isAdmin ? "" : "hidden")}> <a className="btn btn-default" onClick={this.context.router.goBack}>Go back</a> <button type="submit" className="btn btn-primary">Submit</button> </div> </form> </div> ); } } export default DeviceProfileForm;
ui/src/core/components/Loader.js
mkacper/erlangpl
// @flow import React from 'react'; import './Loader.css'; type Props = { text: string }; const Loader = ({ text }: Props) => ( <div className="loader"> <div className="text-center"> <div className="spinner"> <div className="bounce1" /> <div className="bounce2" /> <div className="bounce3" /> </div> <span>{text}</span> </div> </div> ); export default Loader;
src/layout.js
titoesteves/react_practice2
import React from 'react' import ampersandMixin from 'ampersand-react-mixin' import NavHelper from './components/nav-helper' export default React.createClass({ mixins: [ampersandMixin], displayName: 'Layout', render () { const {me} = this.props return ( <NavHelper> <nav className='top-nav top-nav-light cf' role='navigation'> <input id='menu-toggle' className='menu-toggle' type='checkbox'/> <label htmlFor='menu-toggle'>Menu</label> <ul className='list-unstyled list-inline cf'> <li>Labelr</li> <li><a href='/repos'>Repos</a></li> <li className='pull-right'><a href='/logout'>Logout</a> {me.login}</li> </ul> </nav> <div className='container'> {this.props.children} </div> </NavHelper> ) } })
src/android.js
peterox/react-redux-form
/* eslint-disable react/prop-types */ import React from 'react'; import { Picker, Switch, TextInput, Slider, Text, View, } from 'react-native'; import { modelReducer, formReducer, modeled, actions, combineForms, initialFieldState, actionTypes, Control, Form, Fieldset, Errors, batched, form, getField, track, } from './index'; import omit from './utils/omit'; function getTextValue(value) { if (typeof value === 'string' || typeof value === 'number') { return `${value}`; } return ''; } const noop = () => undefined; Control.Picker = (props) => ( <Control component={Picker} mapProps={{ onResponderGrant: ({ onFocus }) => onFocus, onResponderRelease: ({ onBlur }) => onBlur, selectedValue: ({ modelValue }) => modelValue, onValueChange: ({ onChange }) => onChange, onChange: noop, ...props.mapProps, }} {...omit(props, 'mapProps')} /> ); Control.Switch = (props) => ( <Control component={Switch} mapProps={{ onResponderGrant: ({ onFocus }) => onFocus, onResponderRelease: ({ onBlur }) => onBlur, value: ({ modelValue }) => ! ! modelValue, onValueChange: ({ onChange }) => onChange, onChange: noop, ...props.mapProps, }} {...omit(props, 'mapProps')} /> ); Control.TextInput = (props) => ( <Control component={TextInput} mapProps={{ onResponderGrant: ({ onFocus }) => onFocus, value: (_props) => ((! _props.defaultValue && ! _props.hasOwnProperty('value')) ? getTextValue(_props.viewValue) : _props.value), onChangeText: ({ onChange }) => onChange, onChange: noop, onBlur: ({ onBlur, viewValue }) => () => onBlur(viewValue), onFocus: ({ onFocus }) => onFocus, ...props.mapProps, }} {...omit(props, 'mapProps')} /> ); Control.Slider = (props) => ( <Control component={Slider} mapProps={{ value: ({ modelValue }) => modelValue, onResponderGrant: ({ onFocus }) => onFocus, onSlidingComplete: ({ onBlur }) => onBlur, onValueChange: ({ onChange }) => onChange, onChange: noop, ...props.mapProps, }} {...omit(props, 'mapProps')} /> ); const NativeForm = (props) => <Form component={View} {...omit(props, 'mapProps')} />; const NativeFieldset = (props) => <Fieldset component={View} {...omit(props, 'mapProps')} />; const NativeErrors = (props) => ( <Errors wrapper={View} component={Text} {...props} /> ); export { // Reducers formReducer, modelReducer, combineForms, // Constants initialFieldState, actions, actionTypes, // Components Control, NativeForm as Form, NativeErrors as Errors, NativeFieldset as Fieldset, // Enhancers modeled, batched, // Selectors form, // Utilities getField, track, };
clients/libs/slate-editor-components/src/modal/ModalContent.js
nossas/bonde-client
/* eslint-disable no-undef */ /* eslint-disable react/prop-types */ import React from 'react' // FIXME: Needs to handle assets files to work with SSR // eslint-disable-next-line @typescript-eslint/no-var-requires if (require('exenv').canUseDOM) require('./ModalContent.module.css') const ModalContent = ({ children }) => ( <div className="modal--content"> {children} </div> ) // eslint-disable-next-line react/display-name ModalContent.Left = ({ children }) => ( <div className="modal--content-left"> {children} </div> ) // eslint-disable-next-line react/display-name ModalContent.Right = ({ children }) => ( <div className="modal--content-right"> {children} </div> ) export default ModalContent
src/About.js
parkjoon/trivia-aficionados
import React from 'react'; import Banner from './Banner'; import Footer from './Footer'; import Header from './Header'; export default class About extends React.Component { render() { return ( <div> <Header view='about' /> <div role="main" className="main"> <Banner view={'about'} /> <div className="container"> <div className="row mt-xl"> <div className="col-md-8 col-md-offset-2 mt-xlg title-with-video-custom center"> <h1 className="mt-xlg font-weight-semibold text-uppercase">About Us</h1> <p className="mb-none lead">Learn about what makes us the best choice for your next event.</p> </div> </div> </div> <div className="container"> <div className="row mb-xl mt-xlg"> <div className="col-md-9"> <blockquote className="mt-xl ml-lg blockquote-secondary"> <p>We let you decide what night and time you want to schedule trivia, We work around your availability and offer competitive prices.</p> <footer>Tyler Mosher, CEO</footer> </blockquote> </div> <div className="col-md-3 hidden-xs"> <div className="row"> <div className="col-md-6"> <img className="img-responsive mt-xl mb-xl" src="/src/assets/img/demos/digital-agency/office/demo-office-4.jpg" alt="Office" /> </div> <div className="col-md-6"> <img className="img-responsive mb-xl" src="/src/assets/img/demos/digital-agency/office/demo-office-5.jpg" alt="Office" /> </div> </div> </div> </div> </div> <section className="section section-default"> <div className="container"> <div className="row"> <div className="col-md-12 center"> <h2 className="mb-none mt-xl font-weight-semibold">What we do.</h2> <div className="divider divider-primary divider-small divider-small-center mb-xl"> <hr /> </div> <p className="lead mb-none">Our service is simple. We do the leg work to promote the event through local advertising and social media. We bring the customers to your pub, keep them captivated for hours with our world class trivia. They drink and spend their disposable income at your fine establishment. They have such a swell time they return week after week and spread the word about what a great time they have with friends, coworkers & family. We post a recap for every quiz which allows our players to share their experience via social media.</p> </div> </div> </div> </section> <section className="m-xl pb-xl m-t"> <div className="container"> <div className="row"> <div className="col-md-12 center"> <h2 className="mb-none mt-xl font-weight-semibold">What we bring.</h2> <div className="divider divider-primary divider-small divider-small-center mb-xl"> <hr /> </div> <p className="lead mb-none">We provide everything needed to run trivia. We provide the pencils, answer sheets, and A/V equipment. The venue is encouraged to provide the prizes typically consisting of gift certificates redeemable another day. We provide the winning team with a one of a kind Trivia Aficionados metallic lapel pin.</p> </div> </div> </div> </section> <section className="section section-default section-footer"> <div className="container"> <div className="row"> <div className="col-md-12 center"> <h2 className="mb-none mt-xl font-weight-semibold">Why choose us?</h2> <div className="divider divider-primary divider-small divider-small-center mb-xl"> <hr /> </div> <p className="lead mb-none">Writing quizzes is our passion. Our quizzes are unique, engaging, and interactive. We incorporate sound and video, making the experience interactive and memorable with our audience.</p> </div> </div> </div> </section> </div> <Footer /> </div> ); } }
boilerplates/basic/src/components/droids/index.js
goncalvesjoao/react-to-commonJS
import React from 'react'; import Droid from './Droid'; import jQuery from 'jquery'; import config from '../../config'; class Droids extends React.Component { constructor() { super(); this.state = { droids: [] }; } componentWillMount() { jQuery.ajax({ url: config.url + 'droids.json', dataType: 'json', success: (data) => { this.setState({ droids: data }); }, }); } renderDroids() { if (!this.state.droids.length) { return <li><h2>These are not the droids you are looking for</h2></li>; } return this.state.droids.map((droid, index) => { return <Droid key={ index } droid={ droid } { ...this.props } />; }); } render() { return ( <ul className="list-inline"> { this.renderDroids() } </ul> ); } } export default Droids;
tools/lib/watch.js
yudppp/react-starter-kit-with-falcor
/** * React Starter Kit (http://www.reactstarterkit.com/) * * Copyright © 2014-2015 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import gaze from 'gaze'; export default (pattern) => new Promise((resolve, reject) => { gaze(pattern, (err, watcher) => err ? reject(err) : resolve(watcher)); });
examples/custom-server-express/pages/index.js
nikvm/next.js
import React from 'react' import Link from 'next/link' export default () => ( <ul> <li><Link href='/b' as='/a'><a>a</a></Link></li> <li><Link href='/a' as='/b'><a>b</a></Link></li> </ul> )
app/components/profile/Profile.js
JoaoCnh/picto-pc
import React, { Component } from 'react'; import { Link } from 'react-router'; import Button from '../common/Button'; import styles from './Profile.css'; import AuthAPI from '../../api/auth'; import imageUtils from '../../utils/images'; export default class Profile extends Component { constructor(props) { super(props); this.currentUser = AuthAPI.getLogin(); } _handleLogout(event) { event.preventDefault(); this.props.logout(); return this.props.push("/auth/login"); } render() { return ( <div className={styles.profileCard}> <div className={styles.profile}> <img src={imageUtils.getUserPic(this.currentUser)} className={styles.border} /> <div className={styles.profileName}> {this.currentUser.username} </div> </div> <Button asRoute={true} route="profile/info" icon="user" text="Change Information" /> <Button asRoute={true} route="profile/achievements" icon="trophy" text="Achievements" /> <Button asLink={true} callback={this._handleLogout.bind(this)} icon="sign-out" text="Logout" /> </div> ); } }
public/src/admin/AdminPanel.react.js
SLedunois/personal-website
import React, { Component } from 'react'; import Nav from './nav/Nav.react'; import PropTypes from 'prop-types'; class AdminPanel extends Component { render() { return ( <div> <Nav history={this.props.history} location={this.props.location} /> {this.props.children} </div> ); } } AdminPanel.propTypes = { history: PropTypes.object, location: PropTypes.object, children: PropTypes.object, }; export default AdminPanel;
ajax/libs/react-highcharts/8.4.1/ReactHighstock.js
AMoo-Miki/cdnjs
!function(t,r){"object"==typeof exports&&"object"==typeof module?module.exports=r(require("react"),require("highcharts/highstock")):"function"==typeof define&&define.amd?define(["react","highcharts/highstock"],r):"object"==typeof exports?exports.ReactHighstock=r(require("react"),require("highcharts/highstock")):t.ReactHighstock=r(t.React,t.Highcharts)}(this,function(t,r){return function(t){function r(o){if(e[o])return e[o].exports;var n=e[o]={exports:{},id:o,loaded:!1};return t[o].call(n.exports,n,n.exports,r),n.loaded=!0,n.exports}var e={};return r.m=t,r.c=e,r.p="",r(0)}([function(t,r,e){t.exports=e(6)},function(r,e){r.exports=t},function(t,r,e){(function(r){"use strict";var o=Object.assign||function(t){for(var r=1;r<arguments.length;r++){var e=arguments[r];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},n=e(1),i="undefined"==typeof r?window:r;t.exports=function(r,e){var c="Highcharts"+r,s=n.createClass({displayName:c,propTypes:{config:n.PropTypes.object.isRequired,isPureConfig:n.PropTypes.bool,neverReflow:n.PropTypes.bool,callback:n.PropTypes.func},defaultProps:{callback:function(){}},renderChart:function(t){var n=this;if(!t)throw new Error("Config must be specified for the "+c+" component");var s=t.chart;this.chart=new e[r](o({},t,{chart:o({},s,{renderTo:this.refs.chart})}),this.props.callback),this.props.neverReflow||i.requestAnimationFrame&&requestAnimationFrame(function(){n.chart&&n.chart.options&&n.chart.reflow()})},shouldComponentUpdate:function(t){return t.neverReflow||t.isPureConfig&&this.props.config===t.config?!0:(this.renderChart(t.config),!1)},getChart:function(){if(!this.chart)throw new Error("getChart() should not be called before the component is mounted");return this.chart},componentDidMount:function(){this.renderChart(this.props.config)},componentWillUnmount:function(){this.chart.destroy()},render:function(){var t=this.props;return t=o({},t,{ref:"chart"}),n.createElement("div",t)}});return s.Highcharts=e,s.withHighcharts=function(e){return t.exports(r,e)},s}}).call(r,function(){return this}())},,,,function(t,r,e){"use strict";t.exports=e(2)("StockChart",e(9))},,,function(t,e){t.exports=r}])});
src/Accordion.js
victorzhang17/react-bootstrap
import React from 'react'; import PanelGroup from './PanelGroup'; const Accordion = React.createClass({ render() { return ( <PanelGroup {...this.props} accordion> {this.props.children} </PanelGroup> ); } }); export default Accordion;
docs/src/pages/component-demos/app-bar/ButtonAppBar.js
dsslimshaddy/material-ui
// @flow weak import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import AppBar from 'material-ui/AppBar'; import Toolbar from 'material-ui/Toolbar'; import Typography from 'material-ui/Typography'; import Button from 'material-ui/Button'; import IconButton from 'material-ui/IconButton'; import MenuIcon from 'material-ui-icons/Menu'; const styles = { root: { marginTop: 30, width: '100%', }, flex: { flex: 1, }, }; function ButtonAppBar(props) { const classes = props.classes; return ( <div className={classes.root}> <AppBar position="static"> <Toolbar> <IconButton color="contrast" aria-label="Menu"> <MenuIcon /> </IconButton> <Typography type="title" color="inherit" className={classes.flex}> Title </Typography> <Button color="contrast">Login</Button> </Toolbar> </AppBar> </div> ); } ButtonAppBar.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(ButtonAppBar);
packages/material-ui/src/RootRef/RootRef.js
allanalexandre/material-ui
import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import { exactProp } from '@material-ui/utils'; import { setRef } from '../utils/reactHelpers'; /** * ⚠️⚠️⚠️ * If you want the DOM element of a Material-UI component check out * [/getting-started/faq/#how-can-i-access-the-dom-element](FAQ: How can I access the DOM element?) * first. * * This component uses `findDOMNode` which is deprecated in React.StrictMode. * * Helper component to allow attaching a ref to a * wrapped element to access the underlying DOM element. * * It's highly inspired by https://github.com/facebook/react/issues/11401#issuecomment-340543801. * For example: * ```jsx * import React from 'react'; * import RootRef from '@material-ui/core/RootRef'; * * class MyComponent extends React.Component { * constructor() { * super(); * this.domRef = React.createRef(); * } * * componentDidMount() { * console.log(this.domRef.current); // DOM node * } * * render() { * return ( * <RootRef rootRef={this.domRef}> * <SomeChildComponent /> * </RootRef> * ); * } * } * ``` */ class RootRef extends React.Component { componentDidMount() { this.ref = ReactDOM.findDOMNode(this); setRef(this.props.rootRef, this.ref); } componentDidUpdate(prevProps) { const ref = ReactDOM.findDOMNode(this); if (prevProps.rootRef !== this.props.rootRef || this.ref !== ref) { if (prevProps.rootRef !== this.props.rootRef) { setRef(prevProps.rootRef, null); } this.ref = ref; setRef(this.props.rootRef, this.ref); } } componentWillUnmount() { this.ref = null; setRef(this.props.rootRef, null); } render() { return this.props.children; } } RootRef.propTypes = { /** * The wrapped element. */ children: PropTypes.element.isRequired, /** * Provide a way to access the DOM node of the wrapped element. * You can provide a callback ref or a `React.createRef()` ref. */ rootRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired, }; if (process.env.NODE_ENV !== 'production') { RootRef.propTypes = exactProp(RootRef.propTypes); } export default RootRef;
js/jquery.min.js
blastcapgames/blastcapgames.github.io
/*! jQuery v1.11.2 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.2",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=hb(),z=hb(),A=hb(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},eb=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fb){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 gb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+rb(o[l]);w=ab.test(a)&&pb(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function hb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ib(a){return a[u]=!0,a}function jb(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function kb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function lb(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 mb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function nb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function ob(a){return ib(function(b){return b=+b,ib(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 pb(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=gb.support={},f=gb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=gb.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",eb,!1):e.attachEvent&&e.attachEvent("onunload",eb)),p=!f(g),c.attributes=jb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=jb(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=jb(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(jb(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),jb(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&jb(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return lb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?lb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},gb.matches=function(a,b){return gb(a,null,null,b)},gb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return gb(b,n,null,[a]).length>0},gb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},gb.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},gb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},gb.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=gb.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=gb.selectors={cacheLength:50,createPseudo:ib,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||gb.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]&&gb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+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=gb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||gb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ib(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:ib(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ib(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:ib(function(a){return function(b){return gb(a,b).length>0}}),contains:ib(function(a){return a=a.replace(cb,db),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ib(function(a){return W.test(a||"")||gb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:ob(function(){return[0]}),last:ob(function(a,b){return[b-1]}),eq:ob(function(a,b,c){return[0>c?c+b:c]}),even:ob(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:ob(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:ob(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:ob(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]=mb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=nb(b);function qb(){}qb.prototype=d.filters=d.pseudos,d.setFilters=new qb,g=gb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?gb.error(a):z(a,i).slice(0)};function rb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function tb(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 ub(a,b,c){for(var d=0,e=b.length;e>d;d++)gb(a,b[d],c);return c}function vb(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 wb(a,b,c,d,e,f){return d&&!d[u]&&(d=wb(d)),e&&!e[u]&&(e=wb(e,f)),ib(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ub(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:vb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=vb(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=vb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sb(function(a){return a===b},h,!0),l=sb(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=[sb(tb(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 wb(i>1&&tb(m),i>1&&rb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xb(a.slice(i,e)),f>e&&xb(a=a.slice(e)),f>e&&rb(a))}m.push(c)}return tb(m)}function yb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=vb(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&gb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ib(f):f}return h=gb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,yb(e,d)),f.selector=a}return f},i=gb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&pb(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&rb(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&pb(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=jb(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),jb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||kb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&jb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||kb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),jb(function(a){return null==a.getAttribute("disabled")})||kb(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}),gb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1; return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.removeChild(i)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e) }m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m});
examples/todo/js/components/Todo.js
tmitchel2/relay
/** * 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. */ import ChangeTodoStatusMutation from '../mutations/ChangeTodoStatusMutation'; import RemoveTodoMutation from '../mutations/RemoveTodoMutation'; import RenameTodoMutation from '../mutations/RenameTodoMutation'; import TodoTextInput from './TodoTextInput'; import React from 'react'; import Relay from 'react-relay'; import classnames from 'classnames'; class Todo extends React.Component { state = { isEditing: false, }; _handleCompleteChange = (e) => { var complete = e.target.checked; Relay.Store.update( new ChangeTodoStatusMutation({ complete, todo: this.props.todo, viewer: this.props.viewer, }) ); } _handleDestroyClick = () => { this._removeTodo(); } _handleLabelDoubleClick = () => { this._setEditMode(true); } _handleTextInputCancel = () => { this._setEditMode(false); } _handleTextInputDelete = () => { this._setEditMode(false); this._removeTodo(); } _handleTextInputSave = (text) => { this._setEditMode(false); Relay.Store.update( new RenameTodoMutation({todo: this.props.todo, text}) ); } _removeTodo() { Relay.Store.update( new RemoveTodoMutation({todo: this.props.todo, viewer: this.props.viewer}) ); } _setEditMode = (shouldEdit) => { this.setState({isEditing: shouldEdit}); } renderTextInput() { return ( <TodoTextInput className="edit" commitOnBlur={true} initialValue={this.props.todo.text} onCancel={this._handleTextInputCancel} onDelete={this._handleTextInputDelete} onSave={this._handleTextInputSave} /> ); } render() { return ( <li className={classnames({ completed: this.props.todo.complete, editing: this.state.isEditing, })}> <div className="view"> <input checked={this.props.todo.complete} className="toggle" onChange={this._handleCompleteChange} type="checkbox" /> <label onDoubleClick={this._handleLabelDoubleClick}> {this.props.todo.text} </label> <button className="destroy" onClick={this._handleDestroyClick} /> </div> {this.state.isEditing && this.renderTextInput()} </li> ); } } export default Relay.createContainer(Todo, { fragments: { todo: () => Relay.QL` fragment on Todo { complete, id, text, ${ChangeTodoStatusMutation.getFragment('todo')}, ${RemoveTodoMutation.getFragment('todo')}, ${RenameTodoMutation.getFragment('todo')}, } `, viewer: () => Relay.QL` fragment on User { ${ChangeTodoStatusMutation.getFragment('viewer')}, ${RemoveTodoMutation.getFragment('viewer')}, } `, }, });
src/components/Footer/Footer.js
poeschko/ask-refugeescode
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import FaTwitter from 'react-icons/lib/fa/twitter'; import FaFacebook from 'react-icons/lib/fa/facebook'; import FaGitHub from 'react-icons/lib/fa/github'; import s from './Footer.css'; class Footer extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <div className={s.links}> <a className={s.link} href="https://twitter.com/RefugeesCode"> {' '}<FaTwitter />{' '} </a>&nbsp; <a className={s.link} href="https://www.facebook.com/refugeescode/"> {' '}<FaFacebook />{' '} </a>&nbsp; <a className={s.link} href="https://github.com/poeschko/ask-refugeescode" > {' '}<FaGitHub />{' '} </a> </div> <span className={s.text}> © Developed by{' '} <a className={s.link} href="http://www.refugeescode.at/"> refugees{'{'}code{'}'} </a> </span> </div> </div> ); } } export default withStyles(s)(Footer);
tests/react/useReducer_hook.js
AgentME/flow
// @flow import React from 'react'; { React.useReducer(); // Error: function requires another argument. } function reducer(state, action) { switch (action.type) { case "reset": return { count: action.payload }; case "increment": return { count: state.count + 1 }; case "decrement": return { count: state.count - 1 }; default: return state; } } const initialState = { count: 0 }; { const [state, dispatch] = React.useReducer(reducer, initialState); (state.count: number); // Ok (state.count: string); // Error: number is incompatible with string dispatch({ type: "reset", payload: 123 }); dispatch({ type: "increment" }); dispatch({ type: "decrement" }); } { const initialAction = { type: "reset", payload: 123 }; const [state, dispatch] = React.useReducer(reducer, initialState, initialAction); (state.count: number); // Ok dispatch({ type: "reset", payload: 123 }); dispatch({ type: "increment" }); dispatch({ type: "decrement" }); }
app/components/Icons/icons/icon-info.js
code4romania/monitorizare-vot-votanti-client
import React from 'react'; function IconInfo() { return ( <svg version="1.1" id="icon-info" x="0px" y="0px" viewBox="-41 164.9 512 512"> <g> <g> <path d="M229.9,467.8c-10.6-14.9-27.5-24.1-45.7-24.8c-0.4,0-0.8-0.1-1.2-0.1c-23.1,0-42.3-17.5-44.9-39.9c6.7-4.9,12.8-11,18.3-18.4c11-14.9,18.2-33.5,20.8-53.7c0.8-0.9,1.5-1.9,2-3.1c4.7-11.1,7-23,7-35.2c0-47.2-35.7-85.6-79.6-85.6c-11.3,0-22.4,2.6-32.8,7.7c-3.9,0.3-7.7,1-11.4,2.1c-36.7,10.6-57.4,55-46.2,98.9c1.1,4.4,2.6,8.8,4.3,12.9c0.5,1.1,1.1,2.1,1.9,3c4.2,31,18.9,56.8,39,71.4c-2.6,22.5-21.7,40-44.9,40c-0.4,0-0.7,0-1.1,0.1c-31.4,1.1-56.6,27-56.6,58.6v63.1c0,5.9,4.8,10.7,10.7,10.7h188.5c5.9,0,10.7-4.8,10.7-10.7c0-5.9-4.8-10.7-10.7-10.7H-19.7v-52.5c0-20.6,16.7-37.3,37.3-37.3c0.4,0,0.7,0,1.1-0.1c7.7-0.2,15-1.8,21.9-4.4l50.5,72.9c2,2.9,5.3,4.6,8.8,4.6s6.8-1.7,8.8-4.6l50.5-72.9c6.8,2.6,14.2,4.2,21.9,4.4c0.3,0,0.7,0.1,1.1,0.1c12.1,0,23.5,5.9,30.5,15.8c2.1,2.9,5.4,4.5,8.7,4.5c2.1,0,4.3-0.6,6.1-2C232.2,479.3,233.3,472.6,229.9,467.8z M68.5,237.3c2.8-0.8,5.8-1.3,8.8-1.4c1.6-0.1,3.1-0.5,4.5-1.2c7.9-4.2,16.3-6.3,24.9-6.3c31.5,0,57.2,27.7,58.2,62.2c-6.4-4.9-14.4-7.7-23-7.7H86.1c-2.8,0-5.4-0.9-7.6-2.5c-1.9-1.4-3.4-3.3-4.2-5.5c-2-5-7-8.1-12.4-7.8c-5.4,0.3-10,4.1-11.3,9.4c-2.7,10.5-7.8,20.2-14.7,28.5C30.3,273.9,44.2,244.3,68.5,237.3z M43.5,327.6c9.3-8.5,16.9-18.9,22.1-30.3c0,0,0.1,0.1,0.1,0.1c5.9,4.4,13,6.8,20.4,6.8h55.8c6.7,0,12.5,3.9,15.2,9.6c-0.1,22.2-6.4,42.9-17.8,58.3c-10.8,14.6-24.8,22.6-39.5,22.6c-13.6,0-26.8-7-37.2-19.8C52.5,362.5,45.8,345.9,43.5,327.6zM99.8,507.9L59,449c10.9-9.1,18.9-21.6,22.3-35.9c5.9,1.9,12.1,2.8,18.5,2.8c6.3,0,12.5-1,18.5-2.8c3.4,14.3,11.4,26.8,22.3,35.9L99.8,507.9z" /> </g> </g> <g> <g> <path d="M414.4,502.3c-0.3,0-0.7-0.1-1.1-0.1c-23.2,0-42.3-17.5-44.9-40c13.1-9.5,23.8-23.8,30.9-41.1c1,3.3,3.6,6,7,7.1c1,0.3,2.1,0.5,3.2,0.5c3.2,0,6.4-1.5,8.4-4.1c14.9-19.1,22.6-44,21.8-70C439,329,430,305,414.5,287c-15.9-18.4-36.8-28.7-59-28.9c-1.2,0-4.1,0.1-4.6,0.1c-11.4-5.2-23.5-7.6-35.9-7.2c-25.6,0.8-49.2,13.6-66.4,36c-16.7,21.7-25.4,50.1-24.4,79.9c0.2,5,0.6,9.7,1.2,14.1c1.7,12.7,5.2,24.8,10.4,36.1c1.6,3.6,5.1,6,9.1,6.2c3.9,0.2,7.7-1.7,9.7-5.1c0.9-1.4,2-3.2,3.2-4.9c4.8,14.4,12,27.4,21.3,37.7c3.9,4.4,8.2,8.2,12.7,11.4c-2.6,22.5-21.7,40-44.9,40c-0.4,0-0.7,0-1.1,0.1c-31.4,1.1-56.6,27-56.6,58.6v63.1c0,5.9,4.8,10.7,10.7,10.7h260.3c5.9,0,10.7-4.8,10.7-10.7v-63.1C471,529.3,445.8,503.5,414.4,502.3z M249.1,390.5c-1.1-4.1-1.9-8.3-2.5-12.6c-0.5-3.7-0.9-7.6-1-11.8c-0.8-24.8,6.3-48.3,20-66.2c13.2-17.2,31-27,50.1-27.6c0.6,0,14.4-0.8,28.4,6.3c1.6,0.8,3.4,1.2,5.1,1.1c0.2,0,5.7-0.3,5.8-0.3c16,0.1,31.4,7.7,43.2,21.5c12.3,14.3,19.5,33.6,20.1,54.3c0.4,11.2-1.2,22.2-4.6,32.2c-1-2.7-2.1-5.3-3.4-7.9c-10.3-21.9-27.6-38.9-48.8-47.8c-2.7-1.1-5.7-1.1-8.4,0c-2.7,1.2-4.8,3.4-5.8,6.1c-1.4,3.8-3.1,7.6-5.1,11.1c-5.6,10-16.8,15.9-29.4,15.5c-1.9-0.1-3.8-0.1-5.7,0c-9.2,0.3-18.2,2.1-26.8,5.2C272.3,372.9,258,380.9,249.1,390.5z M275.4,396.3c4-2.7,8.3-4.9,12.9-6.6c6.3-2.4,13.1-3.7,20-3.9c1.4,0,2.8,0,4.2,0c20.6,0.7,39.2-9.4,48.7-26.4c0.6-1,1.2-2.1,1.7-3.2c9.7,6,18,14.4,24.3,24.7c-0.1,0.3-0.1,0.6-0.1,1c-1.6,20.2-8.6,38.8-19.7,52.3c-10.4,12.7-23.7,19.8-37.2,19.8C305,453.9,282.7,430,275.4,396.3z M311.7,472.4c6,1.9,12.2,2.9,18.5,2.9c6.4,0,12.6-1,18.6-2.9c4.3,18.2,16,33.5,31.8,42.5c-6.2,22.3-26.6,38.3-50.3,38.3c-23.7,0-44.2-16-50.3-38.3C295.6,505.9,307.4,490.5,311.7,472.4z M449.7,613.4h-239V561c0-20.6,16.7-37.3,37.3-37.3c0.4,0,0.7,0,1.1-0.1c3.7-0.1,7.3-0.5,10.8-1.2c9.3,30.4,37.6,52.1,70.3,52.1s61.1-21.7,70.3-52.1c3.5,0.7,7.1,1.1,10.8,1.2c0.3,0,0.7,0.1,1.1,0.1c20.6,0,37.3,16.7,37.3,37.3V613.4z" /> </g> </g> </svg> ); } export default IconInfo;
static/metis/lib/jquery-validation-1.11.1/lib/jquery-1.8.3.js
wangbinxiang/csAdmin
/*! * jQuery JavaScript Library v1.8.3 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: Tue Nov 13 2012 08:20:33 GMT-0500 (Eastern Standard Time) */ (function( window, undefined ) { var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, navigator = window.navigator, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Save a reference to some core methods core_push = Array.prototype.push, core_slice = Array.prototype.slice, core_indexOf = Array.prototype.indexOf, core_toString = Object.prototype.toString, core_hasOwn = Object.prototype.hasOwnProperty, core_trim = String.prototype.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, // Used for detecting and trimming whitespace core_rnotwhite = /\S/, core_rspace = /\s+/, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // The ready event handler and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context && context.nodeType ? context.ownerDocument || context : document ); // scripts is true for back-compat selector = jQuery.parseHTML( match[1], doc, true ); if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { this.attr.call( selector, context, true ); } return jQuery.merge( this, selector ); // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.8.3", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ), "slice", core_slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ core_toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // scripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, scripts ) { var parsed; if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { scripts = context; context = 0; } context = context || document; // Single tag if ( (parsed = rsingleTag.exec( data )) ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); return jQuery.merge( [], (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); }, parseJSON: function( data ) { if ( !data || typeof data !== "string") { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && core_rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var name, i = 0, length = obj.length, isObj = length === undefined || jQuery.isFunction( obj ); if ( args ) { if ( isObj ) { for ( name in obj ) { if ( callback.apply( obj[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( obj[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in obj ) { if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var type, ret = results || []; if ( arr != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 type = jQuery.type( arr ); if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { core_push.call( ret, arr ); } else { jQuery.merge( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready, 1 ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.split( core_rspace ), function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Control if a given callback is in the list has: function( fn ) { return jQuery.inArray( fn, list ) > -1; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? function() { var returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } } : newDefer[ action ] ); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] = list.fire deferred[ tuple[0] ] = list.fire; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, eventName, i, isSupported, clickFn, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: ( document.compatMode === "CSS1Compat" ), // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", clickFn = function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent("onclick"); div.detachEvent( "onclick", clickFn ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; input.setAttribute( "checked", "checked" ); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } // Run tests that need a body at doc ready jQuery(function() { var container, div, tds, marginDiv, divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = document.createElement("div"); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; div.appendChild( marginDiv ); support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); container.style.zoom = 1; } // Null elements to avoid leaks in IE body.removeChild( container ); container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE fragment.removeChild( div ); all = a = select = opt = input = fragment = div = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, deletedIds: [], // Remove at next major release (1.9/2.0) uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, part, attr, name, l, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery.removeData( elem, type + "queue", true ); jQuery.removeData( elem, key, true ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, fixSpecified, rclass = /[\t\r\n]/g, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea|)$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var removes, className, elem, c, cl, i, l; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { removes = ( value || "" ).split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { className = (" " + elem.className + " ").replace( rclass, " " ); // loop over each item in the removal list for ( c = 0, cl = removes.length; c < cl; c++ ) { // Remove until there is nothing to remove, while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) { className = className.replace( " " + removes[ c ] + " " , " " ); } } elem.className = value ? jQuery.trim( className ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( core_rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 attrFn: {}, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.split( core_rspace ); for ( ; i < attrNames.length; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true, coords: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.value = value + "" ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var t, tns, type, origType, namespaces, origCount, j, events, special, eventType, handleObj, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, "events", true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, type = event.type || event, namespaces = []; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; for ( old = elem; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old === (elem.ownerDocument || document) ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = core_slice.call( arguments ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = []; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { selMatch = {}; matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) event.metaKey = !!event.metaKey; return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === "undefined" ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "_submit_attached" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "_submit_attached", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "_change_attached", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // && selector != null // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var cachedruns, assertGetIdNotName, Expr, getText, isXML, contains, compile, sortOrder, hasDuplicate, outermostContext, baseHasDuplicate = true, strundefined = "undefined", expando = ( "sizcache" + Math.random() ).replace( ".", "" ), Token = String, document = window.document, docElem = document.documentElement, dirruns = 0, done = 0, pop = [].pop, push = [].push, slice = [].slice, // Use a stripped-down indexOf if a native one is unavailable indexOf = [].indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Augment a function for special use by Sizzle markFunction = function( fn, value ) { fn[ expando ] = value == null || value; return fn; }, createCache = function() { var cache = {}, keys = []; return markFunction(function( key, value ) { // Only keep the most recent entries if ( keys.push( key ) > Expr.cacheLength ) { delete cache[ keys.shift() ]; } // Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157) return (cache[ key + " " ] = value); }, cache ); }, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // Regex // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors) // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments not in parens/brackets, // then attribute selectors and non-pseudos (denoted by :), // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)", // For matchExpr.POS and matchExpr.needsContext pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, rnot = /^:not/, rsibling = /[\x20\t\r\n\f]*[+~]/, rendsWithNot = /:not\($/, rheader = /h\d/i, rinputs = /input|select|textarea|button/i, rbackslash = /\\(?!\\)/g, matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "POS": new RegExp( pos, "i" ), "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) }, // Support // Used for testing something on an element assert = function( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } }, // Check if getElementsByTagName("*") returns only elements assertTagNameNoComments = assert(function( div ) { div.appendChild( document.createComment("") ); return !div.getElementsByTagName("*").length; }), // Check if getAttribute returns normalized href attributes assertHrefNotNormalized = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }), // Check if attributes should be retrieved by attribute nodes assertAttributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }), // Check if getElementsByClassName can be trusted assertUsableClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }), // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID assertUsableName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = document.getElementsByName && // buggy browsers will return fewer than the correct 2 document.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 document.getElementsByName( expando + 0 ).length; assertGetIdNotName = !document.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // If slice is not available, provide a backup try { slice.call( docElem.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; for ( ; (elem = this[i]); i++ ) { results.push( elem ); } return results; }; } function Sizzle( selector, context, results, seed ) { results = results || []; context = context || document; var match, elem, xml, m, nodeType = context.nodeType; if ( !selector || typeof selector !== "string" ) { return results; } if ( nodeType !== 1 && nodeType !== 9 ) { return []; } xml = isXML( context ); if ( !xml && !seed ) { if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed, xml ); } Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { return Sizzle( expr, null, null, [ elem ] ).length > 0; }; // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes } else { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } return ret; }; isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Element contains another contains = Sizzle.contains = docElem.contains ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); } : docElem.compareDocumentPosition ? function( a, b ) { return b && !!( a.compareDocumentPosition( b ) & 16 ); } : function( a, b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } return false; }; Sizzle.attr = function( elem, name ) { var val, xml = isXML( elem ); if ( !xml ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( xml || assertAttributes ) { return elem.getAttribute( name ); } val = elem.getAttributeNode( name ); return val ? typeof elem[ name ] === "boolean" ? elem[ name ] ? name : null : val.specified ? val.value : null : null; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, // IE6/7 return a modified href attrHandle: assertHrefNotNormalized ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }, find: { "ID": assertGetIdNotName ? function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } } : function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }, "TAG": assertTagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { var elem, tmp = [], i = 0; for ( ; (elem = results[i]); i++ ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }, "NAME": assertUsableName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }, "CLASS": assertUsableClassName && function( className, context, xml ) { if ( typeof context.getElementsByClassName !== strundefined && !xml ) { return context.getElementsByClassName( className ); } } }, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( rbackslash, "" ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) 4 sign of xn-component 5 x of xn-component 6 sign of y-component 7 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1] === "nth" ) { // nth-child requires argument if ( !match[2] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); // other types prohibit arguments } else if ( match[2] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var unquoted, excess; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } if ( match[3] ) { match[2] = match[3]; } else if ( (unquoted = match[4]) ) { // Only check arguments that contain a pseudo if ( rpseudo.test(unquoted) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index unquoted = unquoted.slice( 0, excess ); match[0] = match[0].slice( 0, excess ); } match[2] = unquoted; } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "ID": assertGetIdNotName ? function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { return elem.getAttribute("id") === id; }; } : function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === id; }; }, "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ expando ][ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem, context ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.substr( result.length - check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, argument, first, last ) { if ( type === "nth" ) { return function( elem ) { var node, diff, parent = elem.parentNode; if ( first === 1 && last === 0 ) { return true; } if ( parent ) { diff = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { diff++; if ( elem === node ) { break; } } } } // Incorporate the offset (or cast to NaN), then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); }; } return function( elem ) { var node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") var nodeType; elem = elem.firstChild; while ( elem ) { if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { return false; } elem = elem.nextSibling; } return true; }, "header": function( elem ) { return rheader.test( elem.nodeName ); }, "text": function( elem ) { var type, attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && (type = elem.type) === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); }, // Input types "radio": createInputPseudo("radio"), "checkbox": createInputPseudo("checkbox"), "file": createInputPseudo("file"), "password": createInputPseudo("password"), "image": createInputPseudo("image"), "submit": createButtonPseudo("submit"), "reset": createButtonPseudo("reset"), "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "focus": function( elem ) { var doc = elem.ownerDocument; return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, "active": function( elem ) { return elem === elem.ownerDocument.activeElement; }, // Positional types "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { for ( var i = 0; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { for ( var i = 1; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; function siblingCheck( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; } sortOrder = docElem.compareDocumentPosition ? function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4 ) ? -1 : 1; } : function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). [0, 0].sort( sortOrder ); baseHasDuplicate = !hasDuplicate; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], i = 1, j = 0; hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ expando ][ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); // Cast descendant combinators to space matched.type = match[0].replace( rtrim, " " ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); matched.type = type; matched.matches = match; } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && combinator.dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( !xml ) { var cache, dirkey = dirruns + " " + doneName + " ", cachedkey = dirkey + cachedruns; while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( (cache = elem[ expando ]) === cachedkey ) { return elem.sizset; } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { if ( elem.sizset ) { return elem; } } else { elem[ expando ] = cachedkey; if ( matcher( elem, context, xml ) ) { elem.sizset = true; return elem; } elem.sizset = false; } } } } else { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( matcher( elem, context, xml ) ) { return elem; } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && tokens.join("") ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if ( outermost ) { outermostContext = context !== document && context; cachedruns = superMatcher.el; } // Add elements passing elementMatchers directly to results for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { for ( j = 0; (matcher = elementMatchers[j]); j++ ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++superMatcher.el; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { for ( j = 0; (matcher = setMatchers[j]); j++ ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; superMatcher.el = 0; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ expando ][ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed, xml ) { var i, tokens, token, type, find, match = tokenize( selector ), j = match.length; if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !xml && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().length ); } // Fetch a seed set for right-to-left matching for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( rbackslash, "" ), rsibling.test( tokens[0].type ) && context.parentNode || context, xml )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && tokens.join(""); if ( !selector ) { push.apply( results, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, xml, results, rsibling.test( selector ) ); return results; } if ( document.querySelectorAll ) { (function() { var disconnectedMatch, oldSelect = select, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ], // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active rbuggyMatches = [ ":active" ], matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector; // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here (do not put tests after this one) if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE9 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<p test=''></p>"; if ( div.querySelectorAll("[test^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) div.innerHTML = "<input type='hidden'/>"; if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push(":enabled", ":disabled"); } }); // rbuggyQSA always contains :focus, so no need for a length check rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") ); select = function( selector, context, results, seed, xml ) { // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply if ( !seed && !xml && !rbuggyQSA.test( selector ) ) { var groups, i, old = true, nid = expando, newContext = context, newSelector = context.nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + groups[i].join(""); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } return oldSelect( selector, context, results, seed, xml ); }; if ( matches ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead try { matches.call( div, "[test!='']:sizzle" ); rbuggyMatches.push( "!=", pseudos ); } catch ( e ) {} }); // rbuggyMatches always contains :active and :focus, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); Sizzle.matchesSelector = function( elem, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyMatches always contains :active, so no need for an existence check if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, null, null, [ elem ] ).length > 0; }; } })(); } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Back-compat function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, l, length, n, r, ret, self = this; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } ret = this.pushStack( "", "find", selector ); for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, core_slice.call( arguments ).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rcheckableType = /^(?:checkbox|radio)$/, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "X<div>", "</div>" ]; } jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); } }, after: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName( "*" ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { if ( !isDisconnected( this[0] ) ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = [].concat.apply( [], args ); var results, first, fragment, iNoClone, i = 0, value = args[0], scripts = [], l = this.length; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call( this, i, table ? self.html() : undefined ); self.domManip( args, table, callback ); }); } if ( this[0] ) { results = jQuery.buildFragment( args, this, scripts ); fragment = results.fragment; first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). // Fragments from the fragment cache must always be cloned and never used in place. for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], i === iNoClone ? fragment : jQuery.clone( fragment, true, true ) ); } } // Fix #11809: Avoid leaking memory fragment = first = null; if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { if ( jQuery.ajax ) { jQuery.ajax({ url: elem.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.error("no ajax"); } } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); if ( nodeName === "object" ) { // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, context, scripts ) { var fragment, cacheable, cachehit, first = args[ 0 ]; // Set context from what may come in as undefined or a jQuery collection or a node // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 & // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception context = context || document; context = !context.nodeType && context[0] || context; context = context.ownerDocument || context; // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { // Mark cacheable and look for a hit cacheable = true; fragment = jQuery.fragments[ first ]; cachehit = fragment !== undefined; } if ( !fragment ) { fragment = context.createDocumentFragment(); jQuery.clean( args, context, fragment, scripts ); // Update the cache, but only store false // unless this is a second parsing of the same content if ( cacheable ) { jQuery.fragments[ first ] = cachehit && fragment; } } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), l = insert.length, parent = this.length === 1 && this[0].parentNode; if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( ; i < l; i++ ) { elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, clone; if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, safe = context === document && safeFragment, ret = []; // Ensure that context is a document if ( !context || typeof context.createDocumentFragment === "undefined" ) { context = document; } // Use the already-created safe fragment if context permits for ( i = 0; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Ensure a safe container in which to render the html safe = safe || createSafeFragment( context ); div = context.createElement("div"); safe.appendChild( div ); // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Go to html and back, then peel off extra wrappers tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; depth = wrap[0]; div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> hasBody = rtbody.test(elem); tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; // Take out of fragment container (we need a fresh div each time) div.parentNode.removeChild( div ); } } if ( elem.nodeType ) { ret.push( elem ); } else { jQuery.merge( ret, elem ); } } // Fix #11356: Clear elements from safeFragment if ( div ) { elem = div = safe = null; } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { for ( i = 0; (elem = ret[i]) != null; i++ ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } } // Append elements to a provided document fragment if ( fragment ) { // Special handling of each script element handleScript = function( elem ) { // Check if we consider it executable if ( !elem.type || rscriptType.test( elem.type ) ) { // Detach the script and store it in the scripts array (if provided) or the fragment // Return truthy to indicate that it has been handled return scripts ? scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : fragment.appendChild( elem ); } }; for ( i = 0; (elem = ret[i]) != null; i++ ) { // Check if we're done after handling an executable script if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { // Append to fragment and handle embedded scripts fragment.appendChild( elem ); if ( typeof elem.getElementsByTagName !== "undefined" ) { // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); // Splice the scripts into ret after their former ancestor and advance our index beyond them ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); i += jsTags.length; } } } } return ret; }, cleanData: function( elems, /* internal */ acceptData ) { var data, id, elem, type, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } jQuery.deletedIds.push( id ); } } } } } }); // Limit scope pollution from any deprecated API (function() { var matched, browser; // Use of jQuery.browser is frowned upon. // More details: http://api.jquery.com/jQuery.browser // jQuery.uaMatch maintained for back-compat jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; matched = jQuery.uaMatch( navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; } // Chrome is Webkit, but Webkit is also Safari. if ( browser.chrome ) { browser.webkit = true; } else if ( browser.webkit ) { browser.safari = true; } jQuery.browser = browser; jQuery.sub = function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }; })(); var curCSS, iframe, iframeDoc, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], eventsToggle = jQuery.fn.toggle; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var elem, display, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && elem.style.display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { display = curCSS( elem, "display" ); if ( !values[ index ] && display !== "none" ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state, fn2 ) { var bool = typeof state === "boolean"; if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) { return eventsToggle.apply( this, arguments ); } return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, numeric, extra ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( numeric || extra !== undefined ) { num = parseFloat( val ); return numeric || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { curCSS = function( elem, name ) { var ret, width, minWidth, maxWidth, computed = window.getComputedStyle( elem, null ), style = elem.style; if ( computed ) { // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { curCSS = function( elem, name ) { var left, rsLeft, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { // we use jQuery.css instead of curCSS here // because of the reliableMarginRight CSS hook! val += jQuery.css( elem, extra + cssExpand[ i ], true ); } // From this point on we use curCSS for maximum performance (relevant in animations) if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } else { // at this point, extra isn't content, so add padding val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, valueIsBorderBox = true, isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { if ( elemdisplay[ nodeName ] ) { return elemdisplay[ nodeName ]; } var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ), display = elem.css("display"); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // Use the already-created iframe if possible iframe = document.body.appendChild( iframe || jQuery.extend( document.createElement("iframe"), { frameBorder: 0, width: 0, height: 0 }) ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write("<!doctype html><html><body>"); iframeDoc.close(); } elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) ); display = curCSS( elem, "display" ); document.body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } else { return getWidthOrHeight( elem, name, extra ); } } }, set: function( elem, value, extra ) { return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box" ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { return curCSS( elem, "marginRight" ); } }); } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { var ret = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rselectTextarea = /^(?:select|textarea)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, list, placeBefore, dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), i = 0, length = dataTypes.length; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var selection, list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ); for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } // Don't do a request if no elements are being requested if ( !this.length ) { return this; } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // Request the remote document jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params, complete: function( jqXHR, status ) { if ( callback ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); } } }).done(function( responseText ) { // Save response for use in complete callback response = arguments; // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append( responseText.replace( rscript, "" ) ) // Locate the specified elements .find( selector ) : // If not, just inject the full result responseText ); }); return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // ifModified key ifModifiedKey, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || strAbort; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ ifModifiedKey ] = modified; } modified = jqXHR.getResponseHeader("Etag"); if ( modified ) { jQuery.etag[ ifModifiedKey ] = modified; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.always( tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv, conv2, current, tmp, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ], converters = {}, i = 0; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } var oldCallbacks = [], rquestion = /\?/, rjsonp = /(=)\?(?=&|$)|\?\?/, nonce = jQuery.now(); // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, data = s.data, url = s.url, hasCallback = s.jsonp !== false, replaceInUrl = hasCallback && rjsonp.test( url ), replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( data ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; overwritten = window[ callbackName ]; // Insert callback into url or form data if ( replaceInUrl ) { s.url = url.replace( rjsonp, "$1" + callbackName ); } else if ( replaceInData ) { s.data = data.replace( rjsonp, "$1" + callbackName ); } else if ( hasCallback ) { s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var xhrCallbacks, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( e ) { } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback, 0 ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }, 0 ); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } function Animation( elem, properties, options ) { var result, index = 0, tweenerIndex = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end, easing ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } createTweens( animation, props ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { anim: animation, queue: animation.opts.queue, elem: elem }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.done(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery.removeData( elem, "fxshow", true ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing any value as a 4th parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, false, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Remove in 2.0 - this supports IE8's panic based approach // to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" || // special check for .toggle( handler, handler, ... ) ( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations resolve immediately if ( empty ) { anim.stop( true ); } }; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) && !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.interval = 13; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } var rroot = /^(?:body|html)$/i; jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } if ( (body = doc.body) === elem ) { return jQuery.offset.bodyOffset( elem ); } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== "undefined" ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); clientTop = docElem.clientTop || body.clientTop || 0; clientLeft = docElem.clientLeft || body.clientLeft || 0; scrollTop = win.pageYOffset || docElem.scrollTop; scrollLeft = win.pageXOffset || docElem.scrollLeft; return { top: box.top + scrollTop - clientTop, left: box.left + scrollLeft - clientLeft }; }; jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.body; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, value, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
ajax/libs/vega/2.2.0/vega.js
calebmer/cdnjs
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.vg = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ module.exports = { version: '2.2.0', dataflow: require('vega-dataflow'), parse: require('./src/parse/'), scene: { Bounder: require('./src/scene/Bounder'), Builder: require('./src/scene/Builder'), Encoder: require('./src/scene/Encoder'), GroupBuilder: require('./src/scene/GroupBuilder'), }, transforms: require('./src/transforms'), schema: require('./src/core/schema'), config: require('./src/core/config'), util: require('datalib'), debug: require('vega-logging').debug }; },{"./src/core/config":88,"./src/core/schema":89,"./src/parse/":95,"./src/scene/Bounder":107,"./src/scene/Builder":108,"./src/scene/Encoder":109,"./src/scene/GroupBuilder":110,"./src/transforms":139,"datalib":24,"vega-dataflow":39,"vega-logging":45}],2:[function(require,module,exports){ },{}],3:[function(require,module,exports){ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : factory((global.dsv = {})); }(this, function (exports) { 'use strict'; var dsv = function(delimiter) { var reFormat = new RegExp("[\"" + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); function parse(text, f) { var o; return parseRows(text, function(row, i) { if (o) return o(row, i - 1); var a = new Function("d", "return {" + row.map(function(name, i) { return JSON.stringify(name) + ": d[" + i + "]"; }).join(",") + "}"); o = f ? function(row, i) { return f(a(row), i); } : a; }); } function parseRows(text, f) { var EOL = {}, // sentinel value for end-of-line EOF = {}, // sentinel value for end-of-file rows = [], // output rows N = text.length, I = 0, // current character index n = 0, // the current line number t, // the current token eol; // is the current token followed by EOL? function token() { if (I >= N) return EOF; // special case: end of file if (eol) return eol = false, EOL; // special case: end of line // special case: quotes var j = I; if (text.charCodeAt(j) === 34) { var i = j; while (i++ < N) { if (text.charCodeAt(i) === 34) { if (text.charCodeAt(i + 1) !== 34) break; ++i; } } I = i + 2; var c = text.charCodeAt(i + 1); if (c === 13) { eol = true; if (text.charCodeAt(i + 2) === 10) ++I; } else if (c === 10) { eol = true; } return text.slice(j + 1, i).replace(/""/g, "\""); } // common case: find next delimiter or newline while (I < N) { var c = text.charCodeAt(I++), k = 1; if (c === 10) eol = true; // \n else if (c === 13) { eol = true; if (text.charCodeAt(I) === 10) ++I, ++k; } // \r|\r\n else if (c !== delimiterCode) continue; return text.slice(j, I - k); } // special case: last token before EOF return text.slice(j); } while ((t = token()) !== EOF) { var a = []; while (t !== EOL && t !== EOF) { a.push(t); t = token(); } if (f && (a = f(a, n++)) == null) continue; rows.push(a); } return rows; } function format(rows) { if (Array.isArray(rows[0])) return formatRows(rows); // deprecated; use formatRows var fieldSet = Object.create(null), fields = []; // Compute unique fields in order of discovery. rows.forEach(function(row) { for (var field in row) { if (!((field += "") in fieldSet)) { fields.push(fieldSet[field] = field); } } }); return [fields.map(formatValue).join(delimiter)].concat(rows.map(function(row) { return fields.map(function(field) { return formatValue(row[field]); }).join(delimiter); })).join("\n"); } function formatRows(rows) { return rows.map(formatRow).join("\n"); } function formatRow(row) { return row.map(formatValue).join(delimiter); } function formatValue(text) { return reFormat.test(text) ? "\"" + text.replace(/\"/g, "\"\"") + "\"" : text; } return { parse: parse, parseRows: parseRows, format: format, formatRows: formatRows }; } exports.csv = dsv(","); exports.tsv = dsv("\t"); exports.dsv = dsv; })); },{}],4:[function(require,module,exports){ if (typeof Map === "undefined") { Map = function() { this.clear(); }; Map.prototype = { set: function(k, v) { this._[k] = v; return this; }, get: function(k) { return this._[k]; }, has: function(k) { return k in this._; }, delete: function(k) { return k in this._ && delete this._[k]; }, clear: function() { this._ = Object.create(null); }, get size() { var n = 0; for (var k in this._) ++n; return n; }, forEach: function(c) { for (var k in this._) c(this._[k], k, this); } }; } else (function() { var m = new Map; if (m.set(0, 0) !== m) { m = m.set; Map.prototype.set = function() { m.apply(this, arguments); return this; }; } })(); (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : factory((global.format = {})); }(this, function (exports) { 'use strict'; var zhCn = { decimal: ".", thousands: ",", grouping: [3], currency: ["¥", ""] }; var ruRu = { decimal: ",", thousands: "\xa0", grouping: [3], currency: ["", "\xa0руб."] }; var ptBr = { decimal: ",", thousands: ".", grouping: [3], currency: ["R$", ""] }; var plPl = { decimal: ",", thousands: ".", grouping: [3], currency: ["", "zł"] }; var nlNl = { decimal: ",", thousands: ".", grouping: [3], currency: ["€\xa0", ""] }; var mkMk = { decimal: ",", thousands: ".", grouping: [3], currency: ["", "\xa0ден."] }; var itIt = { decimal: ",", thousands: ".", grouping: [3], currency: ["€", ""] }; var heIl = { decimal: ".", thousands: ",", grouping: [3], currency: ["₪", ""] }; var frFr = { decimal: ",", thousands: ".", grouping: [3], currency: ["", "\xa0€"] }; var frCa = { decimal: ",", thousands: "\xa0", grouping: [3], currency: ["", "$"] }; var fiFi = { decimal: ",", thousands: "\xa0", grouping: [3], currency: ["", "\xa0€"] }; var esEs = { decimal: ",", thousands: ".", grouping: [3], currency: ["", "\xa0€"] }; var enUs = { decimal: ".", thousands: ",", grouping: [3], currency: ["$", ""] }; var enGb = { decimal: ".", thousands: ",", grouping: [3], currency: ["£", ""] }; var enCa = { decimal: ".", thousands: ",", grouping: [3], currency: ["$", ""] }; var deDe = { decimal: ",", thousands: ".", grouping: [3], currency: ["", "\xa0€"] }; var caEs = { decimal: ",", thousands: ".", grouping: [3], currency: ["", "\xa0€"] }; // Computes the decimal coefficient and exponent of the specified number x with // significant digits p, where x is positive and p is in [1, 21] or undefined. // For example, formatDecimal(1.23) returns ["123", 0]. function formatDecimal(x, p) { if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity var i, coefficient = x.slice(0, i); // The string returned by toExponential either has the form \d\.\d+e[-+]\d+ // (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3). return [ coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient, +x.slice(i + 1) ]; } function exponent(x) { return x = formatDecimal(Math.abs(x)), x ? x[1] : NaN; } var prefixExponent; function formatPrefixAuto(x, p) { var d = formatDecimal(x, p); if (!d) return x + ""; var coefficient = d[0], exponent = d[1], i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1, n = coefficient.length; return i === n ? coefficient : i > n ? coefficient + new Array(i - n + 1).join("0") : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i) : "0." + new Array(1 - i).join("0") + formatDecimal(x, p + i - 1)[0]; // less than 1y! } function formatRounded(x, p) { var d = formatDecimal(x, p); if (!d) return x + ""; var coefficient = d[0], exponent = d[1]; return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1) : coefficient + new Array(exponent - coefficient.length + 2).join("0"); } function formatDefault(x, p) { x = x.toPrecision(p); out: for (var n = x.length, i = 1, i0 = -1, i1; i < n; ++i) { switch (x[i]) { case ".": i0 = i1 = i; break; case "0": if (i0 === 0) i0 = i; i1 = i; break; case "e": break out; default: if (i0 > 0) i0 = 0; break; } } return i0 > 0 ? x.slice(0, i0) + x.slice(i1 + 1) : x; } var formatTypes = { "": formatDefault, "%": function(x, p) { return (x * 100).toFixed(p); }, "b": function(x) { return Math.round(x).toString(2); }, "c": function(x) { return x + ""; }, "d": function(x) { return Math.round(x).toString(10); }, "e": function(x, p) { return x.toExponential(p); }, "f": function(x, p) { return x.toFixed(p); }, "g": function(x, p) { return x.toPrecision(p); }, "o": function(x) { return Math.round(x).toString(8); }, "p": function(x, p) { return formatRounded(x * 100, p); }, "r": formatRounded, "s": formatPrefixAuto, "X": function(x) { return Math.round(x).toString(16).toUpperCase(); }, "x": function(x) { return Math.round(x).toString(16); } }; // [[fill]align][sign][symbol][0][width][,][.precision][type] var re = /^(?:(.)?([<>=^]))?([+\-\( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?([a-z%])?$/i; function formatSpecifier(specifier) { return new FormatSpecifier(specifier); } function FormatSpecifier(specifier) { if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier); var match, fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zero = !!match[5], width = match[6] && +match[6], comma = !!match[7], precision = match[8] && +match[8].slice(1), type = match[9] || ""; // The "n" type is an alias for ",g". if (type === "n") comma = true, type = "g"; // Map invalid types to the default format. else if (!formatTypes[type]) type = ""; // If zero fill is specified, padding goes after sign and before digits. if (zero || (fill === "0" && align === "=")) zero = true, fill = "0", align = "="; this.fill = fill; this.align = align; this.sign = sign; this.symbol = symbol; this.zero = zero; this.width = width; this.comma = comma; this.precision = precision; this.type = type; } FormatSpecifier.prototype.toString = function() { return this.fill + this.align + this.sign + this.symbol + (this.zero ? "0" : "") + (this.width == null ? "" : Math.max(1, this.width | 0)) + (this.comma ? "," : "") + (this.precision == null ? "" : "." + Math.max(0, this.precision | 0)) + this.type; }; function formatGroup(grouping, thousands) { return function(value, width) { var i = value.length, t = [], j = 0, g = grouping[0], length = 0; while (i > 0 && g > 0) { if (length + g + 1 > width) g = Math.max(1, width - length); t.push(value.substring(i -= g, i + g)); if ((length += g + 1) > width) break; g = grouping[j = (j + 1) % grouping.length]; } return t.reverse().join(thousands); }; } var prefixes = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"]; function identity(x) { return x; } function locale(locale) { var group = locale.grouping && locale.thousands ? formatGroup(locale.grouping, locale.thousands) : identity, currency = locale.currency, decimal = locale.decimal; function format(specifier) { specifier = formatSpecifier(specifier); var fill = specifier.fill, align = specifier.align, sign = specifier.sign, symbol = specifier.symbol, zero = specifier.zero, width = specifier.width, comma = specifier.comma, precision = specifier.precision, type = specifier.type; // Compute the prefix and suffix. // For SI-prefix, the suffix is lazily computed. var prefix = symbol === "$" ? currency[0] : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "", suffix = symbol === "$" ? currency[1] : /[%p]/.test(type) ? "%" : ""; // What format function should we use? // Is this an integer type? // Can this type generate exponential notation? var formatType = formatTypes[type], maybeSuffix = !type || /[defgprs%]/.test(type); // Set the default precision if not specified, // or clamp the specified precision to the supported range. // For significant precision, it must be in [1, 21]. // For fixed precision, it must be in [0, 20]. precision = precision == null ? (type ? 6 : 12) : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision)); return function(value) { var valuePrefix = prefix, valueSuffix = suffix; if (type === "c") { valueSuffix = formatType(value) + valueSuffix; value = ""; } else { value = +value; // Convert negative to positive, and compute the prefix. // Note that -0 is not less than 0, but 1 / -0 is! var valueNegative = (value < 0 || 1 / value < 0) && (value *= -1, true); // Perform the initial formatting. value = formatType(value, precision); // Compute the prefix and suffix. valuePrefix = (valueNegative ? (sign === "(" ? sign : "-") : sign === "-" || sign === "(" ? "" : sign) + valuePrefix; valueSuffix = valueSuffix + (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + (valueNegative && sign === "(" ? ")" : ""); // Break the formatted value into the integer “value” part that can be // grouped, and fractional or exponential “suffix” part that is not. if (maybeSuffix) { var i = -1, n = value.length, c; while (++i < n) { if (c = value.charCodeAt(i), 48 > c || c > 57) { valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix; value = value.slice(0, i); break; } } } } // If the fill character is not "0", grouping is applied before padding. if (comma && !zero) value = group(value, Infinity); // Compute the padding. var length = valuePrefix.length + value.length + valueSuffix.length, padding = length < width ? new Array(width - length + 1).join(fill) : ""; // If the fill character is "0", grouping is applied after padding. if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = ""; // Reconstruct the final output based on the desired alignment. switch (align) { case "<": return valuePrefix + value + valueSuffix + padding; case "=": return valuePrefix + padding + value + valueSuffix; case "^": return padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); } return padding + valuePrefix + value + valueSuffix; }; } function formatPrefix(specifier, value) { var f = format((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)), e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3, k = Math.pow(10, -e), prefix = prefixes[8 + e / 3]; return function(value) { return f(k * value) + prefix; }; } return { format: format, formatPrefix: formatPrefix }; } function precisionRound(step, max) { return Math.max(0, exponent(Math.abs(max)) - exponent(Math.abs(step))) + 1; } function precisionPrefix(step, value) { return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3 - exponent(Math.abs(step))); } function precisionFixed(step) { return Math.max(0, -exponent(Math.abs(step))); } var localeDefinitions = (new Map) .set("ca-ES", caEs) .set("de-DE", deDe) .set("en-CA", enCa) .set("en-GB", enGb) .set("en-US", enUs) .set("es-ES", esEs) .set("fi-FI", fiFi) .set("fr-CA", frCa) .set("fr-FR", frFr) .set("he-IL", heIl) .set("it-IT", itIt) .set("mk-MK", mkMk) .set("nl-NL", nlNl) .set("pl-PL", plPl) .set("pt-BR", ptBr) .set("ru-RU", ruRu) .set("zh-CN", zhCn); var defaultLocale = locale(enUs); exports.format = defaultLocale.format; exports.formatPrefix = defaultLocale.formatPrefix; function localeFormat(definition) { if (typeof definition === "string") { definition = localeDefinitions.get(definition); if (!definition) return null; } return locale(definition); } ; exports.localeFormat = localeFormat; exports.formatSpecifier = formatSpecifier; exports.precisionFixed = precisionFixed; exports.precisionPrefix = precisionPrefix; exports.precisionRound = precisionRound; })); },{}],5:[function(require,module,exports){ if (typeof Map === "undefined") { Map = function() { this.clear(); }; Map.prototype = { set: function(k, v) { this._[k] = v; return this; }, get: function(k) { return this._[k]; }, has: function(k) { return k in this._; }, delete: function(k) { return k in this._ && delete this._[k]; }, clear: function() { this._ = Object.create(null); }, get size() { var n = 0; for (var k in this._) ++n; return n; }, forEach: function(c) { for (var k in this._) c(this._[k], k, this); } }; } else (function() { var m = new Map; if (m.set(0, 0) !== m) { m = m.set; Map.prototype.set = function() { m.apply(this, arguments); return this; }; } })(); (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : factory((global.timeFormat = {})); }(this, function (exports) { 'use strict'; var zhCn = { dateTime: "%a %b %e %X %Y", date: "%Y/%-m/%-d", time: "%H:%M:%S", periods: ["上午", "下午"], days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"], shortDays: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"], months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], shortMonths: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"] }; var ruRu = { dateTime: "%A, %e %B %Y г. %X", date: "%d.%m.%Y", time: "%H:%M:%S", periods: ["AM", "PM"], days: ["воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота"], shortDays: ["вс", "пн", "вт", "ср", "чт", "пт", "сб"], months: ["января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"], shortMonths: ["янв", "фев", "мар", "апр", "май", "июн", "июл", "авг", "сен", "окт", "ноя", "дек"] }; var ptBr = { dateTime: "%A, %e de %B de %Y. %X", date: "%d/%m/%Y", time: "%H:%M:%S", periods: ["AM", "PM"], days: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"], shortDays: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"], months: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"], shortMonths: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"] }; var plPl = { dateTime: "%A, %e %B %Y, %X", date: "%d/%m/%Y", time: "%H:%M:%S", periods: ["AM", "PM"], // unused days: ["Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota"], shortDays: ["Niedz.", "Pon.", "Wt.", "Śr.", "Czw.", "Pt.", "Sob."], months: ["Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień"], shortMonths: ["Stycz.", "Luty", "Marz.", "Kwie.", "Maj", "Czerw.", "Lipc.", "Sierp.", "Wrz.", "Paźdz.", "Listop.", "Grudz."]/* In Polish language abbraviated months are not commonly used so there is a dispute about the proper abbraviations. */ }; var nlNl = { dateTime: "%a %e %B %Y %T", date: "%d-%m-%Y", time: "%H:%M:%S", periods: ["AM", "PM"], // unused days: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"], shortDays: ["zo", "ma", "di", "wo", "do", "vr", "za"], months: ["januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"], shortMonths: ["jan", "feb", "mrt", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec"] }; var mkMk = { dateTime: "%A, %e %B %Y г. %X", date: "%d.%m.%Y", time: "%H:%M:%S", periods: ["AM", "PM"], days: ["недела", "понеделник", "вторник", "среда", "четврток", "петок", "сабота"], shortDays: ["нед", "пон", "вто", "сре", "чет", "пет", "саб"], months: ["јануари", "февруари", "март", "април", "мај", "јуни", "јули", "август", "септември", "октомври", "ноември", "декември"], shortMonths: ["јан", "фев", "мар", "апр", "мај", "јун", "јул", "авг", "сеп", "окт", "ное", "дек"] }; var itIt = { dateTime: "%A %e %B %Y, %X", date: "%d/%m/%Y", time: "%H:%M:%S", periods: ["AM", "PM"], // unused days: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato"], shortDays: ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"], months: ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"], shortMonths: ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"] }; var heIl = { dateTime: "%A, %e ב%B %Y %X", date: "%d.%m.%Y", time: "%H:%M:%S", periods: ["AM", "PM"], days: ["ראשון", "שני", "שלישי", "רביעי", "חמישי", "שישי", "שבת"], shortDays: ["א׳", "ב׳", "ג׳", "ד׳", "ה׳", "ו׳", "ש׳"], months: ["ינואר", "פברואר", "מרץ", "אפריל", "מאי", "יוני", "יולי", "אוגוסט", "ספטמבר", "אוקטובר", "נובמבר", "דצמבר"], shortMonths: ["ינו׳", "פבר׳", "מרץ", "אפר׳", "מאי", "יוני", "יולי", "אוג׳", "ספט׳", "אוק׳", "נוב׳", "דצמ׳"] }; var frFr = { dateTime: "%A, le %e %B %Y, %X", date: "%d/%m/%Y", time: "%H:%M:%S", periods: ["AM", "PM"], // unused days: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"], shortDays: ["dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam."], months: ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"], shortMonths: ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."] }; var frCa = { dateTime: "%a %e %b %Y %X", date: "%Y-%m-%d", time: "%H:%M:%S", periods: ["", ""], days: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"], shortDays: ["dim", "lun", "mar", "mer", "jeu", "ven", "sam"], months: ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"], shortMonths: ["jan", "fév", "mar", "avr", "mai", "jui", "jul", "aoû", "sep", "oct", "nov", "déc"] }; var fiFi = { dateTime: "%A, %-d. %Bta %Y klo %X", date: "%-d.%-m.%Y", time: "%H:%M:%S", periods: ["a.m.", "p.m."], days: ["sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai"], shortDays: ["Su", "Ma", "Ti", "Ke", "To", "Pe", "La"], months: ["tammikuu", "helmikuu", "maaliskuu", "huhtikuu", "toukokuu", "kesäkuu", "heinäkuu", "elokuu", "syyskuu", "lokakuu", "marraskuu", "joulukuu"], shortMonths: ["Tammi", "Helmi", "Maalis", "Huhti", "Touko", "Kesä", "Heinä", "Elo", "Syys", "Loka", "Marras", "Joulu"] }; var esEs = { dateTime: "%A, %e de %B de %Y, %X", date: "%d/%m/%Y", time: "%H:%M:%S", periods: ["AM", "PM"], days: ["domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"], shortDays: ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"], months: ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"], shortMonths: ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"] }; var enUs = { dateTime: "%a %b %e %X %Y", date: "%m/%d/%Y", time: "%H:%M:%S", periods: ["AM", "PM"], days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] }; var enGb = { dateTime: "%a %e %b %X %Y", date: "%d/%m/%Y", time: "%H:%M:%S", periods: ["AM", "PM"], days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] }; var enCa = { dateTime: "%a %b %e %X %Y", date: "%Y-%m-%d", time: "%H:%M:%S", periods: ["AM", "PM"], days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] }; var deDe = { dateTime: "%A, der %e. %B %Y, %X", date: "%d.%m.%Y", time: "%H:%M:%S", periods: ["AM", "PM"], // unused days: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"], shortDays: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"], months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], shortMonths: ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"] }; var caEs = { dateTime: "%A, %e de %B de %Y, %X", date: "%d/%m/%Y", time: "%H:%M:%S", periods: ["AM", "PM"], days: ["diumenge", "dilluns", "dimarts", "dimecres", "dijous", "divendres", "dissabte"], shortDays: ["dg.", "dl.", "dt.", "dc.", "dj.", "dv.", "ds."], months: ["gener", "febrer", "març", "abril", "maig", "juny", "juliol", "agost", "setembre", "octubre", "novembre", "desembre"], shortMonths: ["gen.", "febr.", "març", "abr.", "maig", "juny", "jul.", "ag.", "set.", "oct.", "nov.", "des."] }; var t0 = new Date; var t1 = new Date; function newInterval(floori, offseti, count) { function interval(date) { return floori(date = new Date(+date)), date; } interval.floor = interval; interval.round = function(date) { var d0 = new Date(+date), d1 = new Date(date - 1); floori(d0), floori(d1), offseti(d1, 1); return date - d0 < d1 - date ? d0 : d1; }; interval.ceil = function(date) { return floori(date = new Date(date - 1)), offseti(date, 1), date; }; interval.offset = function(date, step) { return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date; }; interval.range = function(start, stop, step) { var range = []; start = new Date(start - 1); stop = new Date(+stop); step = step == null ? 1 : Math.floor(step); if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date offseti(start, 1), floori(start); if (start < stop) range.push(new Date(+start)); while (offseti(start, step), floori(start), start < stop) range.push(new Date(+start)); return range; }; interval.filter = function(test) { return newInterval(function(date) { while (floori(date), !test(date)) date.setTime(date - 1); }, function(date, step) { while (--step >= 0) while (offseti(date, 1), !test(date)); }); }; if (count) interval.count = function(start, end) { t0.setTime(+start), t1.setTime(+end); floori(t0), floori(t1); return Math.floor(count(t0, t1)); }; return interval; } var day = newInterval(function(date) { date.setHours(0, 0, 0, 0); }, function(date, step) { date.setDate(date.getDate() + step); }, function(start, end) { return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * 6e4) / 864e5; }); function weekday(i) { return newInterval(function(date) { date.setHours(0, 0, 0, 0); date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7); }, function(date, step) { date.setDate(date.getDate() + step * 7); }, function(start, end) { return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * 6e4) / 6048e5; }); } var sunday = weekday(0); var monday = weekday(1); var year = newInterval(function(date) { date.setHours(0, 0, 0, 0); date.setMonth(0, 1); }, function(date, step) { date.setFullYear(date.getFullYear() + step); }, function(start, end) { return end.getFullYear() - start.getFullYear(); }); var utcDay = newInterval(function(date) { date.setUTCHours(0, 0, 0, 0); }, function(date, step) { date.setUTCDate(date.getUTCDate() + step); }, function(start, end) { return (end - start) / 864e5; }); function utcWeekday(i) { return newInterval(function(date) { date.setUTCHours(0, 0, 0, 0); date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7); }, function(date, step) { date.setUTCDate(date.getUTCDate() + step * 7); }, function(start, end) { return (end - start) / 6048e5; }); } var utcSunday = utcWeekday(0); var utcMonday = utcWeekday(1); var utcYear = newInterval(function(date) { date.setUTCHours(0, 0, 0, 0); date.setUTCMonth(0, 1); }, function(date, step) { date.setUTCFullYear(date.getUTCFullYear() + step); }, function(start, end) { return end.getUTCFullYear() - start.getUTCFullYear(); }); function localDate(d) { if (0 <= d.y && d.y < 100) { var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L); date.setFullYear(d.y); return date; } return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L); } function utcDate(d) { if (0 <= d.y && d.y < 100) { var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L)); date.setUTCFullYear(d.y); return date; } return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L)); } function newYear(y) { return {y: y, m: 0, d: 1, H: 0, M: 0, S: 0, L: 0}; } function locale(locale) { var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_weekdays = locale.days, locale_shortWeekdays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths; var periodLookup = formatLookup(locale_periods), weekdayRe = formatRe(locale_weekdays), weekdayLookup = formatLookup(locale_weekdays), shortWeekdayRe = formatRe(locale_shortWeekdays), shortWeekdayLookup = formatLookup(locale_shortWeekdays), monthRe = formatRe(locale_months), monthLookup = formatLookup(locale_months), shortMonthRe = formatRe(locale_shortMonths), shortMonthLookup = formatLookup(locale_shortMonths); var formats = { "a": formatShortWeekday, "A": formatWeekday, "b": formatShortMonth, "B": formatMonth, "c": null, "d": formatDayOfMonth, "e": formatDayOfMonth, "H": formatHour24, "I": formatHour12, "j": formatDayOfYear, "L": formatMilliseconds, "m": formatMonthNumber, "M": formatMinutes, "p": formatPeriod, "S": formatSeconds, "U": formatWeekNumberSunday, "w": formatWeekdayNumber, "W": formatWeekNumberMonday, "x": null, "X": null, "y": formatYear, "Y": formatFullYear, "Z": formatZone, "%": formatLiteralPercent }; var utcFormats = { "a": formatUTCShortWeekday, "A": formatUTCWeekday, "b": formatUTCShortMonth, "B": formatUTCMonth, "c": null, "d": formatUTCDayOfMonth, "e": formatUTCDayOfMonth, "H": formatUTCHour24, "I": formatUTCHour12, "j": formatUTCDayOfYear, "L": formatUTCMilliseconds, "m": formatUTCMonthNumber, "M": formatUTCMinutes, "p": formatUTCPeriod, "S": formatUTCSeconds, "U": formatUTCWeekNumberSunday, "w": formatUTCWeekdayNumber, "W": formatUTCWeekNumberMonday, "x": null, "X": null, "y": formatUTCYear, "Y": formatUTCFullYear, "Z": formatUTCZone, "%": formatLiteralPercent }; var parses = { "a": parseShortWeekday, "A": parseWeekday, "b": parseShortMonth, "B": parseMonth, "c": parseLocaleDateTime, "d": parseDayOfMonth, "e": parseDayOfMonth, "H": parseHour24, "I": parseHour24, "j": parseDayOfYear, "L": parseMilliseconds, "m": parseMonthNumber, "M": parseMinutes, "p": parsePeriod, "S": parseSeconds, "U": parseWeekNumberSunday, "w": parseWeekdayNumber, "W": parseWeekNumberMonday, "x": parseLocaleDate, "X": parseLocaleTime, "y": parseYear, "Y": parseFullYear, "Z": parseZone, "%": parseLiteralPercent }; // These recursive directive definitions must be deferred. formats.x = newFormat(locale_date, formats); formats.X = newFormat(locale_time, formats); formats.c = newFormat(locale_dateTime, formats); utcFormats.x = newFormat(locale_date, utcFormats); utcFormats.X = newFormat(locale_time, utcFormats); utcFormats.c = newFormat(locale_dateTime, utcFormats); function newFormat(specifier, formats) { return function(date) { var string = [], i = -1, j = 0, n = specifier.length, c, pad, format; while (++i < n) { if (specifier.charCodeAt(i) === 37) { string.push(specifier.slice(j, i)); if ((pad = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i); if (format = formats[c]) c = format(date, pad == null ? (c === "e" ? " " : "0") : pad); string.push(c); j = i + 1; } } string.push(specifier.slice(j, i)); return string.join(""); }; } function newParse(specifier, newDate) { return function(string) { var d = newYear(1900), i = parseSpecifier(d, specifier, string, 0); if (i != string.length) return null; // The am-pm flag is 0 for AM, and 1 for PM. if ("p" in d) d.H = d.H % 12 + d.p * 12; // If a time zone is specified, all fields are interpreted as UTC and then // offset according to the specified time zone. if ("Z" in d) { if ("w" in d && ("W" in d || "U" in d)) { var day = utcDate(newYear(d.y)).getUTCDay(); if ("W" in d) d.U = d.W, d.w = (d.w + 6) % 7, --day; d.m = 0; d.d = d.w + d.U * 7 - (day + 6) % 7; } d.H += d.Z / 100 | 0; d.M += d.Z % 100; return utcDate(d); } // Otherwise, all fields are in local time. if ("w" in d && ("W" in d || "U" in d)) { var day = newDate(newYear(d.y)).getDay(); if ("W" in d) d.U = d.W, d.w = (d.w + 6) % 7, --day; d.m = 0; d.d = d.w + d.U * 7 - (day + 6) % 7; } return newDate(d); }; } function parseSpecifier(d, specifier, string, j) { var i = 0, n = specifier.length, m = string.length, c, parse; while (i < n) { if (j >= m) return -1; c = specifier.charCodeAt(i++); if (c === 37) { c = specifier.charAt(i++); parse = parses[c in pads ? specifier.charAt(i++) : c]; if (!parse || ((j = parse(d, string, j)) < 0)) return -1; } else if (c != string.charCodeAt(j++)) { return -1; } } return j; } function parseShortWeekday(d, string, i) { var n = shortWeekdayRe.exec(string.slice(i)); return n ? (d.w = shortWeekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } function parseWeekday(d, string, i) { var n = weekdayRe.exec(string.slice(i)); return n ? (d.w = weekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } function parseShortMonth(d, string, i) { var n = shortMonthRe.exec(string.slice(i)); return n ? (d.m = shortMonthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } function parseMonth(d, string, i) { var n = monthRe.exec(string.slice(i)); return n ? (d.m = monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } function parseLocaleDateTime(d, string, i) { return parseSpecifier(d, locale_dateTime, string, i); } function parseLocaleDate(d, string, i) { return parseSpecifier(d, locale_date, string, i); } function parseLocaleTime(d, string, i) { return parseSpecifier(d, locale_time, string, i); } function parsePeriod(d, string, i) { var n = periodLookup.get(string.slice(i, i += 2).toLowerCase()); return n == null ? -1 : (d.p = n, i); } function formatShortWeekday(d) { return locale_shortWeekdays[d.getDay()]; } function formatWeekday(d) { return locale_weekdays[d.getDay()]; } function formatShortMonth(d) { return locale_shortMonths[d.getMonth()]; } function formatMonth(d) { return locale_months[d.getMonth()]; } function formatPeriod(d) { return locale_periods[+(d.getHours() >= 12)]; } function formatUTCShortWeekday(d) { return locale_shortWeekdays[d.getUTCDay()]; } function formatUTCWeekday(d) { return locale_weekdays[d.getUTCDay()]; } function formatUTCShortMonth(d) { return locale_shortMonths[d.getUTCMonth()]; } function formatUTCMonth(d) { return locale_months[d.getUTCMonth()]; } function formatUTCPeriod(d) { return locale_periods[+(d.getUTCHours() >= 12)]; } return { format: function(specifier) { var f = newFormat(specifier += "", formats); f.parse = newParse(specifier, localDate); f.toString = function() { return specifier; }; return f; }, utcFormat: function(specifier) { var f = newFormat(specifier += "", utcFormats); f.parse = newParse(specifier, utcDate); f.toString = function() { return specifier; }; return f; } }; } var pads = {"-": "", "_": " ", "0": "0"}; var numberRe = /^\s*\d+/; var percentRe = /^%/; var requoteRe = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; function pad(value, fill, width) { var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length; return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string); } function requote(s) { return s.replace(requoteRe, "\\$&"); } function formatRe(names) { return new RegExp("^(?:" + names.map(requote).join("|") + ")", "i"); } function formatLookup(names) { var map = new Map, i = -1, n = names.length; while (++i < n) map.set(names[i].toLowerCase(), i); return map; } function parseWeekdayNumber(d, string, i) { var n = numberRe.exec(string.slice(i, i + 1)); return n ? (d.w = +n[0], i + n[0].length) : -1; } function parseWeekNumberSunday(d, string, i) { var n = numberRe.exec(string.slice(i)); return n ? (d.U = +n[0], i + n[0].length) : -1; } function parseWeekNumberMonday(d, string, i) { var n = numberRe.exec(string.slice(i)); return n ? (d.W = +n[0], i + n[0].length) : -1; } function parseFullYear(d, string, i) { var n = numberRe.exec(string.slice(i, i + 4)); return n ? (d.y = +n[0], i + n[0].length) : -1; } function parseYear(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1; } function parseZone(d, string, i) { return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (d.Z = -string, i + 5) // sign differs from getTimezoneOffset! : -1; } function parseMonthNumber(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.m = n[0] - 1, i + n[0].length) : -1; } function parseDayOfMonth(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.d = +n[0], i + n[0].length) : -1; } function parseDayOfYear(d, string, i) { var n = numberRe.exec(string.slice(i, i + 3)); return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1; } function parseHour24(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.H = +n[0], i + n[0].length) : -1; } function parseMinutes(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.M = +n[0], i + n[0].length) : -1; } function parseSeconds(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.S = +n[0], i + n[0].length) : -1; } function parseMilliseconds(d, string, i) { var n = numberRe.exec(string.slice(i, i + 3)); return n ? (d.L = +n[0], i + n[0].length) : -1; } function parseLiteralPercent(d, string, i) { var n = percentRe.exec(string.slice(i, i + 1)); return n ? i + n[0].length : -1; } function formatDayOfMonth(d, p) { return pad(d.getDate(), p, 2); } function formatHour24(d, p) { return pad(d.getHours(), p, 2); } function formatHour12(d, p) { return pad(d.getHours() % 12 || 12, p, 2); } function formatDayOfYear(d, p) { return pad(1 + day.count(year(d), d), p, 3); } function formatMilliseconds(d, p) { return pad(d.getMilliseconds(), p, 3); } function formatMonthNumber(d, p) { return pad(d.getMonth() + 1, p, 2); } function formatMinutes(d, p) { return pad(d.getMinutes(), p, 2); } function formatSeconds(d, p) { return pad(d.getSeconds(), p, 2); } function formatWeekNumberSunday(d, p) { return pad(sunday.count(year(d), d), p, 2); } function formatWeekdayNumber(d) { return d.getDay(); } function formatWeekNumberMonday(d, p) { return pad(monday.count(year(d), d), p, 2); } function formatYear(d, p) { return pad(d.getFullYear() % 100, p, 2); } function formatFullYear(d, p) { return pad(d.getFullYear() % 10000, p, 4); } function formatZone(d) { var z = d.getTimezoneOffset(); return (z > 0 ? "-" : (z *= -1, "+")) + pad(z / 60 | 0, "0", 2) + pad(z % 60, "0", 2); } function formatUTCDayOfMonth(d, p) { return pad(d.getUTCDate(), p, 2); } function formatUTCHour24(d, p) { return pad(d.getUTCHours(), p, 2); } function formatUTCHour12(d, p) { return pad(d.getUTCHours() % 12 || 12, p, 2); } function formatUTCDayOfYear(d, p) { return pad(1 + utcDay.count(utcYear(d), d), p, 3); } function formatUTCMilliseconds(d, p) { return pad(d.getUTCMilliseconds(), p, 3); } function formatUTCMonthNumber(d, p) { return pad(d.getUTCMonth() + 1, p, 2); } function formatUTCMinutes(d, p) { return pad(d.getUTCMinutes(), p, 2); } function formatUTCSeconds(d, p) { return pad(d.getUTCSeconds(), p, 2); } function formatUTCWeekNumberSunday(d, p) { return pad(utcSunday.count(utcYear(d), d), p, 2); } function formatUTCWeekdayNumber(d) { return d.getUTCDay(); } function formatUTCWeekNumberMonday(d, p) { return pad(utcMonday.count(utcYear(d), d), p, 2); } function formatUTCYear(d, p) { return pad(d.getUTCFullYear() % 100, p, 2); } function formatUTCFullYear(d, p) { return pad(d.getUTCFullYear() % 10000, p, 4); } function formatUTCZone() { return "+0000"; } function formatLiteralPercent() { return "%"; } var isoSpecifier = "%Y-%m-%dT%H:%M:%S.%LZ"; function formatIsoNative(date) { return date.toISOString(); } formatIsoNative.parse = function(string) { var date = new Date(string); return isNaN(date) ? null : date; }; formatIsoNative.toString = function() { return isoSpecifier; }; var formatIso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? formatIsoNative : enUs.utcFormat(isoSpecifier); var isoFormat = formatIso; var localeDefinitions = (new Map) .set("ca-ES", caEs) .set("de-DE", deDe) .set("en-CA", enCa) .set("en-GB", enGb) .set("en-US", enUs) .set("es-ES", esEs) .set("fi-FI", fiFi) .set("fr-CA", frCa) .set("fr-FR", frFr) .set("he-IL", heIl) .set("it-IT", itIt) .set("mk-MK", mkMk) .set("nl-NL", nlNl) .set("pl-PL", plPl) .set("pt-BR", ptBr) .set("ru-RU", ruRu) .set("zh-CN", zhCn); var defaultLocale = locale(enUs); exports.format = defaultLocale.format; exports.utcFormat = defaultLocale.utcFormat; function localeFormat(definition) { if (typeof definition === "string") { definition = localeDefinitions.get(definition); if (!definition) return null; } return locale(definition); } ; exports.localeFormat = localeFormat; exports.isoFormat = isoFormat; })); },{}],6:[function(require,module,exports){ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : factory((global.time = {})); }(this, function (exports) { 'use strict'; var t1 = new Date; var t0 = new Date; function newInterval(floori, offseti, count) { function interval(date) { return floori(date = new Date(+date)), date; } interval.floor = interval; interval.round = function(date) { var d0 = new Date(+date), d1 = new Date(date - 1); floori(d0), floori(d1), offseti(d1, 1); return date - d0 < d1 - date ? d0 : d1; }; interval.ceil = function(date) { return floori(date = new Date(date - 1)), offseti(date, 1), date; }; interval.offset = function(date, step) { return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date; }; interval.range = function(start, stop, step) { var range = []; start = new Date(start - 1); stop = new Date(+stop); step = step == null ? 1 : Math.floor(step); if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date offseti(start, 1), floori(start); if (start < stop) range.push(new Date(+start)); while (offseti(start, step), floori(start), start < stop) range.push(new Date(+start)); return range; }; interval.filter = function(test) { return newInterval(function(date) { while (floori(date), !test(date)) date.setTime(date - 1); }, function(date, step) { while (--step >= 0) while (offseti(date, 1), !test(date)); }); }; if (count) interval.count = function(start, end) { t0.setTime(+start), t1.setTime(+end); floori(t0), floori(t1); return Math.floor(count(t0, t1)); }; return interval; } var second = newInterval(function(date) { date.setMilliseconds(0); }, function(date, step) { date.setTime(+date + step * 1e3); }, function(start, end) { return (end - start) / 1e3; }); exports.seconds = second.range; var minute = newInterval(function(date) { date.setSeconds(0, 0); }, function(date, step) { date.setTime(+date + step * 6e4); }, function(start, end) { return (end - start) / 6e4; }); exports.minutes = minute.range; var hour = newInterval(function(date) { date.setMinutes(0, 0, 0); }, function(date, step) { date.setTime(+date + step * 36e5); }, function(start, end) { return (end - start) / 36e5; }); exports.hours = hour.range; var day = newInterval(function(date) { date.setHours(0, 0, 0, 0); }, function(date, step) { date.setDate(date.getDate() + step); }, function(start, end) { return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * 6e4) / 864e5; }); exports.days = day.range; function weekday(i) { return newInterval(function(date) { date.setHours(0, 0, 0, 0); date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7); }, function(date, step) { date.setDate(date.getDate() + step * 7); }, function(start, end) { return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * 6e4) / 6048e5; }); } exports.sunday = weekday(0); exports.sundays = exports.sunday.range; exports.monday = weekday(1); exports.mondays = exports.monday.range; exports.tuesday = weekday(2); exports.tuesdays = exports.tuesday.range; exports.wednesday = weekday(3); exports.wednesdays = exports.wednesday.range; exports.thursday = weekday(4); exports.thursdays = exports.thursday.range; exports.friday = weekday(5); exports.fridays = exports.friday.range; exports.saturday = weekday(6); exports.saturdays = exports.saturday.range; var week = exports.sunday; exports.weeks = week.range; var month = newInterval(function(date) { date.setHours(0, 0, 0, 0); date.setDate(1); }, function(date, step) { date.setMonth(date.getMonth() + step); }, function(start, end) { return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12; }); exports.months = month.range; var year = newInterval(function(date) { date.setHours(0, 0, 0, 0); date.setMonth(0, 1); }, function(date, step) { date.setFullYear(date.getFullYear() + step); }, function(start, end) { return end.getFullYear() - start.getFullYear(); }); exports.years = year.range; var utcSecond = newInterval(function(date) { date.setUTCMilliseconds(0); }, function(date, step) { date.setTime(+date + step * 1e3); }, function(start, end) { return (end - start) / 1e3; }); exports.utcSeconds = utcSecond.range; var utcMinute = newInterval(function(date) { date.setUTCSeconds(0, 0); }, function(date, step) { date.setTime(+date + step * 6e4); }, function(start, end) { return (end - start) / 6e4; }); exports.utcMinutes = utcMinute.range; var utcHour = newInterval(function(date) { date.setUTCMinutes(0, 0, 0); }, function(date, step) { date.setTime(+date + step * 36e5); }, function(start, end) { return (end - start) / 36e5; }); exports.utcHours = utcHour.range; var utcDay = newInterval(function(date) { date.setUTCHours(0, 0, 0, 0); }, function(date, step) { date.setUTCDate(date.getUTCDate() + step); }, function(start, end) { return (end - start) / 864e5; }); exports.utcDays = utcDay.range; function utcWeekday(i) { return newInterval(function(date) { date.setUTCHours(0, 0, 0, 0); date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7); }, function(date, step) { date.setUTCDate(date.getUTCDate() + step * 7); }, function(start, end) { return (end - start) / 6048e5; }); } exports.utcSunday = utcWeekday(0); exports.utcSundays = exports.utcSunday.range; exports.utcMonday = utcWeekday(1); exports.utcMondays = exports.utcMonday.range; exports.utcTuesday = utcWeekday(2); exports.utcTuesdays = exports.utcTuesday.range; exports.utcWednesday = utcWeekday(3); exports.utcWednesdays = exports.utcWednesday.range; exports.utcThursday = utcWeekday(4); exports.utcThursdays = exports.utcThursday.range; exports.utcFriday = utcWeekday(5); exports.utcFridays = exports.utcFriday.range; exports.utcSaturday = utcWeekday(6); exports.utcSaturdays = exports.utcSaturday.range; var utcWeek = exports.utcSunday; exports.utcWeeks = utcWeek.range; var utcMonth = newInterval(function(date) { date.setUTCHours(0, 0, 0, 0); date.setUTCDate(1); }, function(date, step) { date.setUTCMonth(date.getUTCMonth() + step); }, function(start, end) { return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12; }); exports.utcMonths = utcMonth.range; var utcYear = newInterval(function(date) { date.setUTCHours(0, 0, 0, 0); date.setUTCMonth(0, 1); }, function(date, step) { date.setUTCFullYear(date.getUTCFullYear() + step); }, function(start, end) { return end.getUTCFullYear() - start.getUTCFullYear(); }); exports.utcYears = utcYear.range; exports.interval = newInterval; exports.second = second; exports.minute = minute; exports.hour = hour; exports.day = day; exports.week = week; exports.month = month; exports.year = year; exports.utcSecond = utcSecond; exports.utcMinute = utcMinute; exports.utcHour = utcHour; exports.utcDay = utcDay; exports.utcWeek = utcWeek; exports.utcMonth = utcMonth; exports.utcYear = utcYear; })); },{}],7:[function(require,module,exports){ var util = require('../util'), Measures = require('./measures'), Collector = require('./collector'); function Aggregator() { this._cells = {}; this._aggr = []; this._stream = false; } var Flags = Aggregator.Flags = { ADD_CELL: 1, MOD_CELL: 2 }; var proto = Aggregator.prototype; // Parameters proto.stream = function(v) { if (v == null) return this._stream; this._stream = !!v; this._aggr = []; return this; }; // key accessor to use for streaming removes proto.key = function(key) { if (key == null) return this._key; this._key = util.$(key); return this; }; // Input: array of objects of the form // {name: string, get: function} proto.groupby = function(dims) { this._dims = util.array(dims).map(function(d, i) { d = util.isString(d) ? {name: d, get: util.$(d)} : util.isFunction(d) ? {name: util.name(d) || d.name || ('_' + i), get: d} : (d.name && util.isFunction(d.get)) ? d : null; if (d == null) throw 'Invalid groupby argument: ' + d; return d; }); return this.clear(); }; // Input: array of objects of the form // {name: string, ops: [string, ...]} proto.summarize = function(fields) { fields = summarize_args(fields); this._count = true; var aggr = (this._aggr = []), m, f, i, j, op, as, get; for (i=0; i<fields.length; ++i) { for (j=0, m=[], f=fields[i]; j<f.ops.length; ++j) { op = f.ops[j]; if (op !== 'count') this._count = false; as = (f.as && f.as[j]) || (op + (f.name==='*' ? '' : '_'+f.name)); m.push(Measures[op](as)); } get = f.get && util.$(f.get) || (f.name === '*' ? util.identity : util.$(f.name)); aggr.push({ name: f.name, measures: Measures.create( m, this._stream, // streaming remove flag get, // input tuple getter this._assign) // output tuple setter }); } return this.clear(); }; // Convenience method to summarize by count proto.count = function() { return this.summarize({'*':'count'}); }; // Override to perform custom tuple value assignment proto._assign = function(object, name, value) { object[name] = value; }; function summarize_args(fields) { if (util.isArray(fields)) { return fields; } if (fields == null) { return []; } var a = [], name, ops; for (name in fields) { ops = util.array(fields[name]); a.push({name: name, ops: ops}); } return a; } // Cell Management proto.clear = function() { return (this._cells = {}, this); }; proto._cellkey = function(x) { var d = this._dims, n = d.length, i, k = String(d[0].get(x)); for (i=1; i<n; ++i) { k += '|' + d[i].get(x); } return k; }; proto._cell = function(x) { var key = this._dims.length ? this._cellkey(x) : ''; return this._cells[key] || (this._cells[key] = this._newcell(x, key)); }; proto._newcell = function(x, key) { var cell = { num: 0, tuple: this._newtuple(x, key), flag: Flags.ADD_CELL, aggs: {} }; var aggr = this._aggr, i; for (i=0; i<aggr.length; ++i) { cell.aggs[aggr[i].name] = new aggr[i].measures(cell, cell.tuple); } if (cell.collect) { cell.data = new Collector(this._key); } return cell; }; proto._newtuple = function(x) { var dims = this._dims, t = {}, i, n; for (i=0, n=dims.length; i<n; ++i) { t[dims[i].name] = dims[i].get(x); } return this._ingest(t); }; // Override to perform custom tuple ingestion proto._ingest = util.identity; // Process Tuples proto._add = function(x) { var cell = this._cell(x), aggr = this._aggr, i; cell.num += 1; if (!this._count) { // skip if count-only if (cell.collect) cell.data.add(x); for (i=0; i<aggr.length; ++i) { cell.aggs[aggr[i].name].add(x); } } cell.flag |= Flags.MOD_CELL; if (this._on_add) this._on_add(x, cell); }; proto._rem = function(x) { var cell = this._cell(x), aggr = this._aggr, i; cell.num -= 1; if (!this._count) { // skip if count-only if (cell.collect) cell.data.rem(x); for (i=0; i<aggr.length; ++i) { cell.aggs[aggr[i].name].rem(x); } } cell.flag |= Flags.MOD_CELL; if (this._on_rem) this._on_rem(x, cell); }; proto._mod = function(curr, prev) { var cell0 = this._cell(prev), cell1 = this._cell(curr), aggr = this._aggr, i; if (cell0 !== cell1) { cell0.num -= 1; cell1.num += 1; if (cell0.collect) cell0.data.rem(prev); if (cell1.collect) cell1.data.add(curr); } else if (cell0.collect && !util.isObject(curr)) { cell0.data.rem(prev); cell0.data.add(curr); } for (i=0; i<aggr.length; ++i) { cell0.aggs[aggr[i].name].rem(prev); cell1.aggs[aggr[i].name].add(curr); } cell0.flag |= Flags.MOD_CELL; cell1.flag |= Flags.MOD_CELL; if (this._on_mod) this._on_mod(curr, prev, cell0, cell1); }; proto.result = function() { var result = [], aggr = this._aggr, cell, i, k; for (k in this._cells) { cell = this._cells[k]; if (cell.num > 0) { // consolidate collector values if (cell.collect) { cell.data.values(); } // update tuple properties for (i=0; i<aggr.length; ++i) { cell.aggs[aggr[i].name].set(); } // add output tuple result.push(cell.tuple); } else { delete this._cells[k]; } cell.flag = 0; } this._rems = false; return result; }; proto.changes = function(output) { var changes = output || {add:[], rem:[], mod:[]}, aggr = this._aggr, cell, flag, i, k; for (k in this._cells) { cell = this._cells[k]; flag = cell.flag; // consolidate collector values if (cell.collect) { cell.data.values(); } // update tuple properties for (i=0; i<aggr.length; ++i) { cell.aggs[aggr[i].name].set(); } // organize output tuples if (cell.num <= 0) { changes.rem.push(cell.tuple); // if (flag === Flags.MOD_CELL) { ?? delete this._cells[k]; if (this._on_drop) this._on_drop(cell); } else { if (this._on_keep) this._on_keep(cell); if (flag & Flags.ADD_CELL) { changes.add.push(cell.tuple); } else if (flag & Flags.MOD_CELL) { changes.mod.push(cell.tuple); } } cell.flag = 0; } this._rems = false; return changes; }; proto.execute = function(input) { return this.clear().insert(input).result(); }; proto.insert = function(input) { this._consolidate(); for (var i=0; i<input.length; ++i) { this._add(input[i]); } return this; }; proto.remove = function(input) { if (!this._stream) { throw 'Aggregator not configured for streaming removes.' + ' Call stream(true) prior to calling summarize.'; } for (var i=0; i<input.length; ++i) { this._rem(input[i]); } this._rems = true; return this; }; // consolidate removals proto._consolidate = function() { if (!this._rems) return; for (var k in this._cells) { if (this._cells[k].collect) { this._cells[k].data.values(); } } this._rems = false; }; module.exports = Aggregator; },{"../util":29,"./collector":8,"./measures":10}],8:[function(require,module,exports){ var util = require('../util'); var stats = require('../stats'); var REM = '__dl_rem__'; function Collector(key) { this._add = []; this._rem = []; this._key = key || null; this._last = null; } var proto = Collector.prototype; proto.add = function(v) { this._add.push(v); }; proto.rem = function(v) { this._rem.push(v); }; proto.values = function() { this._get = null; if (this._rem.length === 0) return this._add; var a = this._add, r = this._rem, k = this._key, x = Array(a.length - r.length), i, j, n, m; if (!util.isObject(r[0])) { // processing raw values m = stats.count.map(r); for (i=0, j=0, n=a.length; i<n; ++i) { if (m[a[i]] > 0) { m[a[i]] -= 1; } else { x[j++] = a[i]; } } } else if (k) { // has unique key field, so use that m = util.toMap(r, k); for (i=0, j=0, n=a.length; i<n; ++i) { if (!m.hasOwnProperty(k(a[i]))) { x[j++] = a[i]; } } } else { // no unique key, mark tuples directly for (i=0, n=r.length; i<n; ++i) { r[i][REM] = 1; } for (i=0, j=0, n=a.length; i<n; ++i) { if (!a[i][REM]) { x[j++] = a[i]; } } for (i=0, n=r.length; i<n; ++i) { delete r[i][REM]; } } this._rem = []; return (this._add = x); }; // memoizing statistics methods proto.extent = function(get) { if (this._get !== get || !this._ext) { var v = this.values(), i = stats.extent.index(v, get); this._ext = [v[i[0]], v[i[1]]]; this._get = get; } return this._ext; }; proto.argmin = function(get) { return this.extent(get)[0]; }; proto.argmax = function(get) { return this.extent(get)[1]; }; proto.min = function(get) { var m = this.extent(get)[0]; return m ? get(m) : +Infinity; }; proto.max = function(get) { var m = this.extent(get)[1]; return m ? get(m) : -Infinity; }; proto.quartile = function(get) { if (this._get !== get || !this._q) { this._q = stats.quartile(this.values(), get); this._get = get; } return this._q; }; proto.q1 = function(get) { return this.quartile(get)[0]; }; proto.q2 = function(get) { return this.quartile(get)[1]; }; proto.q3 = function(get) { return this.quartile(get)[2]; }; module.exports = Collector; },{"../stats":26,"../util":29}],9:[function(require,module,exports){ var util = require('../util'); var Aggregator = require('./aggregator'); module.exports = function() { // flatten arguments into a single array var args = [].reduce.call(arguments, function(a, x) { return a.concat(util.array(x)); }, []); // create and return an aggregator return new Aggregator() .groupby(args) .summarize({'*':'values'}); }; },{"../util":29,"./aggregator":7}],10:[function(require,module,exports){ var util = require('../util'); var types = { 'values': measure({ name: 'values', init: 'cell.collect = true;', set: 'cell.data.values()', idx: -1 }), 'count': measure({ name: 'count', set: 'cell.num' }), 'missing': measure({ name: 'missing', set: 'this.missing' }), 'valid': measure({ name: 'valid', set: 'this.valid' }), 'sum': measure({ name: 'sum', init: 'this.sum = 0;', add: 'this.sum += v;', rem: 'this.sum -= v;', set: 'this.sum' }), 'mean': measure({ name: 'mean', init: 'this.mean = 0;', add: 'var d = v - this.mean; this.mean += d / this.valid;', rem: 'var d = v - this.mean; this.mean -= this.valid ? d / this.valid : this.mean;', set: 'this.mean' }), 'average': measure({ name: 'average', set: 'this.mean', req: ['mean'], idx: 1 }), 'variance': measure({ name: 'variance', init: 'this.dev = 0;', add: 'this.dev += d * (v - this.mean);', rem: 'this.dev -= d * (v - this.mean);', set: 'this.valid > 1 ? this.dev / (this.valid-1) : 0', req: ['mean'], idx: 1 }), 'variancep': measure({ name: 'variancep', set: 'this.valid > 1 ? this.dev / this.valid : 0', req: ['variance'], idx: 2 }), 'stdev': measure({ name: 'stdev', set: 'this.valid > 1 ? Math.sqrt(this.dev / (this.valid-1)) : 0', req: ['variance'], idx: 2 }), 'stdevp': measure({ name: 'stdevp', set: 'this.valid > 1 ? Math.sqrt(this.dev / this.valid) : 0', req: ['variance'], idx: 2 }), 'median': measure({ name: 'median', set: 'cell.data.q2(this.get)', req: ['values'], idx: 3 }), 'q1': measure({ name: 'q1', set: 'cell.data.q1(this.get)', req: ['values'], idx: 3 }), 'q3': measure({ name: 'q3', set: 'cell.data.q3(this.get)', req: ['values'], idx: 3 }), 'distinct': measure({ name: 'distinct', set: 'this.distinct(cell.data.values(), this.get)', req: ['values'], idx: 3 }), 'argmin': measure({ name: 'argmin', add: 'if (v < this.min) this.argmin = t;', rem: 'if (v <= this.min) this.argmin = null;', set: 'this.argmin = this.argmin || cell.data.argmin(this.get)', req: ['min'], str: ['values'], idx: 3 }), 'argmax': measure({ name: 'argmax', add: 'if (v > this.max) this.argmax = t;', rem: 'if (v >= this.max) this.argmax = null;', set: 'this.argmax = this.argmax || cell.data.argmax(this.get)', req: ['max'], str: ['values'], idx: 3 }), 'min': measure({ name: 'min', init: 'this.min = +Infinity;', add: 'if (v < this.min) this.min = v;', rem: 'if (v <= this.min) this.min = NaN;', set: 'this.min = (isNaN(this.min) ? cell.data.min(this.get) : this.min)', str: ['values'], idx: 4 }), 'max': measure({ name: 'max', init: 'this.max = -Infinity;', add: 'if (v > this.max) this.max = v;', rem: 'if (v >= this.max) this.max = NaN;', set: 'this.max = (isNaN(this.max) ? cell.data.max(this.get) : this.max)', str: ['values'], idx: 4 }), 'modeskew': measure({ name: 'modeskew', set: 'this.dev===0 ? 0 : (this.mean - cell.data.q2(this.get)) / Math.sqrt(this.dev/(this.valid-1))', req: ['mean', 'stdev', 'median'], idx: 5 }) }; function measure(base) { return function(out) { var m = util.extend({init:'', add:'', rem:'', idx:0}, base); m.out = out || base.name; return m; }; } function resolve(agg, stream) { function collect(m, a) { function helper(r) { if (!m[r]) collect(m, m[r] = types[r]()); } if (a.req) a.req.forEach(helper); if (stream && a.str) a.str.forEach(helper); return m; } var map = agg.reduce( collect, agg.reduce(function(m, a) { return (m[a.name] = a, m); }, {}) ); return util.vals(map).sort(function(a, b) { return a.idx - b.idx; }); } function create(agg, stream, accessor, mutator) { var all = resolve(agg, stream), ctr = 'this.cell = cell; this.tuple = t; this.valid = 0; this.missing = 0;', add = 'if (v==null) this.missing++; if (!this.isValid(v)) return; ++this.valid;', rem = 'if (v==null) this.missing--; if (!this.isValid(v)) return; --this.valid;', set = 'var t = this.tuple; var cell = this.cell;'; all.forEach(function(a) { if (a.idx < 0) { ctr = a.init + ctr; add = a.add + add; rem = a.rem + rem; } else { ctr += a.init; add += a.add; rem += a.rem; } }); agg.slice() .sort(function(a, b) { return a.idx - b.idx; }) .forEach(function(a) { set += 'this.assign(t,\''+a.out+'\','+a.set+');'; }); set += 'return t;'; /* jshint evil: true */ ctr = Function('cell', 't', ctr); ctr.prototype.assign = mutator; ctr.prototype.add = Function('t', 'var v = this.get(t);' + add); ctr.prototype.rem = Function('t', 'var v = this.get(t);' + rem); ctr.prototype.set = Function(set); ctr.prototype.get = accessor; ctr.prototype.distinct = require('../stats').count.distinct; ctr.prototype.isValid = util.isValid; ctr.fields = agg.map(util.$('out')); return ctr; } types.create = create; module.exports = types; },{"../stats":26,"../util":29}],11:[function(require,module,exports){ var util = require('../util'), time = require('../time'), EPSILON = 1e-15; function bins(opt) { if (!opt) { throw Error("Missing binning options."); } // determine range var maxb = opt.maxbins || 15, base = opt.base || 10, logb = Math.log(base), div = opt.div || [5, 2], min = opt.min, max = opt.max, span = max - min, step, level, minstep, precision, v, i, eps; if (opt.step) { // if step size is explicitly given, use that step = opt.step; } else if (opt.steps) { // if provided, limit choice to acceptable step sizes step = opt.steps[Math.min( opt.steps.length - 1, bisect(opt.steps, span/maxb, 0, opt.steps.length) )]; } else { // else use span to determine step size level = Math.ceil(Math.log(maxb) / logb); minstep = opt.minstep || 0; step = Math.max( minstep, Math.pow(base, Math.round(Math.log(span) / logb) - level) ); // increase step size if too many bins do { step *= base; } while (Math.ceil(span/step) > maxb); // decrease step size if allowed for (i=0; i<div.length; ++i) { v = step / div[i]; if (v >= minstep && span / v <= maxb) step = v; } } // update precision, min and max v = Math.log(step); precision = v >= 0 ? 0 : ~~(-v / logb) + 1; eps = Math.pow(base, -precision - 1); min = Math.min(min, Math.floor(min / step + eps) * step); max = Math.ceil(max / step) * step; return { start: min, stop: max, step: step, unit: {precision: precision}, value: value, index: index }; } function bisect(a, x, lo, hi) { while (lo < hi) { var mid = lo + hi >>> 1; if (util.cmp(a[mid], x) < 0) { lo = mid + 1; } else { hi = mid; } } return lo; } function value(v) { return this.step * Math.floor(v / this.step + EPSILON); } function index(v) { return Math.floor((v - this.start) / this.step + EPSILON); } function date_value(v) { return this.unit.date(value.call(this, v)); } function date_index(v) { return index.call(this, this.unit.unit(v)); } bins.date = function(opt) { if (!opt) { throw Error("Missing date binning options."); } // find time step, then bin var units = opt.utc ? time.utc : time, dmin = opt.min, dmax = opt.max, maxb = opt.maxbins || 20, minb = opt.minbins || 4, span = (+dmax) - (+dmin), unit = opt.unit ? units[opt.unit] : units.find(span, minb, maxb), spec = bins({ min: unit.min != null ? unit.min : unit.unit(dmin), max: unit.max != null ? unit.max : unit.unit(dmax), maxbins: maxb, minstep: unit.minstep, steps: unit.step }); spec.unit = unit; spec.index = date_index; if (!opt.raw) spec.value = date_value; return spec; }; module.exports = bins; },{"../time":28,"../util":29}],12:[function(require,module,exports){ var bins = require('./bins'), gen = require('../generate'), type = require('../import/type'), util = require('../util'), stats = require('../stats'); var qtype = { 'integer': 1, 'number': 1, 'date': 1 }; function $bin(values, f, opt) { opt = options(values, f, opt); var b = spec(opt); return !b ? (opt.accessor || util.identity) : util.$func('bin', b.unit.unit ? function(x) { return b.value(b.unit.unit(x)); } : function(x) { return b.value(x); } )(opt.accessor); } function histogram(values, f, opt) { opt = options(values, f, opt); var b = spec(opt); return b ? numerical(values, opt.accessor, b) : categorical(values, opt.accessor, opt && opt.sort); } function spec(opt) { var t = opt.type, b = null; if (t == null || qtype[t]) { if (t === 'integer' && opt.minstep == null) opt.minstep = 1; b = (t === 'date') ? bins.date(opt) : bins(opt); } return b; } function options() { var a = arguments, i = 0, values = util.isArray(a[i]) ? a[i++] : null, f = util.isFunction(a[i]) || util.isString(a[i]) ? util.$(a[i++]) : null, opt = util.extend({}, a[i]); if (values) { opt.type = opt.type || type(values, f); if (qtype[opt.type]) { var ext = stats.extent(values, f); opt = util.extend({min: ext[0], max: ext[1]}, opt); } } if (f) { opt.accessor = f; } return opt; } function numerical(values, f, b) { var h = gen.range(b.start, b.stop + b.step/2, b.step) .map(function(v) { return {value: b.value(v), count: 0}; }); for (var i=0, v, j; i<values.length; ++i) { v = f ? f(values[i]) : values[i]; if (util.isValid(v)) { j = b.index(v); if (j < 0 || j >= h.length || !isFinite(j)) continue; h[j].count += 1; } } h.bins = b; return h; } function categorical(values, f, sort) { var u = stats.unique(values, f), c = stats.count.map(values, f); return u.map(function(k) { return {value: k, count: c[k]}; }) .sort(util.comparator(sort ? '-count' : '+value')); } module.exports = { $bin: $bin, histogram: histogram }; },{"../generate":14,"../import/type":23,"../stats":26,"../util":29,"./bins":11}],13:[function(require,module,exports){ var d3_time = require('d3-time'), d3_timeF = require('d3-time-format'), d3_numberF = require('d3-format'), numberF = d3_numberF, // defaults to EN-US timeF = d3_timeF; // defaults to EN-US function numberLocale(l) { var f = d3_numberF.localeFormat(l); if (f == null) throw Error('Unrecognized locale: ' + l); numberF = f; } function timeLocale(l) { var f = d3_timeF.localeFormat(l); if (f == null) throw Error('Unrecognized locale: ' + l); timeF = f; } module.exports = { // Update number formatter to use provided locale configuration. // For more see https://github.com/d3/d3-format numberLocale: numberLocale, number: function(f) { return numberF.format(f); }, numberPrefix: function(f, v) { return numberF.formatPrefix(f, v); }, // Update time formatter to use provided locale configuration. // For more see https://github.com/d3/d3-time-format timeLocale: timeLocale, time: function(f) { return timeF.format(f); }, utc: function(f) { return timeF.utcFormat(f); }, // Set number and time locale simultaneously. locale: function(l) { numberLocale(l); timeLocale(l); }, // automatic formatting functions auto: { number: numberAutoFormat, time: function() { return timeAutoFormat(); }, utc: function() { return utcAutoFormat(); } } }; var e10 = Math.sqrt(50), e5 = Math.sqrt(10), e2 = Math.sqrt(2); function intervals(domain, count) { if (count == null) count = 10; var start = domain[0], stop = domain[domain.length - 1]; if (stop < start) { error = stop; stop = start; start = error; } var span = stop - start, step = Math.pow(10, Math.floor(Math.log(span / count) / Math.LN10)), error = span / count / step; // Filter ticks to get closer to the desired count. if (error >= e10) step *= 10; else if (error >= e5) step *= 5; else if (error >= e2) step *= 2; // Round start and stop values to step interval. return [ Math.ceil(start / step) * step, Math.floor(stop / step) * step + step / 2, // inclusive step ]; } function numberAutoFormat(domain, count, f) { var range = intervals(domain, count); if (f == null) { f = ',.' + d3_numberF.precisionFixed(range[2]) + 'f'; } else { switch (f = d3_numberF.formatSpecifier(f), f.type) { case 's': { var value = Math.max(Math.abs(range[0]), Math.abs(range[1])); if (f.precision == null) f.precision = d3_numberF.precisionPrefix(range[2], value); return numberF.formatPrefix(f, value); } case '': case 'e': case 'g': case 'p': case 'r': { if (f.precision == null) f.precision = d3_numberF.precisionRound(range[2], Math.max(Math.abs(range[0]), Math.abs(range[1]))) - (f.type === 'e'); break; } case 'f': case '%': { if (f.precision == null) f.precision = d3_numberF.precisionFixed(range[2]) - (f.type === '%') * 2; break; } } } return numberF.format(f); } function timeAutoFormat() { var f = timeF.format, formatMillisecond = f('.%L'), formatSecond = f(':%S'), formatMinute = f('%I:%M'), formatHour = f('%I %p'), formatDay = f('%a %d'), formatWeek = f('%b %d'), formatMonth = f('%B'), formatYear = f('%Y'); return function(date) { var d = +date; return (d3_time.second(date) < d ? formatMillisecond : d3_time.minute(date) < d ? formatSecond : d3_time.hour(date) < d ? formatMinute : d3_time.day(date) < d ? formatHour : d3_time.month(date) < d ? (d3_time.week(date) < d ? formatDay : formatWeek) : d3_time.year(date) < d ? formatMonth : formatYear)(date); }; } function utcAutoFormat() { var f = timeF.utcFormat, formatMillisecond = f('.%L'), formatSecond = f(':%S'), formatMinute = f('%I:%M'), formatHour = f('%I %p'), formatDay = f('%a %d'), formatWeek = f('%b %d'), formatMonth = f('%B'), formatYear = f('%Y'); return function(date) { var d = +date; return (d3_time.utcSecond(date) < d ? formatMillisecond : d3_time.utcMinute(date) < d ? formatSecond : d3_time.utcHour(date) < d ? formatMinute : d3_time.utcDay(date) < d ? formatHour : d3_time.utcMonth(date) < d ? (d3_time.utcWeek(date) < d ? formatDay : formatWeek) : d3_time.utcYear(date) < d ? formatMonth : formatYear)(date); }; } },{"d3-format":4,"d3-time":6,"d3-time-format":5}],14:[function(require,module,exports){ var gen = module.exports = {}; gen.repeat = function(val, n) { var a = Array(n), i; for (i=0; i<n; ++i) a[i] = val; return a; }; gen.zeros = function(n) { return gen.repeat(0, n); }; gen.range = function(start, stop, step) { if (arguments.length < 3) { step = 1; if (arguments.length < 2) { stop = start; start = 0; } } if ((stop - start) / step == Infinity) throw new Error('Infinite range'); var range = [], i = -1, j; if (step < 0) while ((j = start + step * ++i) > stop) range.push(j); else while ((j = start + step * ++i) < stop) range.push(j); return range; }; gen.random = {}; gen.random.uniform = function(min, max) { if (max === undefined) { max = min === undefined ? 1 : min; min = 0; } var d = max - min; var f = function() { return min + d * Math.random(); }; f.samples = function(n) { return gen.zeros(n).map(f); }; return f; }; gen.random.integer = function(a, b) { if (b === undefined) { b = a; a = 0; } var d = b - a; var f = function() { return a + Math.floor(d * Math.random()); }; f.samples = function(n) { return gen.zeros(n).map(f); }; return f; }; gen.random.normal = function(mean, stdev) { mean = mean || 0; stdev = stdev || 1; var next; var f = function() { var x = 0, y = 0, rds, c; if (next !== undefined) { x = next; next = undefined; return x; } do { x = Math.random()*2-1; y = Math.random()*2-1; rds = x*x + y*y; } while (rds === 0 || rds > 1); c = Math.sqrt(-2*Math.log(rds)/rds); // Box-Muller transform next = mean + y*c*stdev; return mean + x*c*stdev; }; f.samples = function(n) { return gen.zeros(n).map(f); }; return f; }; },{}],15:[function(require,module,exports){ var util = require('../../util'); var d3_dsv = require('d3-dsv'); function dsv(data, format) { if (data) { var h = format.header; data = (h ? h.join(format.delimiter) + '\n' : '') + data; } return d3_dsv.dsv(format.delimiter).parse(data); } dsv.delimiter = function(delim) { var fmt = {delimiter: delim}; return function(data, format) { return dsv(data, format ? util.extend(format, fmt) : fmt); }; }; module.exports = dsv; },{"../../util":29,"d3-dsv":3}],16:[function(require,module,exports){ var dsv = require('./dsv'); module.exports = { json: require('./json'), topojson: require('./topojson'), treejson: require('./treejson'), dsv: dsv, csv: dsv.delimiter(','), tsv: dsv.delimiter('\t') }; },{"./dsv":15,"./json":17,"./topojson":18,"./treejson":19}],17:[function(require,module,exports){ var util = require('../../util'); module.exports = function(data, format) { var d = util.isObject(data) && !util.isBuffer(data) ? data : JSON.parse(data); if (format && format.property) { d = util.accessor(format.property)(d); } return d; }; },{"../../util":29}],18:[function(require,module,exports){ (function (global){ var json = require('./json'); var reader = function(data, format) { var topojson = reader.topojson; if (topojson == null) { throw Error('TopoJSON library not loaded.'); } var t = json(data, format), obj; if (format && format.feature) { if ((obj = t.objects[format.feature])) { return topojson.feature(t, obj).features; } else { throw Error('Invalid TopoJSON object: ' + format.feature); } } else if (format && format.mesh) { if ((obj = t.objects[format.mesh])) { return [topojson.mesh(t, t.objects[format.mesh])]; } else { throw Error('Invalid TopoJSON object: ' + format.mesh); } } else { throw Error('Missing TopoJSON feature or mesh parameter.'); } }; reader.topojson = (typeof window !== "undefined" ? window['topojson'] : typeof global !== "undefined" ? global['topojson'] : null); module.exports = reader; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./json":17}],19:[function(require,module,exports){ var json = require('./json'); module.exports = function(data, format) { data = json(data, format); return toTable(data, (format && format.children)); }; function toTable(root, childrenField) { childrenField = childrenField || 'children'; var table = []; function visit(node) { table.push(node); var children = node[childrenField]; if (children) { for (var i=0; i<children.length; ++i) { visit(children[i], node); } } } visit(root, null); return (table.root = root, table); } },{"./json":17}],20:[function(require,module,exports){ // Matches absolute URLs with optional protocol // https://... file://... //... var protocol_re = /^([A-Za-z]+:)?\/\//; // Special treatment in node.js for the file: protocol var fileProtocol = 'file://'; // Validate and cleanup URL to ensure that it is allowed to be accessed // Returns cleaned up URL, or false if access is not allowed function sanitizeUrl(opt) { var url = opt.url; if (!url && opt.file) { return fileProtocol + opt.file; } // In case this is a relative url (has no host), prepend opt.baseURL if (opt.baseURL && !protocol_re.test(url)) { if (!startsWith(url, '/') && opt.baseURL[opt.baseURL.length-1] !== '/') { url = '/' + url; // Ensure that there is a slash between the baseURL (e.g. hostname) and url } url = opt.baseURL + url; } // relative protocol, starts with '//' if (!load.useXHR && startsWith(url, '//')) { url = (opt.defaultProtocol || 'http') + ':' + url; } // If opt.domainWhiteList is set, only allows url, whose hostname // * Is the same as the origin (window.location.hostname) // * Equals one of the values in the whitelist // * Is a proper subdomain of one of the values in the whitelist if (opt.domainWhiteList) { var domain, origin; if (load.useXHR) { var a = document.createElement('a'); a.href = url; // From http://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript // IE doesn't populate all link properties when setting .href with a relative URL, // however .href will return an absolute URL which then can be used on itself // to populate these additional fields. if (a.host === '') { a.href = a.href; } domain = a.hostname.toLowerCase(); origin = window.location.hostname; } else { // relative protocol is broken: https://github.com/defunctzombie/node-url/issues/5 var parts = require('url').parse(url); domain = parts.hostname; origin = null; } if (origin !== domain) { var whiteListed = opt.domainWhiteList.some(function(d) { var idx = domain.length - d.length; return d === domain || (idx > 1 && domain[idx-1] === '.' && domain.lastIndexOf(d) === idx); }); if (!whiteListed) { throw 'URL is not whitelisted: ' + url; } } } return url; } function load(opt, callback) { var error = callback || function(e) { throw e; }, url; try { url = load.sanitizeUrl(opt); // enable override } catch (err) { error(err); return; } if (!url) { error('Invalid URL: ' + opt.url); } else if (load.useXHR) { // on client, use xhr return xhr(url, callback); } else if (startsWith(url, fileProtocol)) { // on server, if url starts with 'file://', strip it and load from file return file(url.slice(fileProtocol.length), callback); } else if (url.indexOf('://') < 0) { // TODO better protocol check? // on server, if no protocol assume file return file(url, callback); } else { // for regular URLs on server return http(url, callback); } } function xhrHasResponse(request) { var type = request.responseType; return type && type !== 'text' ? request.response : // null on error request.responseText; // '' on error } function xhr(url, callback) { var async = !!callback; var request = new XMLHttpRequest(); // If IE does not support CORS, use XDomainRequest (copied from d3.xhr) if (this.XDomainRequest && !('withCredentials' in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest(); function respond() { var status = request.status; if (!status && xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) { callback(null, request.responseText); } else { callback(request, null); } } if (async) { if ('onload' in request) { request.onload = request.onerror = respond; } else { request.onreadystatechange = function() { if (request.readyState > 3) respond(); }; } } request.open('GET', url, async); request.send(); if (!async && xhrHasResponse(request)) { return request.responseText; } } function file(filename, callback) { var fs = require('fs'); if (!callback) { return fs.readFileSync(filename, 'utf8'); } fs.readFile(filename, callback); } function http(url, callback) { if (!callback) { return require('sync-request')('GET', url).getBody(); } var options = {url: url, encoding: null, gzip: true}; require('request')(options, function(error, response, body) { if (!error && response.statusCode === 200) { callback(null, body); } else { error = error || 'Load failed with response code ' + response.statusCode + '.'; callback(error, null); } }); } function startsWith(string, searchString) { return string == null ? false : string.lastIndexOf(searchString, 0) === 0; } load.sanitizeUrl = sanitizeUrl; load.useXHR = (typeof XMLHttpRequest !== 'undefined'); module.exports = load; },{"fs":2,"request":2,"sync-request":2,"url":2}],21:[function(require,module,exports){ var util = require('../util'); var type = require('./type'); var formats = require('./formats'); function read(data, format) { var type = (format && format.type) || 'json'; data = formats[type](data, format); if (format && format.parse) parse(data, format.parse); return data; } function parse(data, types) { var cols, parsers, d, i, j, clen, len = data.length; types = (types==='auto') ? type.inferAll(data) : util.duplicate(types); cols = util.keys(types); parsers = cols.map(function(c) { return type.parsers[types[c]]; }); for (i=0, clen=cols.length; i<len; ++i) { d = data[i]; for (j=0; j<clen; ++j) { d[cols[j]] = parsers[j](d[cols[j]]); } } type.annotation(data, types); } read.formats = formats; module.exports = read; },{"../util":29,"./formats":16,"./type":23}],22:[function(require,module,exports){ var util = require('../util'); var load = require('./load'); var read = require('./read'); module.exports = util .keys(read.formats) .reduce(function(out, type) { out[type] = function(opt, format, callback) { // process arguments if (util.isString(opt)) { opt = {url: opt}; } if (arguments.length === 2 && util.isFunction(format)) { callback = format; format = undefined; } // set up read format format = util.extend({parse: 'auto'}, format); format.type = type; // load data var data = load(opt, callback ? function(error, data) { if (error) { callback(error, null); return; } try { // data loaded, now parse it (async) data = read(data, format); callback(null, data); } catch (e) { callback(e, null); } } : undefined); // data loaded, now parse it (sync) if (!callback) return read(data, format); }; return out; }, {}); },{"../util":29,"./load":20,"./read":21}],23:[function(require,module,exports){ var util = require('../util'); var TYPES = '__types__'; var PARSERS = { boolean: util.boolean, integer: util.number, number: util.number, date: util.date, string: function(x) { return x==='' ? null : x; } }; var TESTS = { boolean: function(x) { return x==='true' || x==='false' || util.isBoolean(x); }, integer: function(x) { return TESTS.number(x) && (x=+x) === ~~x; }, number: function(x) { return !isNaN(+x) && !util.isDate(x); }, date: function(x) { return !isNaN(Date.parse(x)); } }; function annotation(data, types) { if (!types) return data && data[TYPES] || null; data[TYPES] = types; } function type(values, f) { f = util.$(f); var v, i, n; // if data array has type annotations, use them if (values[TYPES]) { v = f(values[TYPES]); if (util.isString(v)) return v; } for (i=0, n=values.length; !util.isValid(v) && i<n; ++i) { v = f ? f(values[i]) : values[i]; } return util.isDate(v) ? 'date' : util.isNumber(v) ? 'number' : util.isBoolean(v) ? 'boolean' : util.isString(v) ? 'string' : null; } function typeAll(data, fields) { if (!data.length) return; fields = fields || util.keys(data[0]); return fields.reduce(function(types, f) { return (types[f] = type(data, f), types); }, {}); } function infer(values, f) { f = util.$(f); var i, j, v; // types to test for, in precedence order var types = ['boolean', 'integer', 'number', 'date']; for (i=0; i<values.length; ++i) { // get next value to test v = f ? f(values[i]) : values[i]; // test value against remaining types for (j=0; j<types.length; ++j) { if (util.isValid(v) && !TESTS[types[j]](v)) { types.splice(j, 1); j -= 1; } } // if no types left, return 'string' if (types.length === 0) return 'string'; } return types[0]; } function inferAll(data, fields) { fields = fields || util.keys(data[0]); return fields.reduce(function(types, f) { types[f] = infer(data, f); return types; }, {}); } type.annotation = annotation; type.all = typeAll; type.infer = infer; type.inferAll = inferAll; type.parsers = PARSERS; module.exports = type; },{"../util":29}],24:[function(require,module,exports){ var util = require('./util'); var dl = { version: '1.4.5', load: require('./import/load'), read: require('./import/read'), type: require('./import/type'), Aggregator: require('./aggregate/aggregator'), groupby: require('./aggregate/groupby'), bins: require('./bins/bins'), $bin: require('./bins/histogram').$bin, histogram: require('./bins/histogram').histogram, format: require('./format'), print: require('./print'), template: require('./template'), time: require('./time') }; util.extend(dl, util); util.extend(dl, require('./generate')); util.extend(dl, require('./stats')); util.extend(dl, require('./import/readers')); module.exports = dl; },{"./aggregate/aggregator":7,"./aggregate/groupby":9,"./bins/bins":11,"./bins/histogram":12,"./format":13,"./generate":14,"./import/load":20,"./import/read":21,"./import/readers":22,"./import/type":23,"./print":25,"./stats":26,"./template":27,"./time":28,"./util":29}],25:[function(require,module,exports){ var util = require('./util'); var type = require('./import/type'); var stats = require('./stats'); var template = require('./template'); var FMT = { 'date': '|time:"%m/%d/%Y %H:%M:%S"', 'number': '|number:".4f"', 'integer': '|number:"d"' }; var POS = { 'number': 'left', 'integer': 'left' }; module.exports.table = function(data, opt) { opt = util.extend({separator:' ', minwidth: 8, maxwidth: 15}, opt); var fields = opt.fields || util.keys(data[0]), types = type.all(data); if (opt.start || opt.limit) { var a = opt.start || 0, b = opt.limit ? a + opt.limit : data.length; data = data.slice(a, b); } // determine char width of fields var lens = fields.map(function(name) { var format = FMT[types[name]] || '', t = template('{{' + name + format + '}}'), l = stats.max(data, function(x) { return t(x).length; }); l = Math.max(Math.min(name.length, opt.minwidth), l); return opt.maxwidth > 0 ? Math.min(l, opt.maxwidth) : l; }); // print header row var head = fields.map(function(name, i) { return util.truncate(util.pad(name, lens[i], 'center'), lens[i]); }).join(opt.separator); // build template function for each row var tmpl = template(fields.map(function(name, i) { return '{{' + name + (FMT[types[name]] || '') + ('|pad:' + lens[i] + ',' + (POS[types[name]] || 'right')) + ('|truncate:' + lens[i]) + '}}'; }).join(opt.separator)); // print table return head + "\n" + data.map(tmpl).join('\n'); }; module.exports.summary = function(s) { s = s ? s.__summary__ ? s : stats.summary(s) : this; var str = [], i, n; for (i=0, n=s.length; i<n; ++i) { str.push('-- ' + s[i].field + ' --'); if (s[i].type === 'string' || s[i].distinct < 10) { str.push(printCategoricalProfile(s[i])); } else { str.push(printQuantitativeProfile(s[i])); } str.push(''); } return str.join('\n'); }; function printQuantitativeProfile(p) { return [ 'valid: ' + p.valid, 'missing: ' + p.missing, 'distinct: ' + p.distinct, 'min: ' + p.min, 'max: ' + p.max, 'median: ' + p.median, 'mean: ' + p.mean, 'stdev: ' + p.stdev, 'modeskew: ' + p.modeskew ].join('\n'); } function printCategoricalProfile(p) { var list = [ 'valid: ' + p.valid, 'missing: ' + p.missing, 'distinct: ' + p.distinct, 'top values: ' ]; var u = p.unique; var top = util.keys(u) .sort(function(a,b) { return u[b] - u[a]; }) .slice(0, 6) .map(function(v) { return ' \'' + v + '\' (' + u[v] + ')'; }); return list.concat(top).join('\n'); } },{"./import/type":23,"./stats":26,"./template":27,"./util":29}],26:[function(require,module,exports){ var util = require('./util'); var type = require('./import/type'); var gen = require('./generate'); var stats = {}; // Collect unique values. // Output: an array of unique values, in first-observed order stats.unique = function(values, f, results) { f = util.$(f); results = results || []; var u = {}, v, i, n; for (i=0, n=values.length; i<n; ++i) { v = f ? f(values[i]) : values[i]; if (v in u) continue; u[v] = 1; results.push(v); } return results; }; // Return the length of the input array. stats.count = function(values) { return values && values.length || 0; }; // Count the number of non-null, non-undefined, non-NaN values. stats.count.valid = function(values, f) { f = util.$(f); var v, i, n, valid = 0; for (i=0, n=values.length; i<n; ++i) { v = f ? f(values[i]) : values[i]; if (util.isValid(v)) valid += 1; } return valid; }; // Count the number of null or undefined values. stats.count.missing = function(values, f) { f = util.$(f); var v, i, n, count = 0; for (i=0, n=values.length; i<n; ++i) { v = f ? f(values[i]) : values[i]; if (v == null) count += 1; } return count; }; // Count the number of distinct values. // Null, undefined and NaN are each considered distinct values. stats.count.distinct = function(values, f) { f = util.$(f); var u = {}, v, i, n, count = 0; for (i=0, n=values.length; i<n; ++i) { v = f ? f(values[i]) : values[i]; if (v in u) continue; u[v] = 1; count += 1; } return count; }; // Construct a map from distinct values to occurrence counts. stats.count.map = function(values, f) { f = util.$(f); var map = {}, v, i, n; for (i=0, n=values.length; i<n; ++i) { v = f ? f(values[i]) : values[i]; map[v] = (v in map) ? map[v] + 1 : 1; } return map; }; // Compute the median of an array of numbers. stats.median = function(values, f) { if (f) values = values.map(util.$(f)); values = values.filter(util.isValid).sort(util.cmp); return stats.quantile(values, 0.5); }; // Computes the quartile boundaries of an array of numbers. stats.quartile = function(values, f) { if (f) values = values.map(util.$(f)); values = values.filter(util.isValid).sort(util.cmp); var q = stats.quantile; return [q(values, 0.25), q(values, 0.50), q(values, 0.75)]; }; // Compute the quantile of a sorted array of numbers. // Adapted from the D3.js implementation. stats.quantile = function(values, f, p) { if (p === undefined) { p = f; f = util.identity; } f = util.$(f); var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +f(values[h - 1]), e = H - h; return e ? v + e * (f(values[h]) - v) : v; }; // Compute the sum of an array of numbers. stats.sum = function(values, f) { f = util.$(f); for (var sum=0, i=0, n=values.length, v; i<n; ++i) { v = f ? f(values[i]) : values[i]; if (util.isValid(v)) sum += v; } return sum; }; // Compute the mean (average) of an array of numbers. stats.mean = function(values, f) { f = util.$(f); var mean = 0, delta, i, n, c, v; for (i=0, c=0, n=values.length; i<n; ++i) { v = f ? f(values[i]) : values[i]; if (util.isValid(v)) { delta = v - mean; mean = mean + delta / (++c); } } return mean; }; // Compute the sample variance of an array of numbers. stats.variance = function(values, f) { f = util.$(f); if (!util.isArray(values) || values.length < 2) return 0; var mean = 0, M2 = 0, delta, i, c, v; for (i=0, c=0; i<values.length; ++i) { v = f ? f(values[i]) : values[i]; if (util.isValid(v)) { delta = v - mean; mean = mean + delta / (++c); M2 = M2 + delta * (v - mean); } } M2 = M2 / (c - 1); return M2; }; // Compute the sample standard deviation of an array of numbers. stats.stdev = function(values, f) { return Math.sqrt(stats.variance(values, f)); }; // Compute the Pearson mode skewness ((median-mean)/stdev) of an array of numbers. stats.modeskew = function(values, f) { var avg = stats.mean(values, f), med = stats.median(values, f), std = stats.stdev(values, f); return std === 0 ? 0 : (avg - med) / std; }; // Find the minimum value in an array. stats.min = function(values, f) { return stats.extent(values, f)[0]; }; // Find the maximum value in an array. stats.max = function(values, f) { return stats.extent(values, f)[1]; }; // Find the minimum and maximum of an array of values. stats.extent = function(values, f) { f = util.$(f); var a, b, v, i, n = values.length; for (i=0; i<n; ++i) { v = f ? f(values[i]) : values[i]; if (util.isValid(v)) { a = b = v; break; } } for (; i<n; ++i) { v = f ? f(values[i]) : values[i]; if (util.isValid(v)) { if (v < a) a = v; if (v > b) b = v; } } return [a, b]; }; // Find the integer indices of the minimum and maximum values. stats.extent.index = function(values, f) { f = util.$(f); var x = -1, y = -1, a, b, v, i, n = values.length; for (i=0; i<n; ++i) { v = f ? f(values[i]) : values[i]; if (util.isValid(v)) { a = b = v; x = y = i; break; } } for (; i<n; ++i) { v = f ? f(values[i]) : values[i]; if (util.isValid(v)) { if (v < a) { a = v; x = i; } if (v > b) { b = v; y = i; } } } return [x, y]; }; // Compute the dot product of two arrays of numbers. stats.dot = function(values, a, b) { var sum = 0, i, v; if (!b) { if (values.length !== a.length) { throw Error('Array lengths must match.'); } for (i=0; i<values.length; ++i) { v = values[i] * a[i]; if (v === v) sum += v; } } else { a = util.$(a); b = util.$(b); for (i=0; i<values.length; ++i) { v = a(values[i]) * b(values[i]); if (v === v) sum += v; } } return sum; }; // Compute ascending rank scores for an array of values. // Ties are assigned their collective mean rank. stats.rank = function(values, f) { f = util.$(f) || util.identity; var a = values.map(function(v, i) { return {idx: i, val: f(v)}; }) .sort(util.comparator('val')); var n = values.length, r = Array(n), tie = -1, p = {}, i, v, mu; for (i=0; i<n; ++i) { v = a[i].val; if (tie < 0 && p === v) { tie = i - 1; } else if (tie > -1 && p !== v) { mu = 1 + (i-1 + tie) / 2; for (; tie<i; ++tie) r[a[tie].idx] = mu; tie = -1; } r[a[i].idx] = i + 1; p = v; } if (tie > -1) { mu = 1 + (n-1 + tie) / 2; for (; tie<n; ++tie) r[a[tie].idx] = mu; } return r; }; // Compute the sample Pearson product-moment correlation of two arrays of numbers. stats.cor = function(values, a, b) { var fn = b; b = fn ? values.map(util.$(b)) : a; a = fn ? values.map(util.$(a)) : values; var dot = stats.dot(a, b), mua = stats.mean(a), mub = stats.mean(b), sda = stats.stdev(a), sdb = stats.stdev(b), n = values.length; return (dot - n*mua*mub) / ((n-1) * sda * sdb); }; // Compute the Spearman rank correlation of two arrays of values. stats.cor.rank = function(values, a, b) { var ra = b ? stats.rank(values, util.$(a)) : stats.rank(values), rb = b ? stats.rank(values, util.$(b)) : stats.rank(a), n = values.length, i, s, d; for (i=0, s=0; i<n; ++i) { d = ra[i] - rb[i]; s += d * d; } return 1 - 6*s / (n * (n*n-1)); }; // Compute the distance correlation of two arrays of numbers. // http://en.wikipedia.org/wiki/Distance_correlation stats.cor.dist = function(values, a, b) { var X = b ? values.map(util.$(a)) : values, Y = b ? values.map(util.$(b)) : a; var A = stats.dist.mat(X), B = stats.dist.mat(Y), n = A.length, i, aa, bb, ab; for (i=0, aa=0, bb=0, ab=0; i<n; ++i) { aa += A[i]*A[i]; bb += B[i]*B[i]; ab += A[i]*B[i]; } return Math.sqrt(ab / Math.sqrt(aa*bb)); }; // Compute the vector distance between two arrays of numbers. // Default is Euclidean (exp=2) distance, configurable via exp argument. stats.dist = function(values, a, b, exp) { var f = util.isFunction(b) || util.isString(b), X = values, Y = f ? values : a, e = f ? exp : b, L2 = e === 2 || e == null, n = values.length, s = 0, d, i; if (f) { a = util.$(a); b = util.$(b); } for (i=0; i<n; ++i) { d = f ? (a(X[i])-b(Y[i])) : (X[i]-Y[i]); s += L2 ? d*d : Math.pow(Math.abs(d), e); } return L2 ? Math.sqrt(s) : Math.pow(s, 1/e); }; // Construct a mean-centered distance matrix for an array of numbers. stats.dist.mat = function(X) { var n = X.length, m = n*n, A = Array(m), R = gen.zeros(n), M = 0, v, i, j; for (i=0; i<n; ++i) { A[i*n+i] = 0; for (j=i+1; j<n; ++j) { A[i*n+j] = (v = Math.abs(X[i] - X[j])); A[j*n+i] = v; R[i] += v; R[j] += v; } } for (i=0; i<n; ++i) { M += R[i]; R[i] /= n; } M /= m; for (i=0; i<n; ++i) { for (j=i; j<n; ++j) { A[i*n+j] += M - R[i] - R[j]; A[j*n+i] = A[i*n+j]; } } return A; }; // Compute the Shannon entropy (log base 2) of an array of counts. stats.entropy = function(counts, f) { f = util.$(f); var i, p, s = 0, H = 0, n = counts.length; for (i=0; i<n; ++i) { s += (f ? f(counts[i]) : counts[i]); } if (s === 0) return 0; for (i=0; i<n; ++i) { p = (f ? f(counts[i]) : counts[i]) / s; if (p) H += p * Math.log(p); } return -H / Math.LN2; }; // Compute the mutual information between two discrete variables. // Returns an array of the form [MI, MI_distance] // MI_distance is defined as 1 - I(a,b) / H(a,b). // http://en.wikipedia.org/wiki/Mutual_information stats.mutual = function(values, a, b, counts) { var x = counts ? values.map(util.$(a)) : values, y = counts ? values.map(util.$(b)) : a, z = counts ? values.map(util.$(counts)) : b; var px = {}, py = {}, n = z.length, s = 0, I = 0, H = 0, p, t, i; for (i=0; i<n; ++i) { px[x[i]] = 0; py[y[i]] = 0; } for (i=0; i<n; ++i) { px[x[i]] += z[i]; py[y[i]] += z[i]; s += z[i]; } t = 1 / (s * Math.LN2); for (i=0; i<n; ++i) { if (z[i] === 0) continue; p = (s * z[i]) / (px[x[i]] * py[y[i]]); I += z[i] * t * Math.log(p); H += z[i] * t * Math.log(z[i]/s); } return [I, 1 + I/H]; }; // Compute the mutual information between two discrete variables. stats.mutual.info = function(values, a, b, counts) { return stats.mutual(values, a, b, counts)[0]; }; // Compute the mutual information distance between two discrete variables. // MI_distance is defined as 1 - I(a,b) / H(a,b). stats.mutual.dist = function(values, a, b, counts) { return stats.mutual(values, a, b, counts)[1]; }; // Compute a profile of summary statistics for a variable. stats.profile = function(values, f) { var mean = 0, valid = 0, missing = 0, distinct = 0, min = null, max = null, M2 = 0, vals = [], u = {}, delta, sd, i, v, x; // compute summary stats for (i=0; i<values.length; ++i) { v = f ? f(values[i]) : values[i]; // update unique values u[v] = (v in u) ? u[v] + 1 : (distinct += 1, 1); if (v == null) { ++missing; } else if (util.isValid(v)) { // update stats x = (typeof v === 'string') ? v.length : v; if (min===null || x < min) min = x; if (max===null || x > max) max = x; delta = x - mean; mean = mean + delta / (++valid); M2 = M2 + delta * (x - mean); vals.push(x); } } M2 = M2 / (valid - 1); sd = Math.sqrt(M2); // sort values for median and iqr vals.sort(util.cmp); return { type: type(values, f), unique: u, count: values.length, valid: valid, missing: missing, distinct: distinct, min: min, max: max, mean: mean, stdev: sd, median: (v = stats.quantile(vals, 0.5)), q1: stats.quantile(vals, 0.25), q3: stats.quantile(vals, 0.75), modeskew: sd === 0 ? 0 : (mean - v) / sd }; }; // Compute profiles for all variables in a data set. stats.summary = function(data, fields) { fields = fields || util.keys(data[0]); var s = fields.map(function(f) { var p = stats.profile(data, util.$(f)); return (p.field = f, p); }); return (s.__summary__ = true, s); }; module.exports = stats; },{"./generate":14,"./import/type":23,"./util":29}],27:[function(require,module,exports){ var util = require('./util'), format = require('./format'); var context = { formats: [], format_map: {}, truncate: util.truncate, pad: util.pad }; function template(text) { var src = source(text, 'd'); src = 'var __t; return ' + src + ';'; /* jshint evil: true */ return (new Function('d', src)).bind(context); } template.source = source; template.context = context; module.exports = template; // Clear cache of format objects. // This can *break* prior template functions, so invoke with care! template.clearFormatCache = function() { context.formats = []; context.format_map = {}; }; // Generate property access code for use within template source. // object: the name of the object (variable) containing template data // property: the property access string, verbatim from template tag template.property = function(object, property) { var src = util.field(property).map(util.str).join(']['); return object + '[' + src + ']'; }; // Generate source code for a template function. // text: the template text // variable: the name of the data object variable ('obj' by default) // properties: optional hash for collecting all accessed properties function source(text, variable, properties) { variable = variable || 'obj'; var index = 0; var src = '\''; var regex = template_re; // Compile the template source, escaping string literals appropriately. text.replace(regex, function(match, interpolate, offset) { src += text .slice(index, offset) .replace(template_escaper, template_escapeChar); index = offset + match.length; if (interpolate) { src += '\'\n+((__t=(' + template_var(interpolate, variable, properties) + '))==null?\'\':__t)+\n\''; } // Adobe VMs need the match returned to produce the correct offest. return match; }); return src + '\''; } function template_var(text, variable, properties) { var filters = text.match(filter_re); var prop = filters.shift().trim(); var stringCast = true; function strcall(fn) { fn = fn || ''; if (stringCast) { stringCast = false; src = 'String(' + src + ')' + fn; } else { src += fn; } return src; } function date() { return '(typeof ' + src + '==="number"?new Date('+src+'):'+src+')'; } function number_format(fmt, key) { a = template_format(args[0], key, fmt); stringCast = false; src = 'this.formats['+a+']('+src+')'; } function time_format(fmt, key) { a = template_format(args[0], key, fmt); stringCast = false; src = 'this.formats['+a+']('+date()+')'; } if (properties) properties[prop] = 1; var src = template.property(variable, prop); for (var i=0; i<filters.length; ++i) { var f = filters[i], args = null, pidx, a, b; if ((pidx=f.indexOf(':')) > 0) { f = f.slice(0, pidx); args = filters[i].slice(pidx+1) .match(args_re) .map(function(s) { return s.trim(); }); } f = f.trim(); switch (f) { case 'length': strcall('.length'); break; case 'lower': strcall('.toLowerCase()'); break; case 'upper': strcall('.toUpperCase()'); break; case 'lower-locale': strcall('.toLocaleLowerCase()'); break; case 'upper-locale': strcall('.toLocaleUpperCase()'); break; case 'trim': strcall('.trim()'); break; case 'left': a = util.number(args[0]); strcall('.slice(0,' + a + ')'); break; case 'right': a = util.number(args[0]); strcall('.slice(-' + a +')'); break; case 'mid': a = util.number(args[0]); b = a + util.number(args[1]); strcall('.slice(+'+a+','+b+')'); break; case 'slice': a = util.number(args[0]); strcall('.slice('+ a + (args.length > 1 ? ',' + util.number(args[1]) : '') + ')'); break; case 'truncate': a = util.number(args[0]); b = args[1]; b = (b!=='left' && b!=='middle' && b!=='center') ? 'right' : b; src = 'this.truncate(' + strcall() + ',' + a + ',\'' + b + '\')'; break; case 'pad': a = util.number(args[0]); b = args[1]; b = (b!=='left' && b!=='middle' && b!=='center') ? 'right' : b; src = 'this.pad(' + strcall() + ',' + a + ',\'' + b + '\')'; break; case 'number': number_format(format.number, 'number'); break; case 'time': time_format(format.time, 'time'); break; case 'time-utc': time_format(format.utc, 'time-utc'); break; default: throw Error('Unrecognized template filter: ' + f); } } return src; } var template_re = /\{\{(.+?)\}\}|$/g, filter_re = /(?:"[^"]*"|\'[^\']*\'|[^\|"]+|[^\|\']+)+/g, args_re = /(?:"[^"]*"|\'[^\']*\'|[^,"]+|[^,\']+)+/g; // Certain characters need to be escaped so that they can be put into a // string literal. var template_escapes = { '\'': '\'', '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; var template_escaper = /\\|'|\r|\n|\u2028|\u2029/g; function template_escapeChar(match) { return '\\' + template_escapes[match]; } function template_format(pattern, key, fmt) { if ((pattern[0] === '\'' && pattern[pattern.length-1] === '\'') || (pattern[0] === '"' && pattern[pattern.length-1] === '"')) { pattern = pattern.slice(1, -1); } else { throw Error('Format pattern must be quoted: ' + pattern); } key = key + ':' + pattern; if (!context.format_map[key]) { var f = fmt(pattern); var i = context.formats.length; context.formats.push(f); context.format_map[key] = i; } return context.format_map[key]; } },{"./format":13,"./util":29}],28:[function(require,module,exports){ var d3_time = require('d3-time'); var tempDate = new Date(), baseDate = new Date(0, 0, 1).setFullYear(0), // Jan 1, 0 AD utcBaseDate = new Date(Date.UTC(0, 0, 1)).setUTCFullYear(0); function date(d) { return (tempDate.setTime(+d), tempDate); } // create a time unit entry function entry(type, date, unit, step, min, max) { var e = { type: type, date: date, unit: unit }; if (step) { e.step = step; } else { e.minstep = 1; } if (min != null) e.min = min; if (max != null) e.max = max; return e; } function create(type, unit, base, step, min, max) { return entry(type, function(d) { return unit.offset(base, d); }, function(d) { return unit.count(base, d); }, step, min, max); } var locale = [ create('second', d3_time.second, baseDate), create('minute', d3_time.minute, baseDate), create('hour', d3_time.hour, baseDate), create('day', d3_time.day, baseDate, [1, 7]), create('month', d3_time.month, baseDate, [1, 3, 6]), create('year', d3_time.year, baseDate), // periodic units entry('seconds', function(d) { return new Date(1970, 0, 1, 0, 0, d); }, function(d) { return date(d).getSeconds(); }, null, 0, 59 ), entry('minutes', function(d) { return new Date(1970, 0, 1, 0, d); }, function(d) { return date(d).getMinutes(); }, null, 0, 59 ), entry('hours', function(d) { return new Date(1970, 0, 1, d); }, function(d) { return date(d).getHours(); }, null, 0, 23 ), entry('weekdays', function(d) { return new Date(1970, 0, 4+d); }, function(d) { return date(d).getDay(); }, [1], 0, 6 ), entry('dates', function(d) { return new Date(1970, 0, d); }, function(d) { return date(d).getDate(); }, [1], 1, 31 ), entry('months', function(d) { return new Date(1970, d % 12, 1); }, function(d) { return date(d).getMonth(); }, [1], 0, 11 ) ]; var utc = [ create('second', d3_time.utcSecond, utcBaseDate), create('minute', d3_time.utcMinute, utcBaseDate), create('hour', d3_time.utcHour, utcBaseDate), create('day', d3_time.utcDay, utcBaseDate, [1, 7]), create('month', d3_time.utcMonth, utcBaseDate, [1, 3, 6]), create('year', d3_time.utcYear, utcBaseDate), // periodic units entry('seconds', function(d) { return new Date(Date.UTC(1970, 0, 1, 0, 0, d)); }, function(d) { return date(d).getUTCSeconds(); }, null, 0, 59 ), entry('minutes', function(d) { return new Date(Date.UTC(1970, 0, 1, 0, d)); }, function(d) { return date(d).getUTCMinutes(); }, null, 0, 59 ), entry('hours', function(d) { return new Date(Date.UTC(1970, 0, 1, d)); }, function(d) { return date(d).getUTCHours(); }, null, 0, 23 ), entry('weekdays', function(d) { return new Date(Date.UTC(1970, 0, 4+d)); }, function(d) { return date(d).getUTCDay(); }, [1], 0, 6 ), entry('dates', function(d) { return new Date(Date.UTC(1970, 0, d)); }, function(d) { return date(d).getUTCDate(); }, [1], 1, 31 ), entry('months', function(d) { return new Date(Date.UTC(1970, d % 12, 1)); }, function(d) { return date(d).getUTCMonth(); }, [1], 0, 11 ) ]; var STEPS = [ [31536e6, 5], // 1-year [7776e6, 4], // 3-month [2592e6, 4], // 1-month [12096e5, 3], // 2-week [6048e5, 3], // 1-week [1728e5, 3], // 2-day [864e5, 3], // 1-day [432e5, 2], // 12-hour [216e5, 2], // 6-hour [108e5, 2], // 3-hour [36e5, 2], // 1-hour [18e5, 1], // 30-minute [9e5, 1], // 15-minute [3e5, 1], // 5-minute [6e4, 1], // 1-minute [3e4, 0], // 30-second [15e3, 0], // 15-second [5e3, 0], // 5-second [1e3, 0] // 1-second ]; function find(units, span, minb, maxb) { var step = STEPS[0], i, n, bins; for (i=1, n=STEPS.length; i<n; ++i) { step = STEPS[i]; if (span > step[0]) { bins = span / step[0]; if (bins > maxb) { return units[STEPS[i-1][1]]; } if (bins >= minb) { return units[step[1]]; } } } return units[STEPS[n-1][1]]; } function toUnitMap(units) { var map = {}, i, n; for (i=0, n=units.length; i<n; ++i) { map[units[i].type] = units[i]; } map.find = function(span, minb, maxb) { return find(units, span, minb, maxb); }; return map; } module.exports = toUnitMap(locale); module.exports.utc = toUnitMap(utc); },{"d3-time":6}],29:[function(require,module,exports){ var buffer = require('buffer'), time = require('./time'), utc = time.utc; var u = module.exports = {}; // utility functions var FNAME = '__name__'; u.namedfunc = function(name, f) { return (f[FNAME] = name, f); }; u.name = function(f) { return f==null ? null : f[FNAME]; }; u.identity = function(x) { return x; }; u.true = u.namedfunc('true', function() { return true; }); u.false = u.namedfunc('false', function() { return false; }); u.duplicate = function(obj) { return JSON.parse(JSON.stringify(obj)); }; u.equal = function(a, b) { return JSON.stringify(a) === JSON.stringify(b); }; u.extend = function(obj) { for (var x, name, i=1, len=arguments.length; i<len; ++i) { x = arguments[i]; for (name in x) { obj[name] = x[name]; } } return obj; }; u.length = function(x) { return x != null && x.length != null ? x.length : null; }; u.keys = function(x) { var keys = [], k; for (k in x) keys.push(k); return keys; }; u.vals = function(x) { var vals = [], k; for (k in x) vals.push(x[k]); return vals; }; u.toMap = function(list, f) { return (f = u.$(f)) ? list.reduce(function(obj, x) { return (obj[f(x)] = 1, obj); }, {}) : list.reduce(function(obj, x) { return (obj[x] = 1, obj); }, {}); }; u.keystr = function(values) { // use to ensure consistent key generation across modules var n = values.length; if (!n) return ''; for (var s=String(values[0]), i=1; i<n; ++i) { s += '|' + String(values[i]); } return s; }; // type checking functions var toString = Object.prototype.toString; u.isObject = function(obj) { return obj === Object(obj); }; u.isFunction = function(obj) { return toString.call(obj) === '[object Function]'; }; u.isString = function(obj) { return typeof value === 'string' || toString.call(obj) === '[object String]'; }; u.isArray = Array.isArray || function(obj) { return toString.call(obj) === '[object Array]'; }; u.isNumber = function(obj) { return typeof obj === 'number' || toString.call(obj) === '[object Number]'; }; u.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; }; u.isDate = function(obj) { return toString.call(obj) === '[object Date]'; }; u.isValid = function(obj) { return obj != null && obj === obj; }; u.isBuffer = (buffer.Buffer && buffer.Buffer.isBuffer) || u.false; // type coercion functions u.number = function(s) { return s == null || s === '' ? null : +s; }; u.boolean = function(s) { return s == null || s === '' ? null : s==='false' ? false : !!s; }; u.date = function(s) { return s == null || s === '' ? null : Date.parse(s); }; u.array = function(x) { return x != null ? (u.isArray(x) ? x : [x]) : []; }; u.str = function(x) { return u.isArray(x) ? '[' + x.map(u.str) + ']' : u.isObject(x) ? JSON.stringify(x) : u.isString(x) ? ('\''+util_escape_str(x)+'\'') : x; }; var escape_str_re = /(^|[^\\])'/g; function util_escape_str(x) { return x.replace(escape_str_re, '$1\\\''); } // data access functions var field_re = /\[(.*?)\]|[^.\[]+/g; u.field = function(f) { return String(f).match(field_re).map(function(d) { return d[0] !== '[' ? d : d[1] !== "'" && d[1] !== '"' ? d.slice(1, -1) : d.slice(2, -2).replace(/\\(["'])/g, '$1'); }); }; u.accessor = function(f) { var s; return f==null || u.isFunction(f) ? f : u.namedfunc(f, (s = u.field(f)).length > 1 ? function(x) { return s.reduce(function(x,f) { return x[f]; }, x); } : function(x) { return x[f]; } ); }; // short-cut for accessor u.$ = u.accessor; u.mutator = function(f) { var s; return u.isString(f) && (s=u.field(f)).length > 1 ? function(x, v) { for (var i=0; i<s.length-1; ++i) x = x[s[i]]; x[s[i]] = v; } : function(x, v) { x[f] = v; }; }; u.$func = function(name, op) { return function(f) { f = u.$(f) || u.identity; var n = name + (u.name(f) ? '_'+u.name(f) : ''); return u.namedfunc(n, function(d) { return op(f(d)); }); }; }; u.$valid = u.$func('valid', u.isValid); u.$length = u.$func('length', u.length); u.$in = function(f, values) { f = u.$(f); var map = u.isArray(values) ? u.toMap(values) : values; return function(d) { return !!map[f(d)]; }; }; u.$year = u.$func('year', time.year.unit); u.$month = u.$func('month', time.months.unit); u.$date = u.$func('date', time.dates.unit); u.$day = u.$func('day', time.weekdays.unit); u.$hour = u.$func('hour', time.hours.unit); u.$minute = u.$func('minute', time.minutes.unit); u.$second = u.$func('second', time.seconds.unit); u.$utcYear = u.$func('utcYear', utc.year.unit); u.$utcMonth = u.$func('utcMonth', utc.months.unit); u.$utcDate = u.$func('utcDate', utc.dates.unit); u.$utcDay = u.$func('utcDay', utc.weekdays.unit); u.$utcHour = u.$func('utcHour', utc.hours.unit); u.$utcMinute = u.$func('utcMinute', utc.minutes.unit); u.$utcSecond = u.$func('utcSecond', utc.seconds.unit); // comparison / sorting functions u.comparator = function(sort) { var sign = []; if (sort === undefined) sort = []; sort = u.array(sort).map(function(f) { var s = 1; if (f[0] === '-') { s = -1; f = f.slice(1); } else if (f[0] === '+') { s = +1; f = f.slice(1); } sign.push(s); return u.accessor(f); }); return function(a,b) { var i, n, f, x, y; for (i=0, n=sort.length; i<n; ++i) { f = sort[i]; x = f(a); y = f(b); if (x < y) return -1 * sign[i]; if (x > y) return sign[i]; } return 0; }; }; u.cmp = function(a, b) { if (a < b) { return -1; } else if (a > b) { return 1; } else if (a >= b) { return 0; } else if (a === null) { return -1; } else if (b === null) { return 1; } return NaN; }; u.numcmp = function(a, b) { return a - b; }; u.stablesort = function(array, sortBy, keyFn) { var indices = array.reduce(function(idx, v, i) { return (idx[keyFn(v)] = i, idx); }, {}); array.sort(function(a, b) { var sa = sortBy(a), sb = sortBy(b); return sa < sb ? -1 : sa > sb ? 1 : (indices[keyFn(a)] - indices[keyFn(b)]); }); return array; }; // string functions u.pad = function(s, length, pos, padchar) { padchar = padchar || " "; var d = length - s.length; if (d <= 0) return s; switch (pos) { case 'left': return strrep(d, padchar) + s; case 'middle': case 'center': return strrep(Math.floor(d/2), padchar) + s + strrep(Math.ceil(d/2), padchar); default: return s + strrep(d, padchar); } }; function strrep(n, str) { var s = "", i; for (i=0; i<n; ++i) s += str; return s; } u.truncate = function(s, length, pos, word, ellipsis) { var len = s.length; if (len <= length) return s; ellipsis = ellipsis !== undefined ? String(ellipsis) : '\u2026'; var l = Math.max(0, length - ellipsis.length); switch (pos) { case 'left': return ellipsis + (word ? truncateOnWord(s,l,1) : s.slice(len-l)); case 'middle': case 'center': var l1 = Math.ceil(l/2), l2 = Math.floor(l/2); return (word ? truncateOnWord(s,l1) : s.slice(0,l1)) + ellipsis + (word ? truncateOnWord(s,l2,1) : s.slice(len-l2)); default: return (word ? truncateOnWord(s,l) : s.slice(0,l)) + ellipsis; } }; function truncateOnWord(s, len, rev) { var cnt = 0, tok = s.split(truncate_word_re); if (rev) { s = (tok = tok.reverse()) .filter(function(w) { cnt += w.length; return cnt <= len; }) .reverse(); } else { s = tok.filter(function(w) { cnt += w.length; return cnt <= len; }); } return s.length ? s.join('').trim() : tok[0].slice(0, len); } var truncate_word_re = /([\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF])/; },{"./time":28,"buffer":2}],30:[function(require,module,exports){ var DEPS = require('./Dependencies').ALL; function create(cs, reflow) { var out = {}; copy(cs, out); out.add = []; out.mod = []; out.rem = []; out.reflow = reflow; return out; } function copy(a, b) { b.stamp = a ? a.stamp : 0; b.sort = a ? a.sort : null; b.facet = a ? a.facet : null; b.trans = a ? a.trans : null; b.dirty = a ? a.dirty : []; b.request = a ? a.request : null; for (var d, i=0, n=DEPS.length; i<n; ++i) { b[d=DEPS[i]] = a ? a[d] : {}; } } module.exports = { create: create, copy: copy }; },{"./Dependencies":33}],31:[function(require,module,exports){ var log = require('vega-logging'), Tuple = require('./Tuple'), Base = require('./Node').prototype; function Collector(graph) { Base.init.call(this, graph); this._data = []; this.router(true).collector(true); } var prototype = (Collector.prototype = Object.create(Base)); prototype.constructor = Collector; prototype.data = function() { return this._data; }; prototype.evaluate = function(input) { log.debug(input, ["collecting"]); if (input.rem.length) { this._data = Tuple.idFilter(this._data, input.rem); } if (input.add.length) { this._data = this._data.length ? this._data.concat(input.add) : input.add; } if (input.sort) { this._data.sort(input.sort); } if (input.reflow) { input.mod = input.mod.concat( Tuple.idFilter(this._data, input.add, input.mod, input.rem)); input.reflow = false; } return input; }; module.exports = Collector; },{"./Node":36,"./Tuple":38,"vega-logging":45}],32:[function(require,module,exports){ var log = require('vega-logging'), ChangeSet = require('./ChangeSet'), Collector = require('./Collector'), Tuple = require('./Tuple'), Node = require('./Node'); // jshint ignore:line function DataSource(graph, name, facet) { this._graph = graph; this._name = name; this._data = []; this._source = null; this._facet = facet; this._input = ChangeSet.create(); this._output = null; // Output changeset this._inputNode = null; this._outputNode = null; this._pipeline = null; // Pipeline of transformations. this._collector = null; // Collector to materialize output of pipeline. this._mutates = false; // Does any pipeline operator mutate tuples? } var prototype = DataSource.prototype; prototype.name = function(name) { if (!arguments.length) return this._name; return (this._name = name, this); }; prototype.source = function(src) { if (!arguments.length) return this._source; return (this._source = this._graph.data(src)); }; prototype.insert = function(tuples) { this._input.add = this._input.add.concat(tuples.map(Tuple.ingest)); return this; }; prototype.remove = function(where) { var remove = this._data.filter(where); this._input.rem = this._input.rem.concat(remove); return this; }; prototype.update = function(where, field, func) { var mod = this._input.mod, ids = Tuple.idMap(mod); this._input.fields[field] = 1; this._data.filter(where).forEach(function(x) { var prev = x[field], next = func(x); if (prev !== next) { Tuple.set(x, field, next); if (ids[x._id] !== 1) { mod.push(x); ids[x._id] = 1; } } }); return this; }; prototype.values = function(data) { if (!arguments.length) { return this._collector ? this._collector.data() : this._data; } // Replace backing data this._input.rem = this._data.slice(); if (data) { this.insert(data); } return this; }; prototype.mutates = function(m) { if (!arguments.length) return this._mutates; this._mutates = this._mutates || m; return this; }; prototype.last = function() { return this._output; }; prototype.fire = function(input) { if (input) this._input = input; this._graph.propagate(this._input, this._pipeline[0]); return this; }; prototype.pipeline = function(pipeline) { if (!arguments.length) return this._pipeline; this._inputNode = DataSourceInput(this); this._outputNode = DataSourceOutput(this); var graph = this._graph, mutates = 0, collector = this._inputNode, i, node, router, collects; for (i=0; i<pipeline.length; ++i) { node = pipeline[i]; if (!node._collector && node.batch()) { if (router) { node = new Collector(graph); pipeline.splice(i, 0, node); router = false; } else { node._collector = collector; } } if ((collects = node.collector())) collector = node; router = router || node.router() && !collects; mutates = mutates || node.mutates(); } if (router) pipeline.push(collector = new Collector(graph)); pipeline.unshift(this._inputNode); pipeline.push(this._outputNode); this._collector = collector; this._mutates = !!mutates; this._graph.connect(this._pipeline = pipeline); return this; }; prototype.synchronize = function() { var data = this._data, i, n; for (i=0, n=data.length; i<n; ++i) { Tuple.prev_update(data[i]); } if (this._inputNode !== this._collector) { data = this._collector.data(); for (i=0, n=data.length; i<n; ++i) { Tuple.prev_update(data[i]); } } return this; }; prototype.listener = function() { return DataSourceListener(this).addListener(this._inputNode); }; prototype.addListener = function(l) { if (l instanceof DataSource) { this._collector.addListener(l.listener()); } else { this._outputNode.addListener(l); } return this; }; prototype.removeListener = function(l) { this._outputNode.removeListener(l); }; prototype.listeners = function(ds) { return (ds ? this._collector : this._outputNode).listeners(); }; // Input node applies the datasource's delta, and propagates it to // the rest of the pipeline. It receives touches to reflow data. function DataSourceInput(ds) { var input = new Node(ds._graph) .router(true) .collector(true); input.data = function() { return ds._data; }; input.evaluate = function(input) { log.debug(input, ['input', ds._name]); var delta = ds._input, out = ChangeSet.create(input), f; // Delta might contain fields updated through API for (f in delta.fields) { out.fields[f] = 1; } // update data if (delta.rem.length) { ds._data = Tuple.idFilter(ds._data, delta.rem); } if (delta.add.length) { ds._data = ds._data.concat(delta.add); } // if reflowing, add any other tuples not currently in changeset if (input.reflow) { delta.mod = delta.mod.concat( Tuple.idFilter(ds._data, delta.add, delta.mod, delta.rem)); } // reset change list ds._input = ChangeSet.create(); out.add = delta.add; out.mod = delta.mod; out.rem = delta.rem; out.facet = ds._facet; return out; }; return input; } // Output node captures the last changeset seen by this datasource // (needed for joins and builds) and materializes any nested data. // If this datasource is faceted, materializes the values in the facet. function DataSourceOutput(ds) { var output = new Node(ds._graph) .router(true) .reflows(true) .collector(true); output.data = function() { return ds._collector ? ds._collector.data() : ds._data; }; output.evaluate = function(input) { log.debug(input, ['output', ds._name]); var out = ChangeSet.create(input, true); if (ds._facet) { ds._facet.values = ds.values(); input.facet = null; } ds._output = input; out.data[ds._name] = 1; return out; }; return output; } function DataSourceListener(ds) { var l = new Node(ds._graph).router(true); l.evaluate = function(input) { // Tuple derivation carries a cost. So only derive if the pipeline has // operators that mutate, and thus would override the source data. if (ds.mutates()) { var map = ds._srcMap || (ds._srcMap = {}), // to propagate tuples correctly output = ChangeSet.create(input); output.add = input.add.map(function(t) { return (map[t._id] = Tuple.derive(t)); }); output.mod = input.mod.map(function(t) { return Tuple.rederive(t, map[t._id]); }); output.rem = input.rem.map(function(t) { var o = map[t._id]; return (map[t._id] = null, o); }); return (ds._input = output); } else { return (ds._input = input); } }; return l; } module.exports = DataSource; },{"./ChangeSet":30,"./Collector":31,"./Node":36,"./Tuple":38,"vega-logging":45}],33:[function(require,module,exports){ var deps = module.exports = { ALL: ['data', 'fields', 'scales', 'signals'] }; deps.ALL.forEach(function(k) { deps[k.toUpperCase()] = k; }); },{}],34:[function(require,module,exports){ var dl = require('datalib'), Heap = require('./Heap'), ChangeSet = require('./ChangeSet'), DataSource = require('./DataSource'), Signal = require('./Signal'), Deps = require('./Dependencies'); function Graph() { } var prototype = Graph.prototype; prototype.init = function() { this._stamp = 0; this._rank = 0; this._data = {}; this._signals = {}; this.doNotPropagate = {}; }; prototype.rank = function() { return ++this._rank; }; prototype.data = function(name, pipeline, facet) { var db = this._data; if (!arguments.length) { var all = [], key; for (key in db) { all.push(db[key]); } return all; } else if (arguments.length === 1) { return db[name]; } else { return (db[name] = new DataSource(this, name, facet).pipeline(pipeline)); } }; prototype.dataValues = function(names) { var data = this._data, k; if (!arguments.length) { names = []; for (k in data) names.push(k); } if (Array.isArray(names)) { return names.reduce(function(db, name) { return (db[name] = data[name].values(), db); }, {}); } else { return data[names].values(); } }; function signal(names) { var m = this; if (Array.isArray(names)) { return names.map(function(name) { return m._signals[name]; }); } else { return this._signals[names]; } } prototype.signal = function(name, init) { if (arguments.length === 1) { return signal.call(this, name); } else { return (this._signals[name] = new Signal(this, name, init)); } }; // TODO: separate into signalValue and signalValues? prototype.signalValues = function(names) { if (!arguments.length) { names = []; for (var k in this._signals) names.push(k); } if (Array.isArray(names)) { var values = {}; for (var i=0, n=names.length; i<n; ++i) { values[names[i]] = this._signals[names[i]].value(); } return values; } else { return this._signals[names].value(); } }; prototype.signalRef = function(ref) { if (!Array.isArray(ref)) { ref = dl.field(ref); } var value = this.signal(ref[0]).value(); if (ref.length > 1) { for (var i=1, n=ref.length; i<n; ++i) { value = value[ref[i]]; } } return value; }; // Stamp should be specified with caution. It is necessary for inline datasources, // which need to be populated during the same cycle even though propagation has // passed that part of the dataflow graph. prototype.propagate = function(pulse, node, stamp) { var pulses = {}, listeners, next, nplse, tpls, ntpls, i, len; // new PQ with each propagation cycle so that we can pulse branches // of the dataflow graph during a propagation (e.g., when creating // a new inline datasource). var pq = new Heap(function(a, b) { // Topological sort on qrank as rank may change during propagation. return a.qrank() - b.qrank(); }); if (pulse.stamp) throw Error('Pulse already has a non-zero stamp.'); pulse.stamp = stamp || ++this._stamp; pulses[node._id] = pulse; pq.push(node.qrank(true)); while (pq.size() > 0) { node = pq.peek(); pulse = pulses[node._id]; if (node.rank() !== node.qrank()) { // A node's rank might change during a propagation. Re-queue if so. pq.replace(node.qrank(true)); } else { // Evaluate node and propagate pulse. pq.pop(); pulses[node._id] = null; listeners = node._listeners; pulse = this.evaluate(pulse, node); // Propagate the pulse. if (pulse !== this.doNotPropagate) { // Ensure reflow pulses always send reflow pulses even if skipped. if (!pulse.reflow && node.reflows()) { pulse = ChangeSet.create(pulse, true); } for (i=0, len=listeners.length; i<len; ++i) { next = listeners[i]; if ((nplse = pulses[next._id]) !== undefined) { if (nplse === null) throw Error('Already propagated to node.'); // We've already queued this node. Ensure there should be at most one // pulse with tuples (add/mod/rem), and the remainder will be reflows. tpls = pulse.add.length || pulse.mod.length || pulse.rem.length; ntpls = nplse.add.length || nplse.mod.length || nplse.rem.length; if (tpls && ntpls) throw Error('Multiple changeset pulses to same node'); // Combine reflow and tuples into a single pulse. pulses[next._id] = tpls ? pulse : nplse; pulses[next._id].reflow = pulse.reflow || nplse.reflow; } else { // First time we're seeing this node, queue it for propagation. pq.push(next.qrank(true)); pulses[next._id] = pulse; } } } } } }; prototype.connect = function(branch) { var collector, node, data, signals, i, n, j, m; // connect the pipeline for (i=0, n=branch.length; i<n; ++i) { node = branch[i]; if (node.collector()) collector = node; data = node.dependency(Deps.DATA); for (j=0, m=data.length; j<m; ++j) { this.data(data[j]).addListener(collector); } signals = node.dependency(Deps.SIGNALS); for (j=0, m=signals.length; j<m; ++j) { this.signal(signals[j]).addListener(collector); } if (i > 0) branch[i-1].addListener(node); } return branch; }; prototype.disconnect = function(branch) { var collector, node, data, signals, i, n, j, m; for (i=0, n=branch.length; i<n; ++i) { node = branch[i]; if (node.collector()) collector = node; data = node.dependency(Deps.DATA); for (j=0, m=data.length; j<m; ++j) { this.data(data[j]).removeListener(collector); } signals = node.dependency(Deps.SIGNALS); for (j=0, m=signals.length; j<m; ++j) { this.signal(signals[j]).removeListener(collector); } node.disconnect(); } return branch; }; prototype.reevaluate = function(pulse, node) { var reflowed = pulse.reflow && node.last() >= pulse.stamp, run = node.router() || pulse.add.length || pulse.rem.length; return run || !reflowed || node.reevaluate(pulse); }; prototype.evaluate = function(pulse, node) { if (!this.reevaluate(pulse, node)) return pulse; pulse = node.evaluate(pulse); node.last(pulse.stamp); return pulse; }; module.exports = Graph; },{"./ChangeSet":30,"./DataSource":32,"./Dependencies":33,"./Heap":35,"./Signal":37,"datalib":24}],35:[function(require,module,exports){ function Heap(comparator) { this.cmp = comparator; this.nodes = []; } var prototype = Heap.prototype; prototype.size = function() { return this.nodes.length; }; prototype.clear = function() { this.nodes = []; }; prototype.peek = function() { return this.nodes[0]; }; prototype.push = function(x) { var array = this.nodes; array.push(x); return _siftdown(array, 0, array.length-1, this.cmp); }; prototype.pop = function() { var array = this.nodes, last = array.pop(), item; if (array.length) { item = array[0]; array[0] = last; _siftup(array, 0, this.cmp); } else { item = last; } return item; }; prototype.replace = function(item) { var array = this.nodes, retval = array[0]; array[0] = item; _siftup(array, 0, this.cmp); return retval; }; prototype.pushpop = function(item) { var array = this.nodes, ref = array[0]; if (array.length && this.cmp(ref, item) < 0) { array[0] = item; item = ref; _siftup(array, 0, this.cmp); } return item; }; function _siftdown(array, start, idx, cmp) { var item, parent, pidx; item = array[idx]; while (idx > start) { pidx = (idx - 1) >> 1; parent = array[pidx]; if (cmp(item, parent) < 0) { array[idx] = parent; idx = pidx; continue; } break; } return (array[idx] = item); } function _siftup(array, idx, cmp) { var start = idx, end = array.length, item = array[idx], cidx = 2 * idx + 1, ridx; while (cidx < end) { ridx = cidx + 1; if (ridx < end && cmp(array[cidx], array[ridx]) >= 0) { cidx = ridx; } array[idx] = array[cidx]; idx = cidx; cidx = 2 * idx + 1; } array[idx] = item; return _siftdown(array, start, idx, cmp); } module.exports = Heap; },{}],36:[function(require,module,exports){ var DEPS = require('./Dependencies').ALL, nodeID = 0; function Node(graph) { if (graph) this.init(graph); } var Flags = Node.Flags = { Router: 0x01, // Responsible for propagating tuples, cannot be skipped. Collector: 0x02, // Holds a materialized dataset, pulse node to reflow. Mutates: 0x04, // Sets properties of incoming tuples. Reflows: 0x08, // Forwards a reflow pulse. Batch: 0x10 // Performs batch data processing, needs collector. }; var prototype = Node.prototype; prototype.init = function(graph) { this._id = ++nodeID; this._graph = graph; this._rank = graph.rank(); // Topological sort by rank this._qrank = null; // Rank when enqueued for propagation this._stamp = 0; // Last stamp seen this._listeners = []; this._listeners._ids = {}; // To prevent duplicate listeners // Initialize dependencies. this._deps = {}; for (var i=0, n=DEPS.length; i<n; ++i) { this._deps[DEPS[i]] = []; } // Initialize status flags. this._flags = 0; return this; }; prototype.rank = function() { return this._rank; }; prototype.qrank = function(/* set */) { if (!arguments.length) return this._qrank; return (this._qrank = this._rank, this); }; prototype.last = function(stamp) { if (!arguments.length) return this._stamp; return (this._stamp = stamp, this); }; // -- status flags --- prototype._setf = function(v, b) { if (b) { this._flags |= v; } else { this._flags &= ~v; } return this; }; prototype.router = function(state) { if (!arguments.length) return (this._flags & Flags.Router); return this._setf(Flags.Router, state); }; prototype.collector = function(state) { if (!arguments.length) return (this._flags & Flags.Collector); return this._setf(Flags.Collector, state); }; prototype.mutates = function(state) { if (!arguments.length) return (this._flags & Flags.Mutates); return this._setf(Flags.Mutates, state); }; prototype.reflows = function(state) { if (!arguments.length) return (this._flags & Flags.Reflows); return this._setf(Flags.Reflows, state); }; prototype.batch = function(state) { if (!arguments.length) return (this._flags & Flags.Batch); return this._setf(Flags.Batch, state); }; prototype.dependency = function(type, deps) { var d = this._deps[type], n = d._names || (d._names = {}); // To prevent dupe deps // Get dependencies of the given type if (arguments.length === 1) { return d; } if (deps === null) { // Clear dependencies of the given type d.splice(0, d.length); d._names = {}; } else if (!Array.isArray(deps)) { // Separate this case to avoid cost of array creation if (n[deps]) return this; d.push(deps); n[deps] = 1; } else { for (var i=0, len=deps.length, dep; i<len; ++i) { dep = deps[i]; if (n[dep]) continue; d.push(dep); n[dep] = 1; } } return this; }; prototype.listeners = function() { return this._listeners; }; prototype.addListener = function(l) { if (!(l instanceof Node)) { throw Error('Listener is not a Node'); } if (this._listeners._ids[l._id]) return this; this._listeners.push(l); this._listeners._ids[l._id] = 1; if (this._rank > l._rank) { var q = [l], g = this._graph, cur; while (q.length) { cur = q.shift(); cur._rank = g.rank(); q.push.apply(q, cur.listeners()); } } return this; }; prototype.removeListener = function(l) { var idx = this._listeners.indexOf(l), b = idx >= 0; if (b) { this._listeners.splice(idx, 1); this._listeners._ids[l._id] = null; } return b; }; prototype.disconnect = function() { this._listeners = []; this._listeners._ids = {}; }; // Evaluate this dataflow node for the current pulse. // Subclasses should override to perform custom processing. prototype.evaluate = function(pulse) { return pulse; }; // Should this node be re-evaluated for the current pulse? // Searches pulse to see if any dependencies have updated. prototype.reevaluate = function(pulse) { var prop, dep, i, n, j, m; for (i=0, n=DEPS.length; i<n; ++i) { prop = DEPS[i]; dep = this._deps[prop]; for (j=0, m=dep.length; j<m; ++j) { if (pulse[prop][dep[j]]) return true; } } return false; }; Node.reset = function() { nodeID = 0; }; module.exports = Node; },{"./Dependencies":33}],37:[function(require,module,exports){ var ChangeSet = require('./ChangeSet'), Node = require('./Node'), // jshint ignore:line Base = Node.prototype; function Signal(graph, name, initialValue) { Base.init.call(this, graph); this._name = name; this._value = initialValue; this._verbose = false; // Verbose signals re-pulse the graph even if prev === val. this._handlers = []; return this; } var prototype = (Signal.prototype = Object.create(Base)); prototype.constructor = Signal; prototype.name = function() { return this._name; }; prototype.value = function(val) { if (!arguments.length) return this._value; return (this._value = val, this); }; prototype.verbose = function(v) { if (!arguments.length) return this._verbose; return (this._verbose = !!v, this); }; prototype.evaluate = function(input) { return input.signals[this._name] ? input : this._graph.doNotPropagate; }; prototype.fire = function(cs) { if (!cs) cs = ChangeSet.create(null, true); cs.signals[this._name] = 1; this._graph.propagate(cs, this); }; prototype.on = function(handler) { var signal = this, node = new Node(this._graph); node.evaluate = function(input) { handler(signal.name(), signal.value()); return input; }; this._handlers.push({ handler: handler, node: node }); return this.addListener(node); }; prototype.off = function(handler) { var h = this._handlers, i, x; for (i=h.length; --i>=0;) { if (!handler || h[i].handler === handler) { x = h.splice(i, 1)[0]; this.removeListener(x.node); } } return this; }; module.exports = Signal; },{"./ChangeSet":30,"./Node":36}],38:[function(require,module,exports){ var tupleID = 0; function ingest(datum) { datum = (datum === Object(datum)) ? datum : {data: datum}; datum._id = ++tupleID; if (datum._prev) datum._prev = null; return datum; } function idMap(a, ids) { ids = ids || {}; for (var i=0, n=a.length; i<n; ++i) { ids[a[i]._id] = 1; } return ids; } function copy(t, c) { c = c || {}; for (var k in t) { if (k !== '_prev' && k !== '_id') c[k] = t[k]; } return c; } module.exports = { ingest: ingest, idMap: idMap, derive: function(d) { return ingest(copy(d)); }, rederive: function(d, t) { return copy(d, t); }, set: function(t, k, v) { return t[k] === v ? 0 : (t[k] = v, 1); }, prev: function(t) { return t._prev || t; }, prev_init: function(t) { if (!t._prev) { t._prev = {_id: t._id}; } }, prev_update: function(t) { var p = t._prev, k, v; if (p) for (k in t) { if (k !== '_prev' && k !== '_id') { p[k] = ((v=t[k]) instanceof Object && v._prev) ? v._prev : v; } } }, reset: function() { tupleID = 0; }, idFilter: function(data) { var ids = {}; for (var i=arguments.length; --i>0;) { idMap(arguments[i], ids); } return data.filter(function(x) { return !ids[x._id]; }); } }; },{}],39:[function(require,module,exports){ module.exports = { ChangeSet: require('./ChangeSet'), Collector: require('./Collector'), DataSource: require('./DataSource'), Dependencies: require('./Dependencies'), Graph: require('./Graph'), Node: require('./Node'), Signal: require('./Signal'), Tuple: require('./Tuple'), debug: require('vega-logging').debug }; },{"./ChangeSet":30,"./Collector":31,"./DataSource":32,"./Dependencies":33,"./Graph":34,"./Node":36,"./Signal":37,"./Tuple":38,"vega-logging":45}],40:[function(require,module,exports){ function toMap(list) { var map = {}, i, n; for (i=0, n=list.length; i<n; ++i) map[list[i]] = 1; return map; } function keys(object) { var list = [], k; for (k in object) list.push(k); return list; } module.exports = function(opt) { opt = opt || {}; var constants = opt.constants || require('./constants'), functions = (opt.functions || require('./functions'))(codegen), idWhiteList = opt.idWhiteList ? toMap(opt.idWhiteList) : null, idBlackList = opt.idBlackList ? toMap(opt.idBlackList) : null, memberDepth = 0, FIELD_VAR = opt.fieldVar || 'datum', GLOBAL_VAR = opt.globalVar || 'signals', globals = {}, fields = {}; function codegen_wrap(ast) { var retval = { code: codegen(ast), globals: keys(globals), fields: keys(fields) }; globals = {}; fields = {}; return retval; } function lookupGlobal(id) { return GLOBAL_VAR + '["' + id + '"]'; } function codegen(ast) { if (typeof ast === 'string') return ast; var generator = CODEGEN_TYPES[ast.type]; if (generator == null) { throw new Error('Unsupported type: ' + ast.type); } return generator(ast); } var CODEGEN_TYPES = { 'Literal': function(n) { return n.raw; }, 'Identifier': function(n) { var id = n.name; if (memberDepth > 0) { return id; } if (constants.hasOwnProperty(id)) { return constants[id]; } if (idWhiteList) { if (idWhiteList.hasOwnProperty(id)) { return id; } else { globals[id] = 1; return lookupGlobal(id); } } if (idBlackList && idBlackList.hasOwnProperty(id)) { throw new Error('Illegal identifier: ' + id); } return id; }, 'Program': function(n) { return n.body.map(codegen).join('\n'); }, 'MemberExpression': function(n) { var d = !n.computed; var o = codegen(n.object); if (d) memberDepth += 1; var p = codegen(n.property); if (o === FIELD_VAR) { fields[p] = 1; } // HACKish... if (d) memberDepth -= 1; return o + (d ? '.'+p : '['+p+']'); }, 'CallExpression': function(n) { if (n.callee.type !== 'Identifier') { throw new Error('Illegal callee type: ' + n.callee.type); } var callee = n.callee.name; var args = n.arguments; var fn = functions.hasOwnProperty(callee) && functions[callee]; if (!fn) throw new Error('Unrecognized function: ' + callee); return fn instanceof Function ? fn(args) : fn + '(' + args.map(codegen).join(',') + ')'; }, 'ArrayExpression': function(n) { return '[' + n.elements.map(codegen).join(',') + ']'; }, 'BinaryExpression': function(n) { return '(' + codegen(n.left) + n.operator + codegen(n.right) + ')'; }, 'UnaryExpression': function(n) { return '(' + n.operator + codegen(n.argument) + ')'; }, 'ConditionalExpression': function(n) { return '(' + codegen(n.test) + '?' + codegen(n.consequent) + ':' + codegen(n.alternate) + ')'; }, 'LogicalExpression': function(n) { return '(' + codegen(n.left) + n.operator + codegen(n.right) + ')'; }, 'ObjectExpression': function(n) { return '{' + n.properties.map(codegen).join(',') + '}'; }, 'Property': function(n) { memberDepth += 1; var k = codegen(n.key); memberDepth -= 1; return k + ':' + codegen(n.value); }, 'ExpressionStatement': function(n) { return codegen(n.expression); } }; codegen_wrap.functions = functions; codegen_wrap.constants = constants; return codegen_wrap; }; },{"./constants":41,"./functions":42}],41:[function(require,module,exports){ module.exports = { 'NaN': 'NaN', 'E': 'Math.E', 'LN2': 'Math.LN2', 'LN10': 'Math.LN10', 'LOG2E': 'Math.LOG2E', 'LOG10E': 'Math.LOG10E', 'PI': 'Math.PI', 'SQRT1_2': 'Math.SQRT1_2', 'SQRT2': 'Math.SQRT2' }; },{}],42:[function(require,module,exports){ module.exports = function(codegen) { function fncall(name, args, cast, type) { var obj = codegen(args[0]); if (cast) { obj = cast + '(' + obj + ')'; if (cast.lastIndexOf('new ', 0) === 0) obj = '(' + obj + ')'; } return obj + '.' + name + (type < 0 ? '' : type === 0 ? '()' : '(' + args.slice(1).map(codegen).join(',') + ')'); } var DATE = 'new Date'; var STRING = 'String'; var REGEXP = 'RegExp'; return { // MATH functions 'isNaN': 'isNaN', 'isFinite': 'isFinite', 'abs': 'Math.abs', 'acos': 'Math.acos', 'asin': 'Math.asin', 'atan': 'Math.atan', 'atan2': 'Math.atan2', 'ceil': 'Math.ceil', 'cos': 'Math.cos', 'exp': 'Math.exp', 'floor': 'Math.floor', 'log': 'Math.log', 'max': 'Math.max', 'min': 'Math.min', 'pow': 'Math.pow', 'random': 'Math.random', 'round': 'Math.round', 'sin': 'Math.sin', 'sqrt': 'Math.sqrt', 'tan': 'Math.tan', 'clamp': function(args) { if (args.length < 3) throw new Error('Missing arguments to clamp function.'); if (args.length > 3) throw new Error('Too many arguments to clamp function.'); var a = args.map(codegen); return 'Math.max('+a[1]+', Math.min('+a[2]+','+a[0]+'))'; }, // DATE functions 'now': 'Date.now', 'datetime': 'new Date', 'date': function(args) { return fncall('getDate', args, DATE, 0); }, 'day': function(args) { return fncall('getDay', args, DATE, 0); }, 'year': function(args) { return fncall('getFullYear', args, DATE, 0); }, 'month': function(args) { return fncall('getMonth', args, DATE, 0); }, 'hours': function(args) { return fncall('getHours', args, DATE, 0); }, 'minutes': function(args) { return fncall('getMinutes', args, DATE, 0); }, 'seconds': function(args) { return fncall('getSeconds', args, DATE, 0); }, 'milliseconds': function(args) { return fncall('getMilliseconds', args, DATE, 0); }, 'time': function(args) { return fncall('getTime', args, DATE, 0); }, 'timezoneoffset': function(args) { return fncall('getTimezoneOffset', args, DATE, 0); }, 'utcdate': function(args) { return fncall('getUTCDate', args, DATE, 0); }, 'utcday': function(args) { return fncall('getUTCDay', args, DATE, 0); }, 'utcyear': function(args) { return fncall('getUTCFullYear', args, DATE, 0); }, 'utcmonth': function(args) { return fncall('getUTCMonth', args, DATE, 0); }, 'utchours': function(args) { return fncall('getUTCHours', args, DATE, 0); }, 'utcminutes': function(args) { return fncall('getUTCMinutes', args, DATE, 0); }, 'utcseconds': function(args) { return fncall('getUTCSeconds', args, DATE, 0); }, 'utcmilliseconds': function(args) { return fncall('getUTCMilliseconds', args, DATE, 0); }, // shared sequence functions 'length': function(args) { return fncall('length', args, null, -1); }, 'indexof': function(args) { return fncall('indexOf', args, null); }, 'lastindexof': function(args) { return fncall('lastIndexOf', args, null); }, // STRING functions 'parseFloat': 'parseFloat', 'parseInt': 'parseInt', 'upper': function(args) { return fncall('toUpperCase', args, STRING, 0); }, 'lower': function(args) { return fncall('toLowerCase', args, STRING, 0); }, 'slice': function(args) { return fncall('slice', args, STRING); }, 'substring': function(args) { return fncall('substring', args, STRING); }, // REGEXP functions 'test': function(args) { return fncall('test', args, REGEXP); }, // Control Flow functions 'if': function(args) { if (args.length < 3) throw new Error('Missing arguments to if function.'); if (args.length > 3) throw new Error('Too many arguments to if function.'); var a = args.map(codegen); return a[0]+'?'+a[1]+':'+a[2]; } }; }; },{}],43:[function(require,module,exports){ var parser = require('./parser'), codegen = require('./codegen'); var expr = module.exports = { parse: function(input, opt) { return parser.parse('('+input+')', opt); }, code: function(opt) { return codegen(opt); }, compiler: function(args, opt) { args = args.slice(); var generator = codegen(opt), len = args.length, compile = function(str) { var value = generator(expr.parse(str)); args[len] = '"use strict"; return (' + value.code + ');'; value.fn = Function.apply(null, args); return value; }; compile.codegen = generator; return compile; }, functions: require('./functions'), constants: require('./constants') }; },{"./codegen":40,"./constants":41,"./functions":42,"./parser":44}],44:[function(require,module,exports){ /* The following expression parser is based on Esprima (http://esprima.org/). Original header comment and license for Esprima is included here: Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com> Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com> Copyright (C) 2013 Mathias Bynens <mathias@qiwi.be> Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com> Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be> Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl> Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com> Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com> Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com> Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* istanbul ignore next */ module.exports = (function() { 'use strict'; var Token, TokenName, Syntax, PropertyKind, Messages, Regex, source, strict, index, lineNumber, lineStart, length, lookahead, state, extra; Token = { BooleanLiteral: 1, EOF: 2, Identifier: 3, Keyword: 4, NullLiteral: 5, NumericLiteral: 6, Punctuator: 7, StringLiteral: 8, RegularExpression: 9 }; TokenName = {}; TokenName[Token.BooleanLiteral] = 'Boolean'; TokenName[Token.EOF] = '<end>'; TokenName[Token.Identifier] = 'Identifier'; TokenName[Token.Keyword] = 'Keyword'; TokenName[Token.NullLiteral] = 'Null'; TokenName[Token.NumericLiteral] = 'Numeric'; TokenName[Token.Punctuator] = 'Punctuator'; TokenName[Token.StringLiteral] = 'String'; TokenName[Token.RegularExpression] = 'RegularExpression'; Syntax = { AssignmentExpression: 'AssignmentExpression', ArrayExpression: 'ArrayExpression', BinaryExpression: 'BinaryExpression', CallExpression: 'CallExpression', ConditionalExpression: 'ConditionalExpression', ExpressionStatement: 'ExpressionStatement', Identifier: 'Identifier', Literal: 'Literal', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', ObjectExpression: 'ObjectExpression', Program: 'Program', Property: 'Property', UnaryExpression: 'UnaryExpression' }; PropertyKind = { Data: 1, Get: 2, Set: 4 }; // Error messages should be identical to V8. Messages = { UnexpectedToken: 'Unexpected token %0', UnexpectedNumber: 'Unexpected number', UnexpectedString: 'Unexpected string', UnexpectedIdentifier: 'Unexpected identifier', UnexpectedReserved: 'Unexpected reserved word', UnexpectedEOS: 'Unexpected end of input', NewlineAfterThrow: 'Illegal newline after throw', InvalidRegExp: 'Invalid regular expression', UnterminatedRegExp: 'Invalid regular expression: missing /', InvalidLHSInAssignment: 'Invalid left-hand side in assignment', InvalidLHSInForIn: 'Invalid left-hand side in for-in', MultipleDefaultsInSwitch: 'More than one default clause in switch statement', NoCatchOrFinally: 'Missing catch or finally after try', UnknownLabel: 'Undefined label \'%0\'', Redeclaration: '%0 \'%1\' has already been declared', IllegalContinue: 'Illegal continue statement', IllegalBreak: 'Illegal break statement', IllegalReturn: 'Illegal return statement', StrictModeWith: 'Strict mode code may not include a with statement', StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', StrictVarName: 'Variable name may not be eval or arguments in strict mode', StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', StrictParamDupe: 'Strict mode function may not have duplicate parameter names', StrictFunctionName: 'Function name may not be eval or arguments in strict mode', StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', StrictDelete: 'Delete of an unqualified identifier in strict mode.', StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode', AccessorDataProperty: 'Object literal may not have data and accessor property with the same name', AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', StrictReservedWord: 'Use of future reserved word in strict mode' }; // See also tools/generate-unicode-regex.py. Regex = { NonAsciiIdentifierStart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'), NonAsciiIdentifierPart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]') }; // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. function assert(condition, message) { if (!condition) { throw new Error('ASSERT: ' + message); } } function isDecimalDigit(ch) { return (ch >= 0x30 && ch <= 0x39); // 0..9 } function isHexDigit(ch) { return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; } function isOctalDigit(ch) { return '01234567'.indexOf(ch) >= 0; } // 7.2 White Space function isWhiteSpace(ch) { return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) || (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0); } // 7.3 Line Terminators function isLineTerminator(ch) { return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029); } // 7.6 Identifier Names and Identifiers function isIdentifierStart(ch) { return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) (ch >= 0x41 && ch <= 0x5A) || // A..Z (ch >= 0x61 && ch <= 0x7A) || // a..z (ch === 0x5C) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); } function isIdentifierPart(ch) { return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) (ch >= 0x41 && ch <= 0x5A) || // A..Z (ch >= 0x61 && ch <= 0x7A) || // a..z (ch >= 0x30 && ch <= 0x39) || // 0..9 (ch === 0x5C) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); } // 7.6.1.2 Future Reserved Words function isFutureReservedWord(id) { switch (id) { case 'class': case 'enum': case 'export': case 'extends': case 'import': case 'super': return true; default: return false; } } function isStrictModeReservedWord(id) { switch (id) { case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'yield': case 'let': return true; default: return false; } } // 7.6.1.1 Keywords function isKeyword(id) { if (strict && isStrictModeReservedWord(id)) { return true; } // 'const' is specialized as Keyword in V8. // 'yield' and 'let' are for compatiblity with SpiderMonkey and ES.next. // Some others are from future reserved words. switch (id.length) { case 2: return (id === 'if') || (id === 'in') || (id === 'do'); case 3: return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try') || (id === 'let'); case 4: return (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with') || (id === 'enum'); case 5: return (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw') || (id === 'const') || (id === 'yield') || (id === 'class') || (id === 'super'); case 6: return (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') || (id === 'import'); case 7: return (id === 'default') || (id === 'finally') || (id === 'extends'); case 8: return (id === 'function') || (id === 'continue') || (id === 'debugger'); case 10: return (id === 'instanceof'); default: return false; } } function skipComment() { var ch, start; start = (index === 0); while (index < length) { ch = source.charCodeAt(index); if (isWhiteSpace(ch)) { ++index; } else if (isLineTerminator(ch)) { ++index; if (ch === 0x0D && source.charCodeAt(index) === 0x0A) { ++index; } ++lineNumber; lineStart = index; start = true; } else { break; } } } function scanHexEscape(prefix) { var i, len, ch, code = 0; len = (prefix === 'u') ? 4 : 2; for (i = 0; i < len; ++i) { if (index < length && isHexDigit(source[index])) { ch = source[index++]; code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } else { return ''; } } return String.fromCharCode(code); } function scanUnicodeCodePointEscape() { var ch, code, cu1, cu2; ch = source[index]; code = 0; // At least, one hex digit is required. if (ch === '}') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } while (index < length) { ch = source[index++]; if (!isHexDigit(ch)) { break; } code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } if (code > 0x10FFFF || ch !== '}') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // UTF-16 Encoding if (code <= 0xFFFF) { return String.fromCharCode(code); } cu1 = ((code - 0x10000) >> 10) + 0xD800; cu2 = ((code - 0x10000) & 1023) + 0xDC00; return String.fromCharCode(cu1, cu2); } function getEscapedIdentifier() { var ch, id; ch = source.charCodeAt(index++); id = String.fromCharCode(ch); // '\u' (U+005C, U+0075) denotes an escaped character. if (ch === 0x5C) { if (source.charCodeAt(index) !== 0x75) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } id = ch; } while (index < length) { ch = source.charCodeAt(index); if (!isIdentifierPart(ch)) { break; } ++index; id += String.fromCharCode(ch); // '\u' (U+005C, U+0075) denotes an escaped character. if (ch === 0x5C) { id = id.substr(0, id.length - 1); if (source.charCodeAt(index) !== 0x75) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } id += ch; } } return id; } function getIdentifier() { var start, ch; start = index++; while (index < length) { ch = source.charCodeAt(index); if (ch === 0x5C) { // Blackslash (U+005C) marks Unicode escape sequence. index = start; return getEscapedIdentifier(); } if (isIdentifierPart(ch)) { ++index; } else { break; } } return source.slice(start, index); } function scanIdentifier() { var start, id, type; start = index; // Backslash (U+005C) starts an escaped character. id = (source.charCodeAt(index) === 0x5C) ? getEscapedIdentifier() : getIdentifier(); // There is no keyword or literal with only one character. // Thus, it must be an identifier. if (id.length === 1) { type = Token.Identifier; } else if (isKeyword(id)) { type = Token.Keyword; } else if (id === 'null') { type = Token.NullLiteral; } else if (id === 'true' || id === 'false') { type = Token.BooleanLiteral; } else { type = Token.Identifier; } return { type: type, value: id, lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } // 7.7 Punctuators function scanPunctuator() { var start = index, code = source.charCodeAt(index), code2, ch1 = source[index], ch2, ch3, ch4; switch (code) { // Check for most common single-character punctuators. case 0x2E: // . dot case 0x28: // ( open bracket case 0x29: // ) close bracket case 0x3B: // ; semicolon case 0x2C: // , comma case 0x7B: // { open curly brace case 0x7D: // } close curly brace case 0x5B: // [ case 0x5D: // ] case 0x3A: // : case 0x3F: // ? case 0x7E: // ~ ++index; if (extra.tokenize) { if (code === 0x28) { extra.openParenToken = extra.tokens.length; } else if (code === 0x7B) { extra.openCurlyToken = extra.tokens.length; } } return { type: Token.Punctuator, value: String.fromCharCode(code), lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; default: code2 = source.charCodeAt(index + 1); // '=' (U+003D) marks an assignment or comparison operator. if (code2 === 0x3D) { switch (code) { case 0x2B: // + case 0x2D: // - case 0x2F: // / case 0x3C: // < case 0x3E: // > case 0x5E: // ^ case 0x7C: // | case 0x25: // % case 0x26: // & case 0x2A: // * index += 2; return { type: Token.Punctuator, value: String.fromCharCode(code) + String.fromCharCode(code2), lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; case 0x21: // ! case 0x3D: // = index += 2; // !== and === if (source.charCodeAt(index) === 0x3D) { ++index; } return { type: Token.Punctuator, value: source.slice(start, index), lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } } } // 4-character punctuator: >>>= ch4 = source.substr(index, 4); if (ch4 === '>>>=') { index += 4; return { type: Token.Punctuator, value: ch4, lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } // 3-character punctuators: === !== >>> <<= >>= ch3 = ch4.substr(0, 3); if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') { index += 3; return { type: Token.Punctuator, value: ch3, lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } // Other 2-character punctuators: ++ -- << >> && || ch2 = ch3.substr(0, 2); if ((ch1 === ch2[1] && ('+-<>&|'.indexOf(ch1) >= 0)) || ch2 === '=>') { index += 2; return { type: Token.Punctuator, value: ch2, lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } // 1-character punctuators: < > = ! + - * % & | ^ / if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // 7.8.3 Numeric Literals function scanHexLiteral(start) { var number = ''; while (index < length) { if (!isHexDigit(source[index])) { break; } number += source[index++]; } if (number.length === 0) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseInt('0x' + number, 16), lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } function scanOctalLiteral(start) { var number = '0' + source[index++]; while (index < length) { if (!isOctalDigit(source[index])) { break; } number += source[index++]; } if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseInt(number, 8), octal: true, lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } function scanNumericLiteral() { var number, start, ch; ch = source[index]; assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); start = index; number = ''; if (ch !== '.') { number = source[index++]; ch = source[index]; // Hex number starts with '0x'. // Octal number starts with '0'. if (number === '0') { if (ch === 'x' || ch === 'X') { ++index; return scanHexLiteral(start); } if (isOctalDigit(ch)) { return scanOctalLiteral(start); } // decimal number starts with '0' such as '09' is illegal. if (ch && isDecimalDigit(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === '.') { number += source[index++]; while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === 'e' || ch === 'E') { number += source[index++]; ch = source[index]; if (ch === '+' || ch === '-') { number += source[index++]; } if (isDecimalDigit(source.charCodeAt(index))) { while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } } else { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseFloat(number), lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } // 7.8.4 String Literals function scanStringLiteral() { var str = '', quote, start, ch, code, unescaped, restore, octal = false, startLineNumber, startLineStart; startLineNumber = lineNumber; startLineStart = lineStart; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; while (index < length) { ch = source[index++]; if (ch === quote) { quote = ''; break; } else if (ch === '\\') { ch = source[index++]; if (!ch || !isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'u': case 'x': if (source[index] === '{') { ++index; str += scanUnicodeCodePointEscape(); } else { restore = index; unescaped = scanHexEscape(ch); if (unescaped) { str += unescaped; } else { index = restore; str += ch; } } break; case 'n': str += '\n'; break; case 'r': str += '\r'; break; case 't': str += '\t'; break; case 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } str += String.fromCharCode(code); } else { str += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; } } else if (isLineTerminator(ch.charCodeAt(0))) { break; } else { str += ch; } } if (quote !== '') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.StringLiteral, value: str, octal: octal, startLineNumber: startLineNumber, startLineStart: startLineStart, lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } function testRegExp(pattern, flags) { var tmp = pattern, value; if (flags.indexOf('u') >= 0) { // Replace each astral symbol and every Unicode code point // escape sequence with a single ASCII symbol to avoid throwing on // regular expressions that are only valid in combination with the // `/u` flag. // Note: replacing with the ASCII symbol `x` might cause false // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a // perfectly valid pattern that is equivalent to `[a-b]`, but it // would be replaced by `[x-b]` which throws an error. tmp = tmp .replace(/\\u\{([0-9a-fA-F]+)\}/g, function ($0, $1) { if (parseInt($1, 16) <= 0x10FFFF) { return 'x'; } throwError({}, Messages.InvalidRegExp); }) .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x'); } // First, detect invalid regular expressions. try { value = new RegExp(tmp); } catch (e) { throwError({}, Messages.InvalidRegExp); } // Return a regular expression object for this pattern-flag pair, or // `null` in case the current environment doesn't support the flags it // uses. try { return new RegExp(pattern, flags); } catch (exception) { return null; } } function scanRegExpBody() { var ch, str, classMarker, terminated, body; ch = source[index]; assert(ch === '/', 'Regular expression literal must start with a slash'); str = source[index++]; classMarker = false; terminated = false; while (index < length) { ch = source[index++]; str += ch; if (ch === '\\') { ch = source[index++]; // ECMA-262 7.8.5 if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, Messages.UnterminatedRegExp); } str += ch; } else if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, Messages.UnterminatedRegExp); } else if (classMarker) { if (ch === ']') { classMarker = false; } } else { if (ch === '/') { terminated = true; break; } else if (ch === '[') { classMarker = true; } } } if (!terminated) { throwError({}, Messages.UnterminatedRegExp); } // Exclude leading and trailing slash. body = str.substr(1, str.length - 2); return { value: body, literal: str }; } function scanRegExpFlags() { var ch, str, flags, restore; str = ''; flags = ''; while (index < length) { ch = source[index]; if (!isIdentifierPart(ch.charCodeAt(0))) { break; } ++index; if (ch === '\\' && index < length) { ch = source[index]; if (ch === 'u') { ++index; restore = index; ch = scanHexEscape('u'); if (ch) { flags += ch; for (str += '\\u'; restore < index; ++restore) { str += source[restore]; } } else { index = restore; flags += 'u'; str += '\\u'; } throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); } else { str += '\\'; throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { flags += ch; str += ch; } } return { value: flags, literal: str }; } function scanRegExp() { var start, body, flags, value; lookahead = null; skipComment(); start = index; body = scanRegExpBody(); flags = scanRegExpFlags(); value = testRegExp(body.value, flags.value); if (extra.tokenize) { return { type: Token.RegularExpression, value: value, regex: { pattern: body.value, flags: flags.value }, lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } return { literal: body.literal + flags.literal, value: value, regex: { pattern: body.value, flags: flags.value }, start: start, end: index }; } function collectRegex() { var pos, loc, regex, token; skipComment(); pos = index; loc = { start: { line: lineNumber, column: index - lineStart } }; regex = scanRegExp(); loc.end = { line: lineNumber, column: index - lineStart }; if (!extra.tokenize) { // Pop the previous token, which is likely '/' or '/=' if (extra.tokens.length > 0) { token = extra.tokens[extra.tokens.length - 1]; if (token.range[0] === pos && token.type === 'Punctuator') { if (token.value === '/' || token.value === '/=') { extra.tokens.pop(); } } } extra.tokens.push({ type: 'RegularExpression', value: regex.literal, regex: regex.regex, range: [pos, index], loc: loc }); } return regex; } function isIdentifierName(token) { return token.type === Token.Identifier || token.type === Token.Keyword || token.type === Token.BooleanLiteral || token.type === Token.NullLiteral; } function advanceSlash() { var prevToken, checkToken; // Using the following algorithm: // https://github.com/mozilla/sweet.js/wiki/design prevToken = extra.tokens[extra.tokens.length - 1]; if (!prevToken) { // Nothing before that: it cannot be a division. return collectRegex(); } if (prevToken.type === 'Punctuator') { if (prevToken.value === ']') { return scanPunctuator(); } if (prevToken.value === ')') { checkToken = extra.tokens[extra.openParenToken - 1]; if (checkToken && checkToken.type === 'Keyword' && (checkToken.value === 'if' || checkToken.value === 'while' || checkToken.value === 'for' || checkToken.value === 'with')) { return collectRegex(); } return scanPunctuator(); } if (prevToken.value === '}') { // Dividing a function by anything makes little sense, // but we have to check for that. if (extra.tokens[extra.openCurlyToken - 3] && extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') { // Anonymous function. checkToken = extra.tokens[extra.openCurlyToken - 4]; if (!checkToken) { return scanPunctuator(); } } else if (extra.tokens[extra.openCurlyToken - 4] && extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') { // Named function. checkToken = extra.tokens[extra.openCurlyToken - 5]; if (!checkToken) { return collectRegex(); } } else { return scanPunctuator(); } return scanPunctuator(); } return collectRegex(); } if (prevToken.type === 'Keyword' && prevToken.value !== 'this') { return collectRegex(); } return scanPunctuator(); } function advance() { var ch; skipComment(); if (index >= length) { return { type: Token.EOF, lineNumber: lineNumber, lineStart: lineStart, start: index, end: index }; } ch = source.charCodeAt(index); if (isIdentifierStart(ch)) { return scanIdentifier(); } // Very common: ( and ) and ; if (ch === 0x28 || ch === 0x29 || ch === 0x3B) { return scanPunctuator(); } // String literal starts with single quote (U+0027) or double quote (U+0022). if (ch === 0x27 || ch === 0x22) { return scanStringLiteral(); } // Dot (.) U+002E can also start a floating-point number, hence the need // to check the next character. if (ch === 0x2E) { if (isDecimalDigit(source.charCodeAt(index + 1))) { return scanNumericLiteral(); } return scanPunctuator(); } if (isDecimalDigit(ch)) { return scanNumericLiteral(); } // Slash (/) U+002F can also start a regex. if (extra.tokenize && ch === 0x2F) { return advanceSlash(); } return scanPunctuator(); } function collectToken() { var loc, token, value, entry; skipComment(); loc = { start: { line: lineNumber, column: index - lineStart } }; token = advance(); loc.end = { line: lineNumber, column: index - lineStart }; if (token.type !== Token.EOF) { value = source.slice(token.start, token.end); entry = { type: TokenName[token.type], value: value, range: [token.start, token.end], loc: loc }; if (token.regex) { entry.regex = { pattern: token.regex.pattern, flags: token.regex.flags }; } extra.tokens.push(entry); } return token; } function lex() { var token; token = lookahead; index = token.end; lineNumber = token.lineNumber; lineStart = token.lineStart; lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance(); index = token.end; lineNumber = token.lineNumber; lineStart = token.lineStart; return token; } function peek() { var pos, line, start; pos = index; line = lineNumber; start = lineStart; lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance(); index = pos; lineNumber = line; lineStart = start; } function Position() { this.line = lineNumber; this.column = index - lineStart; } function SourceLocation() { this.start = new Position(); this.end = null; } function WrappingSourceLocation(startToken) { if (startToken.type === Token.StringLiteral) { this.start = { line: startToken.startLineNumber, column: startToken.start - startToken.startLineStart }; } else { this.start = { line: startToken.lineNumber, column: startToken.start - startToken.lineStart }; } this.end = null; } function Node() { // Skip comment. index = lookahead.start; if (lookahead.type === Token.StringLiteral) { lineNumber = lookahead.startLineNumber; lineStart = lookahead.startLineStart; } else { lineNumber = lookahead.lineNumber; lineStart = lookahead.lineStart; } if (extra.range) { this.range = [index, 0]; } if (extra.loc) { this.loc = new SourceLocation(); } } function WrappingNode(startToken) { if (extra.range) { this.range = [startToken.start, 0]; } if (extra.loc) { this.loc = new WrappingSourceLocation(startToken); } } WrappingNode.prototype = Node.prototype = { finish: function () { if (extra.range) { this.range[1] = index; } if (extra.loc) { this.loc.end = new Position(); if (extra.source) { this.loc.source = extra.source; } } }, finishArrayExpression: function (elements) { this.type = Syntax.ArrayExpression; this.elements = elements; this.finish(); return this; }, finishAssignmentExpression: function (operator, left, right) { this.type = Syntax.AssignmentExpression; this.operator = operator; this.left = left; this.right = right; this.finish(); return this; }, finishBinaryExpression: function (operator, left, right) { this.type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression; this.operator = operator; this.left = left; this.right = right; this.finish(); return this; }, finishCallExpression: function (callee, args) { this.type = Syntax.CallExpression; this.callee = callee; this.arguments = args; this.finish(); return this; }, finishConditionalExpression: function (test, consequent, alternate) { this.type = Syntax.ConditionalExpression; this.test = test; this.consequent = consequent; this.alternate = alternate; this.finish(); return this; }, finishExpressionStatement: function (expression) { this.type = Syntax.ExpressionStatement; this.expression = expression; this.finish(); return this; }, finishIdentifier: function (name) { this.type = Syntax.Identifier; this.name = name; this.finish(); return this; }, finishLiteral: function (token) { this.type = Syntax.Literal; this.value = token.value; this.raw = source.slice(token.start, token.end); if (token.regex) { if (this.raw == '//') { this.raw = '/(?:)/'; } this.regex = token.regex; } this.finish(); return this; }, finishMemberExpression: function (accessor, object, property) { this.type = Syntax.MemberExpression; this.computed = accessor === '['; this.object = object; this.property = property; this.finish(); return this; }, finishObjectExpression: function (properties) { this.type = Syntax.ObjectExpression; this.properties = properties; this.finish(); return this; }, finishProgram: function (body) { this.type = Syntax.Program; this.body = body; this.finish(); return this; }, finishProperty: function (kind, key, value) { this.type = Syntax.Property; this.key = key; this.value = value; this.kind = kind; this.finish(); return this; }, finishUnaryExpression: function (operator, argument) { this.type = Syntax.UnaryExpression; this.operator = operator; this.argument = argument; this.prefix = true; this.finish(); return this; } }; // Return true if there is a line terminator before the next token. function peekLineTerminator() { var pos, line, start, found; pos = index; line = lineNumber; start = lineStart; skipComment(); found = lineNumber !== line; index = pos; lineNumber = line; lineStart = start; return found; } // Throw an exception function throwError(token, messageFormat) { var error, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace( /%(\d)/g, function (whole, index) { assert(index < args.length, 'Message reference must be in range'); return args[index]; } ); if (typeof token.lineNumber === 'number') { error = new Error('Line ' + token.lineNumber + ': ' + msg); error.index = token.start; error.lineNumber = token.lineNumber; error.column = token.start - lineStart + 1; } else { error = new Error('Line ' + lineNumber + ': ' + msg); error.index = index; error.lineNumber = lineNumber; error.column = index - lineStart + 1; } error.description = msg; throw error; } function throwErrorTolerant() { try { throwError.apply(null, arguments); } catch (e) { if (extra.errors) { extra.errors.push(e); } else { throw e; } } } // Throw an exception because of the token. function throwUnexpected(token) { if (token.type === Token.EOF) { throwError(token, Messages.UnexpectedEOS); } if (token.type === Token.NumericLiteral) { throwError(token, Messages.UnexpectedNumber); } if (token.type === Token.StringLiteral) { throwError(token, Messages.UnexpectedString); } if (token.type === Token.Identifier) { throwError(token, Messages.UnexpectedIdentifier); } if (token.type === Token.Keyword) { if (isFutureReservedWord(token.value)) { throwError(token, Messages.UnexpectedReserved); } else if (strict && isStrictModeReservedWord(token.value)) { throwErrorTolerant(token, Messages.StrictReservedWord); return; } throwError(token, Messages.UnexpectedToken, token.value); } // BooleanLiteral, NullLiteral, or Punctuator. throwError(token, Messages.UnexpectedToken, token.value); } // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. function expect(value) { var token = lex(); if (token.type !== Token.Punctuator || token.value !== value) { throwUnexpected(token); } } /** * @name expectTolerant * @description Quietly expect the given token value when in tolerant mode, otherwise delegates * to <code>expect(value)</code> * @param {String} value The value we are expecting the lookahead token to have * @since 2.0 */ function expectTolerant(value) { if (extra.errors) { var token = lookahead; if (token.type !== Token.Punctuator && token.value !== value) { throwErrorTolerant(token, Messages.UnexpectedToken, token.value); } else { lex(); } } else { expect(value); } } // Return true if the next token matches the specified punctuator. function match(value) { return lookahead.type === Token.Punctuator && lookahead.value === value; } // Return true if the next token matches the specified keyword function matchKeyword(keyword) { return lookahead.type === Token.Keyword && lookahead.value === keyword; } function consumeSemicolon() { var line; // Catch the very common case first: immediately a semicolon (U+003B). if (source.charCodeAt(index) === 0x3B || match(';')) { lex(); return; } line = lineNumber; skipComment(); if (lineNumber !== line) { return; } if (lookahead.type !== Token.EOF && !match('}')) { throwUnexpected(lookahead); } } // 11.1.4 Array Initialiser function parseArrayInitialiser() { var elements = [], node = new Node(); expect('['); while (!match(']')) { if (match(',')) { lex(); elements.push(null); } else { elements.push(parseAssignmentExpression()); if (!match(']')) { expect(','); } } } lex(); return node.finishArrayExpression(elements); } // 11.1.5 Object Initialiser function parseObjectPropertyKey() { var token, node = new Node(); token = lex(); // Note: This function is called only from parseObjectProperty(), where // EOF and Punctuator tokens are already filtered out. if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { if (strict && token.octal) { throwErrorTolerant(token, Messages.StrictOctalLiteral); } return node.finishLiteral(token); } return node.finishIdentifier(token.value); } function parseObjectProperty() { var token, key, id, value, node = new Node(); token = lookahead; if (token.type === Token.Identifier) { id = parseObjectPropertyKey(); expect(':'); value = parseAssignmentExpression(); return node.finishProperty('init', id, value); } if (token.type === Token.EOF || token.type === Token.Punctuator) { throwUnexpected(token); } else { key = parseObjectPropertyKey(); expect(':'); value = parseAssignmentExpression(); return node.finishProperty('init', key, value); } } function parseObjectInitialiser() { var properties = [], property, name, key, kind, map = {}, toString = String, node = new Node(); expect('{'); while (!match('}')) { property = parseObjectProperty(); if (property.key.type === Syntax.Identifier) { name = property.key.name; } else { name = toString(property.key.value); } kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; key = '$' + name; if (Object.prototype.hasOwnProperty.call(map, key)) { if (map[key] === PropertyKind.Data) { if (strict && kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.StrictDuplicateProperty); } else if (kind !== PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } } else { if (kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } else if (map[key] & kind) { throwErrorTolerant({}, Messages.AccessorGetSet); } } map[key] |= kind; } else { map[key] = kind; } properties.push(property); if (!match('}')) { expectTolerant(','); } } expect('}'); return node.finishObjectExpression(properties); } // 11.1.6 The Grouping Operator function parseGroupExpression() { var expr; expect('('); ++state.parenthesisCount; expr = parseExpression(); expect(')'); return expr; } // 11.1 Primary Expressions var legalKeywords = {"if":1, "this":1}; function parsePrimaryExpression() { var type, token, expr, node; if (match('(')) { return parseGroupExpression(); } if (match('[')) { return parseArrayInitialiser(); } if (match('{')) { return parseObjectInitialiser(); } type = lookahead.type; node = new Node(); if (type === Token.Identifier || legalKeywords[lookahead.value]) { expr = node.finishIdentifier(lex().value); } else if (type === Token.StringLiteral || type === Token.NumericLiteral) { if (strict && lookahead.octal) { throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); } expr = node.finishLiteral(lex()); } else if (type === Token.Keyword) { throw new Error("Disabled."); } else if (type === Token.BooleanLiteral) { token = lex(); token.value = (token.value === 'true'); expr = node.finishLiteral(token); } else if (type === Token.NullLiteral) { token = lex(); token.value = null; expr = node.finishLiteral(token); } else if (match('/') || match('/=')) { if (typeof extra.tokens !== 'undefined') { expr = node.finishLiteral(collectRegex()); } else { expr = node.finishLiteral(scanRegExp()); } peek(); } else { throwUnexpected(lex()); } return expr; } // 11.2 Left-Hand-Side Expressions function parseArguments() { var args = []; expect('('); if (!match(')')) { while (index < length) { args.push(parseAssignmentExpression()); if (match(')')) { break; } expectTolerant(','); } } expect(')'); return args; } function parseNonComputedProperty() { var token, node = new Node(); token = lex(); if (!isIdentifierName(token)) { throwUnexpected(token); } return node.finishIdentifier(token.value); } function parseNonComputedMember() { expect('.'); return parseNonComputedProperty(); } function parseComputedMember() { var expr; expect('['); expr = parseExpression(); expect(']'); return expr; } function parseLeftHandSideExpressionAllowCall() { var expr, args, property, startToken, previousAllowIn = state.allowIn; startToken = lookahead; state.allowIn = true; expr = parsePrimaryExpression(); for (;;) { if (match('.')) { property = parseNonComputedMember(); expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property); } else if (match('(')) { args = parseArguments(); expr = new WrappingNode(startToken).finishCallExpression(expr, args); } else if (match('[')) { property = parseComputedMember(); expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property); } else { break; } } state.allowIn = previousAllowIn; return expr; } // 11.3 Postfix Expressions function parsePostfixExpression() { var expr = parseLeftHandSideExpressionAllowCall(); if (lookahead.type === Token.Punctuator) { if ((match('++') || match('--')) && !peekLineTerminator()) { throw new Error("Disabled."); } } return expr; } // 11.4 Unary Operators function parseUnaryExpression() { var token, expr, startToken; if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { expr = parsePostfixExpression(); } else if (match('++') || match('--')) { throw new Error("Disabled."); } else if (match('+') || match('-') || match('~') || match('!')) { startToken = lookahead; token = lex(); expr = parseUnaryExpression(); expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr); } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { throw new Error("Disabled."); } else { expr = parsePostfixExpression(); } return expr; } function binaryPrecedence(token, allowIn) { var prec = 0; if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { return 0; } switch (token.value) { case '||': prec = 1; break; case '&&': prec = 2; break; case '|': prec = 3; break; case '^': prec = 4; break; case '&': prec = 5; break; case '==': case '!=': case '===': case '!==': prec = 6; break; case '<': case '>': case '<=': case '>=': case 'instanceof': prec = 7; break; case 'in': prec = allowIn ? 7 : 0; break; case '<<': case '>>': case '>>>': prec = 8; break; case '+': case '-': prec = 9; break; case '*': case '/': case '%': prec = 11; break; default: break; } return prec; } // 11.5 Multiplicative Operators // 11.6 Additive Operators // 11.7 Bitwise Shift Operators // 11.8 Relational Operators // 11.9 Equality Operators // 11.10 Binary Bitwise Operators // 11.11 Binary Logical Operators function parseBinaryExpression() { var marker, markers, expr, token, prec, stack, right, operator, left, i; marker = lookahead; left = parseUnaryExpression(); token = lookahead; prec = binaryPrecedence(token, state.allowIn); if (prec === 0) { return left; } token.prec = prec; lex(); markers = [marker, lookahead]; right = parseUnaryExpression(); stack = [left, token, right]; while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) { // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { right = stack.pop(); operator = stack.pop().value; left = stack.pop(); markers.pop(); expr = new WrappingNode(markers[markers.length - 1]).finishBinaryExpression(operator, left, right); stack.push(expr); } // Shift. token = lex(); token.prec = prec; stack.push(token); markers.push(lookahead); expr = parseUnaryExpression(); stack.push(expr); } // Final reduce to clean-up the stack. i = stack.length - 1; expr = stack[i]; markers.pop(); while (i > 1) { expr = new WrappingNode(markers.pop()).finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr); i -= 2; } return expr; } // 11.12 Conditional Operator function parseConditionalExpression() { var expr, previousAllowIn, consequent, alternate, startToken; startToken = lookahead; expr = parseBinaryExpression(); if (match('?')) { lex(); previousAllowIn = state.allowIn; state.allowIn = true; consequent = parseAssignmentExpression(); state.allowIn = previousAllowIn; expect(':'); alternate = parseAssignmentExpression(); expr = new WrappingNode(startToken).finishConditionalExpression(expr, consequent, alternate); } return expr; } // 11.13 Assignment Operators function parseAssignmentExpression() { var oldParenthesisCount, token, expr, startToken; oldParenthesisCount = state.parenthesisCount; startToken = lookahead; token = lookahead; expr = parseConditionalExpression(); return expr; } // 11.14 Comma Operator function parseExpression() { var expr = parseAssignmentExpression(); if (match(',')) { throw new Error("Disabled."); // no sequence expressions } return expr; } // 12.4 Expression Statement function parseExpressionStatement(node) { var expr = parseExpression(); consumeSemicolon(); return node.finishExpressionStatement(expr); } // 12 Statements function parseStatement() { var type = lookahead.type, expr, node; if (type === Token.EOF) { throwUnexpected(lookahead); } if (type === Token.Punctuator && lookahead.value === '{') { throw new Error("Disabled."); // block statement } node = new Node(); if (type === Token.Punctuator) { switch (lookahead.value) { case ';': throw new Error("Disabled."); // empty statement case '(': return parseExpressionStatement(node); default: break; } } else if (type === Token.Keyword) { throw new Error("Disabled."); // keyword } expr = parseExpression(); consumeSemicolon(); return node.finishExpressionStatement(expr); } // 14 Program function parseSourceElement() { if (lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'const': case 'let': throw new Error("Disabled."); case 'function': throw new Error("Disabled."); default: return parseStatement(); } } if (lookahead.type !== Token.EOF) { return parseStatement(); } } function parseSourceElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted; while (index < length) { token = lookahead; if (token.type !== Token.StringLiteral) { break; } sourceElement = parseSourceElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.start + 1, token.end - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } while (index < length) { sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } return sourceElements; } function parseProgram() { var body, node; skipComment(); peek(); node = new Node(); strict = true; // assume strict body = parseSourceElements(); return node.finishProgram(body); } function filterTokenLocation() { var i, entry, token, tokens = []; for (i = 0; i < extra.tokens.length; ++i) { entry = extra.tokens[i]; token = { type: entry.type, value: entry.value }; if (entry.regex) { token.regex = { pattern: entry.regex.pattern, flags: entry.regex.flags }; } if (extra.range) { token.range = entry.range; } if (extra.loc) { token.loc = entry.loc; } tokens.push(token); } extra.tokens = tokens; } function tokenize(code, options) { var toString, tokens; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { allowIn: true, labelSet: {}, inFunctionBody: false, inIteration: false, inSwitch: false, lastCommentStart: -1 }; extra = {}; // Options matching. options = options || {}; // Of course we collect tokens here. options.tokens = true; extra.tokens = []; extra.tokenize = true; // The following two fields are necessary to compute the Regex tokens. extra.openParenToken = -1; extra.openCurlyToken = -1; extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } try { peek(); if (lookahead.type === Token.EOF) { return extra.tokens; } lex(); while (lookahead.type !== Token.EOF) { try { lex(); } catch (lexError) { if (extra.errors) { extra.errors.push(lexError); // We have to break on the first error // to avoid infinite loops. break; } else { throw lexError; } } } filterTokenLocation(); tokens = extra.tokens; if (typeof extra.errors !== 'undefined') { tokens.errors = extra.errors; } } catch (e) { throw e; } finally { extra = {}; } return tokens; } function parse(code, options) { var program, toString; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { allowIn: true, labelSet: {}, parenthesisCount: 0, inFunctionBody: false, inIteration: false, inSwitch: false, lastCommentStart: -1 }; extra = {}; if (typeof options !== 'undefined') { extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; if (extra.loc && options.source !== null && options.source !== undefined) { extra.source = toString(options.source); } if (typeof options.tokens === 'boolean' && options.tokens) { extra.tokens = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } } try { program = parseProgram(); if (typeof extra.tokens !== 'undefined') { filterTokenLocation(); program.tokens = extra.tokens; } if (typeof extra.errors !== 'undefined') { program.errors = extra.errors; } } catch (e) { throw e; } finally { extra = {}; } return program; } return { tokenize: tokenize, parse: parse }; })(); },{}],45:[function(require,module,exports){ var ts = Date.now(); function write(msg) { msg = '[Vega Log] ' + msg; console.log(msg); } function error(msg) { msg = '[Vega Err] ' + msg; console.error(msg); } function debug(input, args) { if (!debug.enable) return; var log = Function.prototype.bind.call(console.log, console); var state = { prevTime: Date.now() - ts, stamp: input.stamp }; if (input.add) { state.add = input.add.length; state.mod = input.mod.length; state.rem = input.rem.length; state.reflow = !!input.reflow; } log.apply(console, (args.push(JSON.stringify(state)), args)); ts = Date.now(); } module.exports = { log: write, error: error, debug: (debug.enable = false, debug) }; },{}],46:[function(require,module,exports){ module.exports = { path: require('./path'), render: require('./render'), Item: require('./util/Item'), bound: require('./util/bound'), Bounds: require('./util/Bounds'), Gradient: require('./util/Gradient'), toJSON: require('./util/scene').toJSON, fromJSON: require('./util/scene').fromJSON }; },{"./path":49,"./render":69,"./util/Bounds":75,"./util/Gradient":76,"./util/Item":78,"./util/bound":79,"./util/scene":83}],47:[function(require,module,exports){ var segmentCache = {}, bezierCache = {}, join = [].join; // Copied from Inkscape svgtopdf, thanks! function segments(x, y, rx, ry, large, sweep, rotateX, ox, oy) { var key = join.call(arguments); if (segmentCache[key]) { return segmentCache[key]; } var th = rotateX * (Math.PI/180); var sin_th = Math.sin(th); var cos_th = Math.cos(th); rx = Math.abs(rx); ry = Math.abs(ry); var px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5; var py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5; var pl = (px*px) / (rx*rx) + (py*py) / (ry*ry); if (pl > 1) { pl = Math.sqrt(pl); rx *= pl; ry *= pl; } var a00 = cos_th / rx; var a01 = sin_th / rx; var a10 = (-sin_th) / ry; var a11 = (cos_th) / ry; var x0 = a00 * ox + a01 * oy; var y0 = a10 * ox + a11 * oy; var x1 = a00 * x + a01 * y; var y1 = a10 * x + a11 * y; var d = (x1-x0) * (x1-x0) + (y1-y0) * (y1-y0); var sfactor_sq = 1 / d - 0.25; if (sfactor_sq < 0) sfactor_sq = 0; var sfactor = Math.sqrt(sfactor_sq); if (sweep == large) sfactor = -sfactor; var xc = 0.5 * (x0 + x1) - sfactor * (y1-y0); var yc = 0.5 * (y0 + y1) + sfactor * (x1-x0); var th0 = Math.atan2(y0-yc, x0-xc); var th1 = Math.atan2(y1-yc, x1-xc); var th_arc = th1-th0; if (th_arc < 0 && sweep === 1){ th_arc += 2 * Math.PI; } else if (th_arc > 0 && sweep === 0) { th_arc -= 2 * Math.PI; } var segs = Math.ceil(Math.abs(th_arc / (Math.PI * 0.5 + 0.001))); var result = []; for (var i=0; i<segs; ++i) { var th2 = th0 + i * th_arc / segs; var th3 = th0 + (i+1) * th_arc / segs; result[i] = [xc, yc, th2, th3, rx, ry, sin_th, cos_th]; } return (segmentCache[key] = result); } function bezier(params) { var key = join.call(params); if (bezierCache[key]) { return bezierCache[key]; } var cx = params[0], cy = params[1], th0 = params[2], th1 = params[3], rx = params[4], ry = params[5], sin_th = params[6], cos_th = params[7]; var a00 = cos_th * rx; var a01 = -sin_th * ry; var a10 = sin_th * rx; var a11 = cos_th * ry; var cos_th0 = Math.cos(th0); var sin_th0 = Math.sin(th0); var cos_th1 = Math.cos(th1); var sin_th1 = Math.sin(th1); var th_half = 0.5 * (th1 - th0); var sin_th_h2 = Math.sin(th_half * 0.5); var t = (8/3) * sin_th_h2 * sin_th_h2 / Math.sin(th_half); var x1 = cx + cos_th0 - t * sin_th0; var y1 = cy + sin_th0 + t * cos_th0; var x3 = cx + cos_th1; var y3 = cy + sin_th1; var x2 = x3 + t * sin_th1; var y2 = y3 - t * cos_th1; return (bezierCache[key] = [ a00 * x1 + a01 * y1, a10 * x1 + a11 * y1, a00 * x2 + a01 * y2, a10 * x2 + a11 * y2, a00 * x3 + a01 * y3, a10 * x3 + a11 * y3 ]); } module.exports = { segments: segments, bezier: bezier, cache: { segments: segmentCache, bezier: bezierCache } }; },{}],48:[function(require,module,exports){ var arc = require('./arc'); module.exports = function(path, bounds) { var current, // current instruction previous = null, x = 0, // current x y = 0, // current y controlX = 0, // current control point x controlY = 0, // current control point y tempX, tempY, tempControlX, tempControlY, i, len; for (i=0, len=path.length; i<len; ++i) { current = path[i]; switch (current[0]) { // command case 'l': // lineto, relative x += current[1]; y += current[2]; bounds.add(x, y); break; case 'L': // lineto, absolute x = current[1]; y = current[2]; bounds.add(x, y); break; case 'h': // horizontal lineto, relative x += current[1]; bounds.add(x, y); break; case 'H': // horizontal lineto, absolute x = current[1]; bounds.add(x, y); break; case 'v': // vertical lineto, relative y += current[1]; bounds.add(x, y); break; case 'V': // verical lineto, absolute y = current[1]; bounds.add(x, y); break; case 'm': // moveTo, relative x += current[1]; y += current[2]; bounds.add(x, y); break; case 'M': // moveTo, absolute x = current[1]; y = current[2]; bounds.add(x, y); break; case 'c': // bezierCurveTo, relative tempX = x + current[5]; tempY = y + current[6]; controlX = x + current[3]; controlY = y + current[4]; bounds.add(x + current[1], y + current[2]); bounds.add(controlX, controlY); bounds.add(tempX, tempY); x = tempX; y = tempY; break; case 'C': // bezierCurveTo, absolute x = current[5]; y = current[6]; controlX = current[3]; controlY = current[4]; bounds.add(current[1], current[2]); bounds.add(controlX, controlY); bounds.add(x, y); break; case 's': // shorthand cubic bezierCurveTo, relative // transform to absolute x,y tempX = x + current[3]; tempY = y + current[4]; // calculate reflection of previous control points controlX = 2 * x - controlX; controlY = 2 * y - controlY; bounds.add(controlX, controlY); bounds.add(x + current[1], y + current[2]); bounds.add(tempX, tempY); // set control point to 2nd one of this command // the first control point is assumed to be the reflection of // the second control point on the previous command relative // to the current point. controlX = x + current[1]; controlY = y + current[2]; x = tempX; y = tempY; break; case 'S': // shorthand cubic bezierCurveTo, absolute tempX = current[3]; tempY = current[4]; // calculate reflection of previous control points controlX = 2*x - controlX; controlY = 2*y - controlY; x = tempX; y = tempY; bounds.add(current[1], current[2]); bounds.add(controlX, controlY); bounds.add(tempX, tempY); // set control point to 2nd one of this command // the first control point is assumed to be the reflection of // the second control point on the previous command relative // to the current point. controlX = current[1]; controlY = current[2]; break; case 'q': // quadraticCurveTo, relative // transform to absolute x,y tempX = x + current[3]; tempY = y + current[4]; controlX = x + current[1]; controlY = y + current[2]; x = tempX; y = tempY; bounds.add(controlX, controlY); bounds.add(tempX, tempY); break; case 'Q': // quadraticCurveTo, absolute tempX = current[3]; tempY = current[4]; x = tempX; y = tempY; controlX = current[1]; controlY = current[2]; bounds.add(controlX, controlY); bounds.add(tempX, tempY); break; case 't': // shorthand quadraticCurveTo, relative // transform to absolute x,y tempX = x + current[1]; tempY = y + current[2]; if (previous[0].match(/[QqTt]/) === null) { // If there is no previous command or if the previous command was not a Q, q, T or t, // assume the control point is coincident with the current point controlX = x; controlY = y; } else if (previous[0] === 't') { // calculate reflection of previous control points for t controlX = 2 * x - tempControlX; controlY = 2 * y - tempControlY; } else if (previous[0] === 'q') { // calculate reflection of previous control points for q controlX = 2 * x - controlX; controlY = 2 * y - controlY; } tempControlX = controlX; tempControlY = controlY; x = tempX; y = tempY; controlX = x + current[1]; controlY = y + current[2]; bounds.add(controlX, controlY); bounds.add(tempX, tempY); break; case 'T': tempX = current[1]; tempY = current[2]; // calculate reflection of previous control points controlX = 2 * x - controlX; controlY = 2 * y - controlY; x = tempX; y = tempY; bounds.add(controlX, controlY); bounds.add(tempX, tempY); break; case 'a': boundArc(x, y, [ current[1], current[2], current[3], current[4], current[5], current[6] + x, current[7] + y ], bounds); x += current[6]; y += current[7]; break; case 'A': boundArc(x, y, [ current[1], current[2], current[3], current[4], current[5], current[6], current[7] ], bounds); x = current[6]; y = current[7]; break; case 'z': case 'Z': break; } previous = current; } return bounds; }; function boundArc(x, y, coords, bounds) { var seg = arc.segments( coords[5], // ex coords[6], // ey coords[0], // rx coords[1], // ry coords[3], // large coords[4], // sweep coords[2], // rot x, y ); for (var i=0; i<seg.length; ++i) { var bez = arc.bezier(seg[i]); bounds.add(bez[0], bez[1]); bounds.add(bez[2], bez[3]); bounds.add(bez[4], bez[5]); } } },{"./arc":47}],49:[function(require,module,exports){ module.exports = { parse: require('./parse'), render: require('./render'), bounds: require('./bounds') }; },{"./bounds":48,"./parse":50,"./render":51}],50:[function(require,module,exports){ // Path parsing and rendering code adapted from fabric.js -- Thanks! var cmdlen = { m:2, l:2, h:1, v:1, c:6, s:4, q:4, t:2, a:7 }, regexp = [/([MLHVCSQTAZmlhvcsqtaz])/g, /###/, /(\d)([-+])/g, /\s|,|###/]; module.exports = function(pathstr) { var result = [], path, curr, chunks, parsed, param, cmd, len, i, j, n, m; // First, break path into command sequence path = pathstr .slice() .replace(regexp[0], '###$1') .split(regexp[1]) .slice(1); // Next, parse each command in turn for (i=0, n=path.length; i<n; ++i) { curr = path[i]; chunks = curr .slice(1) .trim() .replace(regexp[2],'$1###$2') .split(regexp[3]); cmd = curr.charAt(0); parsed = [cmd]; for (j=0, m=chunks.length; j<m; ++j) { if ((param = +chunks[j]) === param) { // not NaN parsed.push(param); } } len = cmdlen[cmd.toLowerCase()]; if (parsed.length-1 > len) { for (j=1, m=parsed.length; j<m; j+=len) { result.push([cmd].concat(parsed.slice(j, j+len))); } } else { result.push(parsed); } } return result; }; },{}],51:[function(require,module,exports){ var arc = require('./arc'); module.exports = function(g, path, l, t) { var current, // current instruction previous = null, x = 0, // current x y = 0, // current y controlX = 0, // current control point x controlY = 0, // current control point y tempX, tempY, tempControlX, tempControlY; if (l == null) l = 0; if (t == null) t = 0; g.beginPath(); for (var i=0, len=path.length; i<len; ++i) { current = path[i]; switch (current[0]) { // first letter case 'l': // lineto, relative x += current[1]; y += current[2]; g.lineTo(x + l, y + t); break; case 'L': // lineto, absolute x = current[1]; y = current[2]; g.lineTo(x + l, y + t); break; case 'h': // horizontal lineto, relative x += current[1]; g.lineTo(x + l, y + t); break; case 'H': // horizontal lineto, absolute x = current[1]; g.lineTo(x + l, y + t); break; case 'v': // vertical lineto, relative y += current[1]; g.lineTo(x + l, y + t); break; case 'V': // verical lineto, absolute y = current[1]; g.lineTo(x + l, y + t); break; case 'm': // moveTo, relative x += current[1]; y += current[2]; g.moveTo(x + l, y + t); break; case 'M': // moveTo, absolute x = current[1]; y = current[2]; g.moveTo(x + l, y + t); break; case 'c': // bezierCurveTo, relative tempX = x + current[5]; tempY = y + current[6]; controlX = x + current[3]; controlY = y + current[4]; g.bezierCurveTo( x + current[1] + l, // x1 y + current[2] + t, // y1 controlX + l, // x2 controlY + t, // y2 tempX + l, tempY + t ); x = tempX; y = tempY; break; case 'C': // bezierCurveTo, absolute x = current[5]; y = current[6]; controlX = current[3]; controlY = current[4]; g.bezierCurveTo( current[1] + l, current[2] + t, controlX + l, controlY + t, x + l, y + t ); break; case 's': // shorthand cubic bezierCurveTo, relative // transform to absolute x,y tempX = x + current[3]; tempY = y + current[4]; // calculate reflection of previous control points controlX = 2 * x - controlX; controlY = 2 * y - controlY; g.bezierCurveTo( controlX + l, controlY + t, x + current[1] + l, y + current[2] + t, tempX + l, tempY + t ); // set control point to 2nd one of this command // the first control point is assumed to be the reflection of // the second control point on the previous command relative // to the current point. controlX = x + current[1]; controlY = y + current[2]; x = tempX; y = tempY; break; case 'S': // shorthand cubic bezierCurveTo, absolute tempX = current[3]; tempY = current[4]; // calculate reflection of previous control points controlX = 2*x - controlX; controlY = 2*y - controlY; g.bezierCurveTo( controlX + l, controlY + t, current[1] + l, current[2] + t, tempX + l, tempY + t ); x = tempX; y = tempY; // set control point to 2nd one of this command // the first control point is assumed to be the reflection of // the second control point on the previous command relative // to the current point. controlX = current[1]; controlY = current[2]; break; case 'q': // quadraticCurveTo, relative // transform to absolute x,y tempX = x + current[3]; tempY = y + current[4]; controlX = x + current[1]; controlY = y + current[2]; g.quadraticCurveTo( controlX + l, controlY + t, tempX + l, tempY + t ); x = tempX; y = tempY; break; case 'Q': // quadraticCurveTo, absolute tempX = current[3]; tempY = current[4]; g.quadraticCurveTo( current[1] + l, current[2] + t, tempX + l, tempY + t ); x = tempX; y = tempY; controlX = current[1]; controlY = current[2]; break; case 't': // shorthand quadraticCurveTo, relative // transform to absolute x,y tempX = x + current[1]; tempY = y + current[2]; if (previous[0].match(/[QqTt]/) === null) { // If there is no previous command or if the previous command was not a Q, q, T or t, // assume the control point is coincident with the current point controlX = x; controlY = y; } else if (previous[0] === 't') { // calculate reflection of previous control points for t controlX = 2 * x - tempControlX; controlY = 2 * y - tempControlY; } else if (previous[0] === 'q') { // calculate reflection of previous control points for q controlX = 2 * x - controlX; controlY = 2 * y - controlY; } tempControlX = controlX; tempControlY = controlY; g.quadraticCurveTo( controlX + l, controlY + t, tempX + l, tempY + t ); x = tempX; y = tempY; controlX = x + current[1]; controlY = y + current[2]; break; case 'T': tempX = current[1]; tempY = current[2]; // calculate reflection of previous control points controlX = 2 * x - controlX; controlY = 2 * y - controlY; g.quadraticCurveTo( controlX + l, controlY + t, tempX + l, tempY + t ); x = tempX; y = tempY; break; case 'a': drawArc(g, x + l, y + t, [ current[1], current[2], current[3], current[4], current[5], current[6] + x + l, current[7] + y + t ]); x += current[6]; y += current[7]; break; case 'A': drawArc(g, x + l, y + t, [ current[1], current[2], current[3], current[4], current[5], current[6] + l, current[7] + t ]); x = current[6]; y = current[7]; break; case 'z': case 'Z': g.closePath(); break; } previous = current; } }; function drawArc(g, x, y, coords) { var seg = arc.segments( coords[5], // end x coords[6], // end y coords[0], // radius x coords[1], // radius y coords[3], // large flag coords[4], // sweep flag coords[2], // rotation x, y ); for (var i=0; i<seg.length; ++i) { var bez = arc.bezier(seg[i]); g.bezierCurveTo.apply(g, bez); } } },{"./arc":47}],52:[function(require,module,exports){ function Handler() { this._active = null; this._handlers = {}; } var prototype = Handler.prototype; prototype.initialize = function(el, pad, obj) { this._el = el; this._obj = obj || null; return this.padding(pad); }; prototype.element = function() { return this._el; }; prototype.padding = function(pad) { this._padding = pad || {top:0, left:0, bottom:0, right:0}; return this; }; prototype.scene = function(scene) { if (!arguments.length) return this._scene; this._scene = scene; return this; }; // add an event handler // subclasses should override prototype.on = function(/*type, handler*/) {}; // remove an event handler // subclasses should override prototype.off = function(/*type, handler*/) {}; // return an array with all registered event handlers prototype.handlers = function() { var h = this._handlers, a = [], k; for (k in h) { a.push.apply(a, h[k]); } return a; }; prototype.eventName = function(name) { var i = name.indexOf('.'); return i < 0 ? name : name.slice(0,i); }; module.exports = Handler; },{}],53:[function(require,module,exports){ function Renderer() { this._el = null; this._bgcolor = null; } var prototype = Renderer.prototype; prototype.initialize = function(el, width, height, padding) { this._el = el; return this.resize(width, height, padding); }; prototype.element = function() { return this._el; }; prototype.background = function(bgcolor) { if (arguments.length === 0) return this._bgcolor; this._bgcolor = bgcolor; return this; }; prototype.resize = function(width, height, padding) { this._width = width; this._height = height; this._padding = padding || {top:0, left:0, bottom:0, right:0}; return this; }; prototype.render = function(/*scene, items*/) { return this; }; module.exports = Renderer; },{}],54:[function(require,module,exports){ var DOM = require('../../util/dom'), Handler = require('../Handler'), marks = require('./marks'); function CanvasHandler() { Handler.call(this); this._down = null; this._touch = null; this._first = true; } var base = Handler.prototype; var prototype = (CanvasHandler.prototype = Object.create(base)); prototype.constructor = CanvasHandler; prototype.initialize = function(el, pad, obj) { // add event listeners var canvas = this._canvas = DOM.find(el, 'canvas'), that = this; this.events.forEach(function(type) { canvas.addEventListener(type, function(evt) { if (prototype[type]) { prototype[type].call(that, evt); } else { that.fire(type, evt); } }); }); return base.initialize.call(this, el, pad, obj); }; prototype.canvas = function() { return this._canvas; }; // retrieve the current canvas context prototype.context = function() { return this._canvas.getContext('2d'); }; // supported events prototype.events = [ 'keydown', 'keypress', 'keyup', 'mousedown', 'mouseup', 'mousemove', 'mouseout', 'mouseover', 'click', 'dblclick', 'wheel', 'mousewheel', 'touchstart', 'touchmove', 'touchend' ]; // to keep firefox happy prototype.DOMMouseScroll = function(evt) { this.fire('mousewheel', evt); }; prototype.mousemove = function(evt) { var a = this._active, p = this.pickEvent(evt); if (p === a) { // active item and picked item are the same this.fire('mousemove', evt); // fire move } else { // active item and picked item are different this.fire('mouseout', evt); // fire out for prior active item this._active = p; // set new active item this.fire('mouseover', evt); // fire over for new active item this.fire('mousemove', evt); // fire move for new active item } }; prototype.mouseout = function(evt) { this.fire('mouseout', evt); this._active = null; }; prototype.mousedown = function(evt) { this._down = this._active; this.fire('mousedown', evt); }; prototype.click = function(evt) { if (this._down === this._active) { this.fire('click', evt); this._down = null; } }; prototype.touchstart = function(evt) { this._touch = this.pickEvent(evt.changedTouches[0]); if (this._first) { this._active = this._touch; this._first = false; } this.fire('touchstart', evt, true); }; prototype.touchmove = function(evt) { this.fire('touchmove', evt, true); }; prototype.touchend = function(evt) { this.fire('touchend', evt, true); this._touch = null; }; // fire an event prototype.fire = function(type, evt, touch) { var a = touch ? this._touch : this._active, h = this._handlers[type], i, len; if (h) { evt.vegaType = type; for (i=0, len=h.length; i<len; ++i) { h[i].handler.call(this._obj, evt, a); } } }; // add an event handler prototype.on = function(type, handler) { var name = this.eventName(type), h = this._handlers; (h[name] || (h[name] = [])).push({ type: type, handler: handler }); return this; }; // remove an event handler prototype.off = function(type, handler) { var name = this.eventName(type), h = this._handlers[name], i; if (!h) return; for (i=h.length; --i>=0;) { if (h[i].type !== type) continue; if (!handler || h[i].handler === handler) h.splice(i, 1); } return this; }; prototype.pickEvent = function(evt) { var rect = this._canvas.getBoundingClientRect(), pad = this._padding, x, y; return this.pick(this._scene, x = (evt.clientX - rect.left), y = (evt.clientY - rect.top), x - pad.left, y - pad.top); }; // find the scenegraph item at the current mouse position // x, y -- the absolute x, y mouse coordinates on the canvas element // gx, gy -- the relative coordinates within the current group prototype.pick = function(scene, x, y, gx, gy) { var g = this.context(), mark = marks[scene.marktype]; return mark.pick.call(this, g, scene, x, y, gx, gy); }; module.exports = CanvasHandler; },{"../../util/dom":81,"../Handler":52,"./marks":61}],55:[function(require,module,exports){ var DOM = require('../../util/dom'), Bounds = require('../../util/Bounds'), ImageLoader = require('../../util/ImageLoader'), Canvas = require('../../util/canvas'), Renderer = require('../Renderer'), marks = require('./marks'); function CanvasRenderer(loadConfig) { Renderer.call(this); this._loader = new ImageLoader(loadConfig); } CanvasRenderer.RETINA = true; var base = Renderer.prototype; var prototype = (CanvasRenderer.prototype = Object.create(base)); prototype.constructor = CanvasRenderer; prototype.initialize = function(el, width, height, padding) { this._canvas = Canvas.instance(width, height); if (el) { DOM.clear(el, 0).appendChild(this._canvas); this._canvas.setAttribute('class', 'marks'); } return base.initialize.call(this, el, width, height, padding); }; prototype.resize = function(width, height, padding) { base.resize.call(this, width, height, padding); Canvas.resize(this._canvas, this._width, this._height, this._padding, CanvasRenderer.RETINA); return this; }; prototype.canvas = function() { return this._canvas; }; prototype.context = function() { return this._canvas ? this._canvas.getContext('2d') : null; }; prototype.pendingImages = function() { return this._loader.pending(); }; function clipToBounds(g, items) { if (!items) return null; var b = new Bounds(), i, n, item, mark, group; for (i=0, n=items.length; i<n; ++i) { item = items[i]; mark = item.mark; group = mark.group; item = marks[mark.marktype].nested ? mark : item; b.union(translate(item.bounds, group)); if (item['bounds:prev']) { b.union(translate(item['bounds:prev'], group)); } } b.round(); g.beginPath(); g.rect(b.x1, b.y1, b.width(), b.height()); g.clip(); return b; } function translate(bounds, group) { if (group == null) return bounds; var b = bounds.clone(); for (; group != null; group = group.mark.group) { b.translate(group.x || 0, group.y || 0); } return b; } prototype.render = function(scene, items) { var g = this.context(), p = this._padding, w = this._width + p.left + p.right, h = this._height + p.top + p.bottom, b; // setup this._scene = scene; // cache scene for async redraw g.save(); b = clipToBounds(g, items); this.clear(-p.left, -p.top, w, h); // render this.draw(g, scene, b); // takedown g.restore(); this._scene = null; // clear scene cache return this; }; prototype.draw = function(ctx, scene, bounds) { var mark = marks[scene.marktype]; mark.draw.call(this, ctx, scene, bounds); }; prototype.clear = function(x, y, w, h) { var g = this.context(); g.clearRect(x, y, w, h); if (this._bgcolor != null) { g.fillStyle = this._bgcolor; g.fillRect(x, y, w, h); } }; prototype.loadImage = function(uri) { var renderer = this, scene = this._scene; return this._loader.loadImage(uri, function() { renderer.renderAsync(scene); }); }; prototype.renderAsync = function(scene) { // TODO make safe for multiple scene rendering? var renderer = this; if (renderer._async_id) { clearTimeout(renderer._async_id); } renderer._async_id = setTimeout(function() { renderer.render(scene); delete renderer._async_id; }, 10); }; module.exports = CanvasRenderer; },{"../../util/Bounds":75,"../../util/ImageLoader":77,"../../util/canvas":80,"../../util/dom":81,"../Renderer":53,"./marks":61}],56:[function(require,module,exports){ module.exports = { Handler: require('./CanvasHandler'), Renderer: require('./CanvasRenderer') }; },{"./CanvasHandler":54,"./CanvasRenderer":55}],57:[function(require,module,exports){ var util = require('./util'); var halfpi = Math.PI / 2; function path(g, o) { var x = o.x || 0, y = o.y || 0, ir = o.innerRadius || 0, or = o.outerRadius || 0, sa = (o.startAngle || 0) - halfpi, ea = (o.endAngle || 0) - halfpi; g.beginPath(); if (ir === 0) g.moveTo(x, y); else g.arc(x, y, ir, sa, ea, 0); g.arc(x, y, or, ea, sa, 1); g.closePath(); } module.exports = { draw: util.drawAll(path), pick: util.pickPath(path) }; },{"./util":68}],58:[function(require,module,exports){ var util = require('./util'), parse = require('../../../path/parse'), render = require('../../../path/render'), areaPath = require('../../../util/svg').path.area; function path(g, items) { var o = items[0], p = o.pathCache || (o.pathCache = parse(areaPath(items))); render(g, p); } function pick(g, scene, x, y, gx, gy) { var items = scene.items, b = scene.bounds; if (!items || !items.length || b && !b.contains(gx, gy)) { return null; } if (g.pixelratio != null && g.pixelratio !== 1) { x *= g.pixelratio; y *= g.pixelratio; } return hit(g, items, x, y) ? items[0] : null; } var hit = util.testPath(path); module.exports = { draw: util.drawOne(path), pick: pick, nested: true }; },{"../../../path/parse":50,"../../../path/render":51,"../../../util/svg":84,"./util":68}],59:[function(require,module,exports){ var util = require('./util'), rect = require('./rect'); function draw(g, scene, bounds) { if (!scene.items || !scene.items.length) return; var groups = scene.items, renderer = this, group, items, axes, legends, gx, gy, i, n, j, m; rect.draw.call(renderer, g, scene, bounds); for (i=0, n=groups.length; i<n; ++i) { group = groups[i]; axes = group.axisItems || []; items = group.items || []; legends = group.legendItems || []; gx = group.x || 0; gy = group.y || 0; // render group contents g.save(); g.translate(gx, gy); if (group.clip) { g.beginPath(); g.rect(0, 0, group.width || 0, group.height || 0); g.clip(); } if (bounds) bounds.translate(-gx, -gy); for (j=0, m=axes.length; j<m; ++j) { if (axes[j].layer === 'back') { renderer.draw(g, axes[j], bounds); } } for (j=0, m=items.length; j<m; ++j) { renderer.draw(g, items[j], bounds); } for (j=0, m=axes.length; j<m; ++j) { if (axes[j].layer !== 'back') { renderer.draw(g, axes[j], bounds); } } for (j=0, m=legends.length; j<m; ++j) { renderer.draw(g, legends[j], bounds); } if (bounds) bounds.translate(gx, gy); g.restore(); } } function hit(g, o) { return o.fill || o.stroke; } function pick(g, scene, x, y, gx, gy) { if (scene.bounds && !scene.bounds.contains(gx, gy)) { return null; } var items = scene.items || [], subscene, group, hits, dx, dy, i, j; for (i=items.length; --i>=0;) { group = items[i]; dx = group.x || 0; dy = group.y || 0; g.save(); g.translate(dx, dy); for (j=group.items.length; --j >= 0;) { subscene = group.items[j]; if (subscene.interactive === false) continue; hits = this.pick(subscene, x, y, gx-dx, gy-dy); if (hits) { g.restore(); return hits; } } g.restore(); } return scene.interactive !== false ? pickSelf(g, scene, x, y, gx, gy) : null; } var pickSelf = util.pick(hit); module.exports = { draw: draw, pick: pick }; },{"./rect":64,"./util":68}],60:[function(require,module,exports){ var util = require('./util'); function draw(g, scene, bounds) { if (!scene.items || !scene.items.length) return; var renderer = this, items = scene.items, o; for (var i=0, len=items.length; i<len; ++i) { o = items[i]; if (bounds && !bounds.intersects(o.bounds)) continue; // bounds check if (!(o.image && o.image.url === o.url)) { o.image = renderer.loadImage(o.url); o.image.url = o.url; } var x = o.x || 0, y = o.y || 0, w = o.width || (o.image && o.image.width) || 0, h = o.height || (o.image && o.image.height) || 0, opac; x = x - (o.align==='center' ? w/2 : o.align==='right' ? w : 0); y = y - (o.baseline==='middle' ? h/2 : o.baseline==='bottom' ? h : 0); if (o.image.loaded) { g.globalAlpha = (opac = o.opacity) != null ? opac : 1; g.drawImage(o.image, x, y, w, h); } } } module.exports = { draw: draw, pick: util.pick() }; },{"./util":68}],61:[function(require,module,exports){ module.exports = { arc: require('./arc'), area: require('./area'), group: require('./group'), image: require('./image'), line: require('./line'), path: require('./path'), rect: require('./rect'), rule: require('./rule'), symbol: require('./symbol'), text: require('./text') }; },{"./arc":57,"./area":58,"./group":59,"./image":60,"./line":62,"./path":63,"./rect":64,"./rule":65,"./symbol":66,"./text":67}],62:[function(require,module,exports){ var util = require('./util'), parse = require('../../../path/parse'), render = require('../../../path/render'), linePath = require('../../../util/svg').path.line; function path(g, items) { var o = items[0], p = o.pathCache || (o.pathCache = parse(linePath(items))); render(g, p); } function pick(g, scene, x, y, gx, gy) { var items = scene.items, b = scene.bounds; if (!items || !items.length || b && !b.contains(gx, gy)) { return null; } if (g.pixelratio != null && g.pixelratio !== 1) { x *= g.pixelratio; y *= g.pixelratio; } return hit(g, items, x, y) ? items[0] : null; } var hit = util.testPath(path, false); module.exports = { draw: util.drawOne(path), pick: pick, nested: true }; },{"../../../path/parse":50,"../../../path/render":51,"../../../util/svg":84,"./util":68}],63:[function(require,module,exports){ var util = require('./util'), parse = require('../../../path/parse'), render = require('../../../path/render'); function path(g, o) { if (o.path == null) return true; var p = o.pathCache || (o.pathCache = parse(o.path)); render(g, p, o.x, o.y); } module.exports = { draw: util.drawAll(path), pick: util.pickPath(path) }; },{"../../../path/parse":50,"../../../path/render":51,"./util":68}],64:[function(require,module,exports){ var util = require('./util'); function draw(g, scene, bounds) { if (!scene.items || !scene.items.length) return; var items = scene.items, o, opac, x, y, w, h; for (var i=0, len=items.length; i<len; ++i) { o = items[i]; if (bounds && !bounds.intersects(o.bounds)) continue; // bounds check opac = o.opacity == null ? 1 : o.opacity; if (opac === 0) continue; x = o.x || 0; y = o.y || 0; w = o.width || 0; h = o.height || 0; if (o.fill && util.fill(g, o, opac)) { g.fillRect(x, y, w, h); } if (o.stroke && util.stroke(g, o, opac)) { g.strokeRect(x, y, w, h); } } } module.exports = { draw: draw, pick: util.pick() }; },{"./util":68}],65:[function(require,module,exports){ var util = require('./util'); function draw(g, scene, bounds) { if (!scene.items || !scene.items.length) return; var items = scene.items, o, opac, x1, y1, x2, y2; for (var i=0, len=items.length; i<len; ++i) { o = items[i]; if (bounds && !bounds.intersects(o.bounds)) continue; // bounds check opac = o.opacity == null ? 1 : o.opacity; if (opac === 0) continue; x1 = o.x || 0; y1 = o.y || 0; x2 = o.x2 != null ? o.x2 : x1; y2 = o.y2 != null ? o.y2 : y1; if (o.stroke && util.stroke(g, o, opac)) { g.beginPath(); g.moveTo(x1, y1); g.lineTo(x2, y2); g.stroke(); } } } function stroke(g, o) { var x1 = o.x || 0, y1 = o.y || 0, x2 = o.x2 != null ? o.x2 : x1, y2 = o.y2 != null ? o.y2 : y1, lw = o.strokeWidth, lc = o.strokeCap; g.lineWidth = lw != null ? lw : 1; g.lineCap = lc != null ? lc : 'butt'; g.beginPath(); g.moveTo(x1, y1); g.lineTo(x2, y2); } function hit(g, o, x, y) { if (!g.isPointInStroke) return false; stroke(g, o); return g.isPointInStroke(x, y); } module.exports = { draw: draw, pick: util.pick(hit) }; },{"./util":68}],66:[function(require,module,exports){ var util = require('./util'); var sqrt3 = Math.sqrt(3), tan30 = Math.tan(30 * Math.PI / 180); function path(g, o) { var size = o.size != null ? o.size : 100, x = o.x, y = o.y, r, t, rx, ry; g.beginPath(); if (o.shape == null || o.shape === 'circle') { r = Math.sqrt(size / Math.PI); g.arc(x, y, r, 0, 2*Math.PI, 0); g.closePath(); return; } switch (o.shape) { case 'cross': r = Math.sqrt(size / 5) / 2; t = 3*r; g.moveTo(x-t, y-r); g.lineTo(x-r, y-r); g.lineTo(x-r, y-t); g.lineTo(x+r, y-t); g.lineTo(x+r, y-r); g.lineTo(x+t, y-r); g.lineTo(x+t, y+r); g.lineTo(x+r, y+r); g.lineTo(x+r, y+t); g.lineTo(x-r, y+t); g.lineTo(x-r, y+r); g.lineTo(x-t, y+r); break; case 'diamond': ry = Math.sqrt(size / (2 * tan30)); rx = ry * tan30; g.moveTo(x, y-ry); g.lineTo(x+rx, y); g.lineTo(x, y+ry); g.lineTo(x-rx, y); break; case 'square': t = Math.sqrt(size); r = t / 2; g.rect(x-r, y-r, t, t); break; case 'triangle-down': rx = Math.sqrt(size / sqrt3); ry = rx * sqrt3 / 2; g.moveTo(x, y+ry); g.lineTo(x+rx, y-ry); g.lineTo(x-rx, y-ry); break; case 'triangle-up': rx = Math.sqrt(size / sqrt3); ry = rx * sqrt3 / 2; g.moveTo(x, y-ry); g.lineTo(x+rx, y+ry); g.lineTo(x-rx, y+ry); } g.closePath(); } module.exports = { draw: util.drawAll(path), pick: util.pickPath(path) }; },{"./util":68}],67:[function(require,module,exports){ var Bounds = require('../../../util/Bounds'), textBounds = require('../../../util/bound').text, font = require('../../../util/font'), util = require('./util'), tempBounds = new Bounds(); function draw(g, scene, bounds) { if (!scene.items || !scene.items.length) return; var items = scene.items, o, opac, x, y, r, t; for (var i=0, len=items.length; i<len; ++i) { o = items[i]; if (bounds && !bounds.intersects(o.bounds)) continue; // bounds check opac = o.opacity == null ? 1 : o.opacity; if (opac === 0) continue; g.font = font.string(o); g.textAlign = o.align || 'left'; x = (o.x || 0); y = (o.y || 0); if ((r = o.radius)) { t = (o.theta || 0) - Math.PI/2; x += r * Math.cos(t); y += r * Math.sin(t); } if (o.angle) { g.save(); g.translate(x, y); g.rotate(o.angle * Math.PI/180); x = y = 0; // reset x, y } x += (o.dx || 0); y += (o.dy || 0) + font.offset(o); if (o.fill && util.fill(g, o, opac)) { g.fillText(o.text, x, y); } if (o.stroke && util.stroke(g, o, opac)) { g.strokeText(o.text, x, y); } if (o.angle) g.restore(); } } function hit(g, o, x, y, gx, gy) { if (o.fontSize <= 0) return false; if (!o.angle) return true; // bounds sufficient if no rotation // project point into space of unrotated bounds var b = textBounds(o, tempBounds, true), a = -o.angle * Math.PI / 180, cos = Math.cos(a), sin = Math.sin(a), ox = o.x, oy = o.y, px = cos*gx - sin*gy + (ox - ox*cos + oy*sin), py = sin*gx + cos*gy + (oy - ox*sin - oy*cos); return b.contains(px, py); } module.exports = { draw: draw, pick: util.pick(hit) }; },{"../../../util/Bounds":75,"../../../util/bound":79,"../../../util/font":82,"./util":68}],68:[function(require,module,exports){ function drawPathOne(path, g, o, items) { if (path(g, items)) return; var opac = o.opacity == null ? 1 : o.opacity; if (opac===0) return; if (o.fill && fill(g, o, opac)) { g.fill(); } if (o.stroke && stroke(g, o, opac)) { g.stroke(); } } function drawPathAll(path, g, scene, bounds) { var i, len, item; for (i=0, len=scene.items.length; i<len; ++i) { item = scene.items[i]; if (!bounds || bounds.intersects(item.bounds)) { drawPathOne(path, g, item, item); } } } function drawAll(pathFunc) { return function(g, scene, bounds) { drawPathAll(pathFunc, g, scene, bounds); }; } function drawOne(pathFunc) { return function(g, scene, bounds) { if (!scene.items.length) return; if (!bounds || bounds.intersects(scene.bounds)) { drawPathOne(pathFunc, g, scene.items[0], scene.items); } }; } var trueFunc = function() { return true; }; function pick(test) { if (!test) test = trueFunc; return function(g, scene, x, y, gx, gy) { if (!scene.items.length) return null; var o, b, i; if (g.pixelratio != null && g.pixelratio !== 1) { x *= g.pixelratio; y *= g.pixelratio; } for (i=scene.items.length; --i >= 0;) { o = scene.items[i]; b = o.bounds; // first hit test against bounding box if ((b && !b.contains(gx, gy)) || !b) continue; // if in bounding box, perform more careful test if (test(g, o, x, y, gx, gy)) return o; } return null; }; } function testPath(path, filled) { return function(g, o, x, y) { var item = Array.isArray(o) ? o[0] : o, fill = (filled == null) ? item.fill : filled, stroke = item.stroke && g.isPointInStroke, lw, lc; if (stroke) { lw = item.strokeWidth; lc = item.strokeCap; g.lineWidth = lw != null ? lw : 1; g.lineCap = lc != null ? lc : 'butt'; } return path(g, o) ? false : (fill && g.isPointInPath(x, y)) || (stroke && g.isPointInStroke(x, y)); }; } function pickPath(path) { return pick(testPath(path)); } function fill(g, o, opacity) { opacity *= (o.fillOpacity==null ? 1 : o.fillOpacity); if (opacity > 0) { g.globalAlpha = opacity; g.fillStyle = color(g, o, o.fill); return true; } else { return false; } } function stroke(g, o, opacity) { var lw = (lw = o.strokeWidth) != null ? lw : 1, lc; if (lw <= 0) return false; opacity *= (o.strokeOpacity==null ? 1 : o.strokeOpacity); if (opacity > 0) { g.globalAlpha = opacity; g.strokeStyle = color(g, o, o.stroke); g.lineWidth = lw; g.lineCap = (lc = o.strokeCap) != null ? lc : 'butt'; g.vgLineDash(o.strokeDash || null); g.vgLineDashOffset(o.strokeDashOffset || 0); return true; } else { return false; } } function color(g, o, value) { return (value.id) ? gradient(g, value, o.bounds) : value; } function gradient(g, p, b) { var w = b.width(), h = b.height(), x1 = b.x1 + p.x1 * w, y1 = b.y1 + p.y1 * h, x2 = b.x1 + p.x2 * w, y2 = b.y1 + p.y2 * h, grad = g.createLinearGradient(x1, y1, x2, y2), stop = p.stops, i, n; for (i=0, n=stop.length; i<n; ++i) { grad.addColorStop(stop[i].offset, stop[i].color); } return grad; } module.exports = { drawOne: drawOne, drawAll: drawAll, pick: pick, pickPath: pickPath, testPath: testPath, stroke: stroke, fill: fill, color: color, gradient: gradient }; },{}],69:[function(require,module,exports){ module.exports = { 'canvas': require('./canvas'), 'svg': require('./svg') }; },{"./canvas":56,"./svg":73}],70:[function(require,module,exports){ var DOM = require('../../util/dom'), Handler = require('../Handler'); function SVGHandler() { Handler.call(this); } var base = Handler.prototype; var prototype = (SVGHandler.prototype = Object.create(base)); prototype.constructor = SVGHandler; prototype.initialize = function(el, pad, obj) { this._svg = DOM.find(el, 'svg'); return base.initialize.call(this, el, pad, obj); }; prototype.svg = function() { return this._svg; }; // wrap an event listener for the SVG DOM prototype.listener = function(handler) { var that = this; return function(evt) { var target = evt.target, item = target.__data__; evt.vegaType = evt.type; item = Array.isArray(item) ? item[0] : item; handler.call(that._obj, evt, item); }; }; // add an event handler prototype.on = function(type, handler) { var name = this.eventName(type), svg = this._svg, h = this._handlers, x = { type: type, handler: handler, listener: this.listener(handler) }; (h[name] || (h[name] = [])).push(x); svg.addEventListener(name, x.listener); return this; }; // remove an event handler prototype.off = function(type, handler) { var name = this.eventName(type), svg = this._svg, h = this._handlers[name], i; if (!h) return; for (i=h.length; --i>=0;) { if (h[i].type === type && !handler || h[i].handler === handler) { svg.removeEventListener(name, h[i].listener); h.splice(i, 1); } } return this; }; module.exports = SVGHandler; },{"../../util/dom":81,"../Handler":52}],71:[function(require,module,exports){ var ImageLoader = require('../../util/ImageLoader'), Renderer = require('../Renderer'), font = require('../../util/font'), DOM = require('../../util/dom'), SVG = require('../../util/svg'), ns = SVG.metadata.xmlns, marks = require('./marks'); function SVGRenderer(loadConfig) { Renderer.call(this); this._loader = new ImageLoader(loadConfig); this._dirtyID = 0; } var base = Renderer.prototype; var prototype = (SVGRenderer.prototype = Object.create(base)); prototype.constructor = SVGRenderer; prototype.initialize = function(el, width, height, padding) { if (el) { this._svg = DOM.child(el, 0, 'svg', ns, 'marks'); DOM.clear(el, 1); // set the svg root group this._root = DOM.child(this._svg, 0, 'g', ns); DOM.clear(this._svg, 1); } // create the svg definitions cache this._defs = { clip_id: 1, gradient: {}, clipping: {} }; // set background color if defined this.background(this._bgcolor); return base.initialize.call(this, el, width, height, padding); }; prototype.background = function(bgcolor) { if (arguments.length && this._svg) { this._svg.style.setProperty('background-color', bgcolor); } return base.background.apply(this, arguments); }; prototype.resize = function(width, height, padding) { base.resize.call(this, width, height, padding); if (this._svg) { var w = this._width, h = this._height, p = this._padding; this._svg.setAttribute('width', w + p.left + p.right); this._svg.setAttribute('height', h + p.top + p.bottom); this._root.setAttribute('transform', 'translate('+p.left+','+p.top+')'); } return this; }; prototype.svg = function() { if (!this._svg) return null; var attr = { 'class': 'marks', 'width': this._width + this._padding.left + this._padding.right, 'height': this._height + this._padding.top + this._padding.bottom, }; for (var key in SVG.metadata) { attr[key] = SVG.metadata[key]; } return DOM.openTag('svg', attr) + this._svg.innerHTML + DOM.closeTag('svg'); }; prototype.imageURL = function(url) { return this._loader.imageURL(url); }; // -- Render entry point -- prototype.render = function(scene, items) { if (this._dirtyCheck(items)) { if (this._dirtyAll) this._resetDefs(); this.draw(this._root, scene, -1); DOM.clear(this._root, 1); } this.updateDefs(); return this; }; prototype.draw = function(el, scene, index) { this.drawMark(el, scene, index, marks[scene.marktype]); }; // -- Manage SVG definitions ('defs') block -- prototype.updateDefs = function() { var svg = this._svg, defs = this._defs, el = defs.el, index = 0, id; for (id in defs.gradient) { if (!el) el = (defs.el = DOM.child(svg, 0, 'defs', ns)); updateGradient(el, defs.gradient[id], index++); } for (id in defs.clipping) { if (!el) el = (defs.el = DOM.child(svg, 0, 'defs', ns)); updateClipping(el, defs.clipping[id], index++); } // clean-up if (el) { if (index === 0) { svg.removeChild(el); defs.el = null; } else { DOM.clear(el, index); } } }; function updateGradient(el, grad, index) { var i, n, stop; el = DOM.child(el, index, 'linearGradient', ns); el.setAttribute('id', grad.id); el.setAttribute('x1', grad.x1); el.setAttribute('x2', grad.x2); el.setAttribute('y1', grad.y1); el.setAttribute('y2', grad.y2); for (i=0, n=grad.stops.length; i<n; ++i) { stop = DOM.child(el, i, 'stop', ns); stop.setAttribute('offset', grad.stops[i].offset); stop.setAttribute('stop-color', grad.stops[i].color); } DOM.clear(el, i); } function updateClipping(el, clip, index) { var rect; el = DOM.child(el, index, 'clipPath', ns); el.setAttribute('id', clip.id); rect = DOM.child(el, 0, 'rect', ns); rect.setAttribute('x', 0); rect.setAttribute('y', 0); rect.setAttribute('width', clip.width); rect.setAttribute('height', clip.height); } prototype._resetDefs = function() { var def = this._defs; def.clip_id = 1; def.gradient = {}; def.clipping = {}; }; // -- Manage rendering of items marked as dirty -- prototype.isDirty = function(item) { return this._dirtyAll || item.dirty === this._dirtyID; }; prototype._dirtyCheck = function(items) { this._dirtyAll = true; if (!items) return true; var id = ++this._dirtyID, item, mark, type, mdef, i, n, o; for (i=0, n=items.length; i<n; ++i) { item = items[i]; mark = item.mark; if (mark.marktype !== type) { // memoize mark instance lookup type = mark.marktype; mdef = marks[type]; } if (item.status === 'exit') { // EXIT if (item._svg) { if (mdef.nest && item.mark.items.length) { // if nested mark with remaining points, update instead this._update(mdef, item._svg, item.mark.items[0]); o = item.mark.items[0]; o._svg = item._svg; o._update = id; } else { // otherwise remove from DOM DOM.remove(item._svg); } item._svg = null; } continue; } item = (mdef.nest ? mark.items[0] : item); if (item._update === id) { // Already processed continue; } else if (item._svg) { // UPDATE this._update(mdef, item._svg, item); } else { // ENTER this._dirtyAll = false; dirtyParents(item, id); } item._update = id; } return !this._dirtyAll; }; function dirtyParents(item, id) { for (; item && item.dirty !== id; item=item.mark.group) { item.dirty = id; if (item.mark && item.mark.dirty !== id) { item.mark.dirty = id; } else return; } } // -- Construct & maintain scenegraph to SVG mapping --- // Draw a mark container. prototype.drawMark = function(el, scene, index, mdef) { if (!this.isDirty(scene)) return; var items = mdef.nest ? (scene.items && scene.items.length ? [scene.items[0]] : []) : scene.items || [], events = scene.interactive === false ? 'none' : null, isGroup = (mdef.tag === 'g'), className = DOM.cssClass(scene), p, i, n, c, d, insert; p = DOM.child(el, index+1, 'g', ns, className); p.setAttribute('class', className); scene._svg = p; if (!isGroup && events) { p.style.setProperty('pointer-events', events); } for (i=0, n=items.length; i<n; ++i) { if (this.isDirty(d = items[i])) { insert = !(this._dirtyAll || d._svg); c = insert ? bind(p, mdef, d, i, true) : (p.childNodes[i] || bind(p, mdef, d, i)); this._update(mdef, c, d); if (isGroup) { if (insert) this._dirtyAll = true; this._recurse(c, d); if (insert) this._dirtyAll = false; } } } DOM.clear(p, i); return p; }; // Recursively process group contents. prototype._recurse = function(el, group) { var items = group.items || [], legends = group.legendItems || [], axes = group.axisItems || [], idx = 0, j, m; for (j=0, m=axes.length; j<m; ++j) { if (axes[j].layer === 'back') { this.drawMark(el, axes[j], idx++, marks.group); } } for (j=0, m=items.length; j<m; ++j) { this.draw(el, items[j], idx++); } for (j=0, m=axes.length; j<m; ++j) { if (axes[j].layer !== 'back') { this.drawMark(el, axes[j], idx++, marks.group); } } for (j=0, m=legends.length; j<m; ++j) { this.drawMark(el, legends[j], idx++, marks.group); } // remove any extraneous DOM elements DOM.clear(el, 1 + idx); }; // Bind a scenegraph item to an SVG DOM element. // Create new SVG elements as needed. function bind(el, mdef, item, index, insert) { // create svg element, bind item data for D3 compatibility var node = DOM.child(el, index, mdef.tag, ns, null, insert); node.__data__ = item; node.__values__ = {fill: 'default'}; // create background rect if (mdef.tag === 'g') { var bg = DOM.child(node, 0, 'rect', ns, 'background'); bg.__data__ = item; } // add pointer from scenegraph item to svg element return (item._svg = node); } // -- Set attributes & styles on SVG elements --- var href = (typeof window !== 'undefined' ? window.location.href : ''), element = null, // temp var for current SVG element values = null; // temp var for current values hash // Extra configuration for certain mark types var mark_extras = { group: function(mdef, el, item) { element = el.childNodes[0]; values = el.__values__; // use parent's values hash mdef.background(emit, item, this); var value = item.mark.interactive === false ? 'none' : null; if (value !== values.events) { element.style.setProperty('pointer-events', value); values.events = value; } }, text: function(mdef, el, item) { if (item.text !== values.text) { el.textContent = item.text || ''; values.text = item.text; } var str = font.string(item); if (str !== values.font) { el.style.setProperty('font', str); values.font = str; } } }; prototype._update = function(mdef, el, item) { // set dom element and values cache // provides access to emit method element = el; values = el.__values__; // apply svg attributes mdef.attr(emit, item, this); // some marks need special treatment var extra = mark_extras[mdef.type]; if (extra) extra(mdef, el, item); // apply svg css styles // note: element may be modified by 'extra' method this.style(element, item); }; function emit(name, value, ns) { // early exit if value is unchanged if (value === values[name]) return; if (value != null) { // if value is provided, update DOM attribute if (ns) { element.setAttributeNS(ns, name, value); } else { element.setAttribute(name, value); } } else { // else remove DOM attribute if (ns) { element.removeAttributeNS(ns, name); } else { element.removeAttribute(name); } } // note current value for future comparison values[name] = value; } prototype.style = function(el, o) { if (o == null) return; var i, n, prop, name, value; for (i=0, n=SVG.styleProperties.length; i<n; ++i) { prop = SVG.styleProperties[i]; value = o[prop]; if (value === values[prop]) continue; name = SVG.styles[prop]; if (value == null) { if (name === 'fill') { el.style.setProperty(name, 'none'); } else { el.style.removeProperty(name); } } else { if (value.id) { // ensure definition is included this._defs.gradient[value.id] = value; value = 'url(' + href + '#' + value.id + ')'; } el.style.setProperty(name, value+''); } values[prop] = value; } }; module.exports = SVGRenderer; },{"../../util/ImageLoader":77,"../../util/dom":81,"../../util/font":82,"../../util/svg":84,"../Renderer":53,"./marks":74}],72:[function(require,module,exports){ var Renderer = require('../Renderer'), ImageLoader = require('../../util/ImageLoader'), SVG = require('../../util/svg'), font = require('../../util/font'), DOM = require('../../util/dom'), openTag = DOM.openTag, closeTag = DOM.closeTag, MARKS = require('./marks'); function SVGStringRenderer(loadConfig) { Renderer.call(this); this._loader = new ImageLoader(loadConfig); this._text = { head: '', root: '', foot: '', defs: '', body: '' }; this._defs = { clip_id: 1, gradient: {}, clipping: {} }; } var base = Renderer.prototype; var prototype = (SVGStringRenderer.prototype = Object.create(base)); prototype.constructor = SVGStringRenderer; prototype.resize = function(width, height, padding) { base.resize.call(this, width, height, padding); var p = this._padding, t = this._text; var attr = { 'class': 'marks', 'width': this._width + p.left + p.right, 'height': this._height + p.top + p.bottom, }; for (var key in SVG.metadata) { attr[key] = SVG.metadata[key]; } t.head = openTag('svg', attr); t.root = openTag('g', { transform: 'translate(' + p.left + ',' + p.top + ')' }); t.foot = closeTag('g') + closeTag('svg'); return this; }; prototype.svg = function() { var t = this._text; return t.head + t.defs + t.root + t.body + t.foot; }; prototype.render = function(scene) { this._text.body = this.mark(scene); this._text.defs = this.buildDefs(); return this; }; prototype.reset = function() { this._defs.clip_id = 0; return this; }; prototype.buildDefs = function() { var all = this._defs, defs = '', i, id, def, stops; for (id in all.gradient) { def = all.gradient[id]; stops = def.stops; defs += openTag('linearGradient', { id: id, x1: def.x1, x2: def.x2, y1: def.y1, y2: def.y2 }); for (i=0; i<stops.length; ++i) { defs += openTag('stop', { offset: stops[i].offset, 'stop-color': stops[i].color }) + closeTag('stop'); } defs += closeTag('linearGradient'); } for (id in all.clipping) { def = all.clipping[id]; defs += openTag('clipPath', {id: id}); defs += openTag('rect', { x: 0, y: 0, width: def.width, height: def.height }) + closeTag('rect'); defs += closeTag('clipPath'); } return (defs.length > 0) ? openTag('defs') + defs + closeTag('defs') : ''; }; prototype.imageURL = function(url) { return this._loader.imageURL(url); }; var object; function emit(name, value, ns, prefixed) { object[prefixed || name] = value; } prototype.attributes = function(attr, item) { object = {}; attr(emit, item, this); return object; }; prototype.mark = function(scene) { var mdef = MARKS[scene.marktype], tag = mdef.tag, attr = mdef.attr, nest = mdef.nest || false, data = nest ? (scene.items && scene.items.length ? [scene.items[0]] : []) : (scene.items || []), defs = this._defs, str = '', style, i, item; if (tag !== 'g' && scene.interactive === false) { style = 'style="pointer-events: none;"'; } // render opening group tag str += openTag('g', { 'class': DOM.cssClass(scene) }, style); // render contained elements for (i=0; i<data.length; ++i) { item = data[i]; style = (tag !== 'g') ? styles(item, scene, tag, defs) : null; str += openTag(tag, this.attributes(attr, item), style); if (tag === 'text') { str += escape_text(item.text); } else if (tag === 'g') { str += openTag('rect', this.attributes(mdef.background, item), styles(item, scene, 'bgrect', defs)) + closeTag('rect'); str += this.markGroup(item); } str += closeTag(tag); } // render closing group tag return str + closeTag('g'); }; prototype.markGroup = function(scene) { var str = '', axes = scene.axisItems || [], items = scene.items || [], legends = scene.legendItems || [], j, m; for (j=0, m=axes.length; j<m; ++j) { if (axes[j].layer === 'back') { str += this.mark(axes[j]); } } for (j=0, m=items.length; j<m; ++j) { str += this.mark(items[j]); } for (j=0, m=axes.length; j<m; ++j) { if (axes[j].layer !== 'back') { str += this.mark(axes[j]); } } for (j=0, m=legends.length; j<m; ++j) { str += this.mark(legends[j]); } return str; }; function styles(o, mark, tag, defs) { if (o == null) return ''; var i, n, prop, name, value, s = ''; if (tag === 'bgrect' && mark.interactive === false) { s += 'pointer-events: none;'; } if (tag === 'text') { s += 'font: ' + font.string(o) + ';'; } for (i=0, n=SVG.styleProperties.length; i<n; ++i) { prop = SVG.styleProperties[i]; name = SVG.styles[prop]; value = o[prop]; if (value == null) { if (name === 'fill') { s += (s.length ? ' ' : '') + 'fill: none;'; } } else { if (value.id) { // ensure definition is included defs.gradient[value.id] = value; value = 'url(#' + value.id + ')'; } s += (s.length ? ' ' : '') + name + ': ' + value + ';'; } } return s ? 'style="' + s + '"' : null; } function escape_text(s) { s = (s == null ? '' : String(s)); return s.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); } module.exports = SVGStringRenderer; },{"../../util/ImageLoader":77,"../../util/dom":81,"../../util/font":82,"../../util/svg":84,"../Renderer":53,"./marks":74}],73:[function(require,module,exports){ module.exports = { Handler: require('./SVGHandler'), Renderer: require('./SVGRenderer'), string: { Renderer : require('./SVGStringRenderer') } }; },{"./SVGHandler":70,"./SVGRenderer":71,"./SVGStringRenderer":72}],74:[function(require,module,exports){ var font = require('../../util/font'), SVG = require('../../util/svg'), textAlign = SVG.textAlign, path = SVG.path; function translateItem(o) { return translate(o.x || 0, o.y || 0); } function translate(x, y) { return 'translate(' + x + ',' + y + ')'; } module.exports = { arc: { tag: 'path', type: 'arc', attr: function(emit, o) { emit('transform', translateItem(o)); emit('d', path.arc(o)); } }, area: { tag: 'path', type: 'area', nest: true, attr: function(emit, o) { var items = o.mark.items; if (items.length) emit('d', path.area(items)); } }, group: { tag: 'g', type: 'group', attr: function(emit, o, renderer) { var id = null, defs, c; emit('transform', translateItem(o)); if (o.clip) { defs = renderer._defs; id = o.clip_id || (o.clip_id = 'clip' + defs.clip_id++); c = defs.clipping[id] || (defs.clipping[id] = {id: id}); c.width = o.width || 0; c.height = o.height || 0; } emit('clip-path', id ? ('url(#' + id + ')') : null); }, background: function(emit, o) { emit('class', 'background'); emit('width', o.width || 0); emit('height', o.height || 0); } }, image: { tag: 'image', type: 'image', attr: function(emit, o, renderer) { var x = o.x || 0, y = o.y || 0, w = o.width || 0, h = o.height || 0, url = renderer.imageURL(o.url); x = x - (o.align === 'center' ? w/2 : o.align === 'right' ? w : 0); y = y - (o.baseline === 'middle' ? h/2 : o.baseline === 'bottom' ? h : 0); emit('href', url, 'http://www.w3.org/1999/xlink', 'xlink:href'); emit('transform', translate(x, y)); emit('width', w); emit('height', h); } }, line: { tag: 'path', type: 'line', nest: true, attr: function(emit, o) { var items = o.mark.items; if (items.length) emit('d', path.line(items)); } }, path: { tag: 'path', type: 'path', attr: function(emit, o) { emit('transform', translateItem(o)); emit('d', o.path); } }, rect: { tag: 'rect', type: 'rect', nest: false, attr: function(emit, o) { emit('transform', translateItem(o)); emit('width', o.width || 0); emit('height', o.height || 0); } }, rule: { tag: 'line', type: 'rule', attr: function(emit, o) { emit('transform', translateItem(o)); emit('x2', o.x2 != null ? o.x2 - (o.x||0) : 0); emit('y2', o.y2 != null ? o.y2 - (o.y||0) : 0); } }, symbol: { tag: 'path', type: 'symbol', attr: function(emit, o) { emit('transform', translateItem(o)); emit('d', path.symbol(o)); } }, text: { tag: 'text', type: 'text', nest: false, attr: function(emit, o) { var dx = (o.dx || 0), dy = (o.dy || 0) + font.offset(o), x = (o.x || 0), y = (o.y || 0), a = o.angle || 0, r = o.radius || 0, t; if (r) { t = (o.theta || 0) - Math.PI/2; x += r * Math.cos(t); y += r * Math.sin(t); } emit('text-anchor', textAlign[o.align] || 'start'); if (a) { t = translate(x, y) + ' rotate('+a+')'; if (dx || dy) t += ' ' + translate(dx, dy); } else { t = translate(x+dx, y+dy); } emit('transform', t); } } }; },{"../../util/font":82,"../../util/svg":84}],75:[function(require,module,exports){ function Bounds(b) { this.clear(); if (b) this.union(b); } var prototype = Bounds.prototype; prototype.clone = function() { return new Bounds(this); }; prototype.clear = function() { this.x1 = +Number.MAX_VALUE; this.y1 = +Number.MAX_VALUE; this.x2 = -Number.MAX_VALUE; this.y2 = -Number.MAX_VALUE; return this; }; prototype.set = function(x1, y1, x2, y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; return this; }; prototype.add = function(x, y) { if (x < this.x1) this.x1 = x; if (y < this.y1) this.y1 = y; if (x > this.x2) this.x2 = x; if (y > this.y2) this.y2 = y; return this; }; prototype.expand = function(d) { this.x1 -= d; this.y1 -= d; this.x2 += d; this.y2 += d; return this; }; prototype.round = function() { this.x1 = Math.floor(this.x1); this.y1 = Math.floor(this.y1); this.x2 = Math.ceil(this.x2); this.y2 = Math.ceil(this.y2); return this; }; prototype.translate = function(dx, dy) { this.x1 += dx; this.x2 += dx; this.y1 += dy; this.y2 += dy; return this; }; prototype.rotate = function(angle, x, y) { var cos = Math.cos(angle), sin = Math.sin(angle), cx = x - x*cos + y*sin, cy = y - x*sin - y*cos, x1 = this.x1, x2 = this.x2, y1 = this.y1, y2 = this.y2; return this.clear() .add(cos*x1 - sin*y1 + cx, sin*x1 + cos*y1 + cy) .add(cos*x1 - sin*y2 + cx, sin*x1 + cos*y2 + cy) .add(cos*x2 - sin*y1 + cx, sin*x2 + cos*y1 + cy) .add(cos*x2 - sin*y2 + cx, sin*x2 + cos*y2 + cy); }; prototype.union = function(b) { if (b.x1 < this.x1) this.x1 = b.x1; if (b.y1 < this.y1) this.y1 = b.y1; if (b.x2 > this.x2) this.x2 = b.x2; if (b.y2 > this.y2) this.y2 = b.y2; return this; }; prototype.encloses = function(b) { return b && ( this.x1 <= b.x1 && this.x2 >= b.x2 && this.y1 <= b.y1 && this.y2 >= b.y2 ); }; prototype.intersects = function(b) { return b && !( this.x2 < b.x1 || this.x1 > b.x2 || this.y2 < b.y1 || this.y1 > b.y2 ); }; prototype.contains = function(x, y) { return !( x < this.x1 || x > this.x2 || y < this.y1 || y > this.y2 ); }; prototype.width = function() { return this.x2 - this.x1; }; prototype.height = function() { return this.y2 - this.y1; }; module.exports = Bounds; },{}],76:[function(require,module,exports){ var gradient_id = 0; function Gradient(type) { this.id = 'gradient_' + (gradient_id++); this.type = type || 'linear'; this.stops = []; this.x1 = 0; this.x2 = 1; this.y1 = 0; this.y2 = 0; } var prototype = Gradient.prototype; prototype.stop = function(offset, color) { this.stops.push({ offset: offset, color: color }); return this; }; module.exports = Gradient; },{}],77:[function(require,module,exports){ (function (global){ var load = require('datalib/src/import/load'); function ImageLoader(loadConfig) { this._pending = 0; this._config = loadConfig || ImageLoader.Config; } // Overridable global default load configuration ImageLoader.Config = null; var prototype = ImageLoader.prototype; prototype.pending = function() { return this._pending; }; prototype.params = function(uri) { var p = {url: uri}, k; for (k in this._config) { p[k] = this._config[k]; } return p; }; prototype.imageURL = function(uri) { return load.sanitizeUrl(this.params(uri)); }; function browser(uri, callback) { var url = load.sanitizeUrl(this.params(uri)); if (!url) { // error if (callback) callback(uri, null); return null; } var loader = this, image = new Image(); loader._pending += 1; image.onload = function() { loader._pending -= 1; image.loaded = true; if (callback) callback(null, image); }; image.src = url; return image; } function server(uri, callback) { var loader = this, image = new ((typeof window !== "undefined" ? window['canvas'] : typeof global !== "undefined" ? global['canvas'] : null).Image)(); loader._pending += 1; load(this.params(uri), function(err, data) { loader._pending -= 1; if (err) { if (callback) callback(err, null); return null; } image.src = data; image.loaded = true; if (callback) callback(null, image); }); return image; } prototype.loadImage = function(uri, callback) { return load.useXHR ? browser.call(this, uri, callback) : server.call(this, uri, callback); }; module.exports = ImageLoader; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"datalib/src/import/load":20}],78:[function(require,module,exports){ function Item(mark) { this.mark = mark; } var prototype = Item.prototype; prototype.hasPropertySet = function(name) { var props = this.mark.def.properties; return props && props[name] != null; }; prototype.cousin = function(offset, index) { if (offset === 0) return this; offset = offset || -1; var mark = this.mark, group = mark.group, iidx = index==null ? mark.items.indexOf(this) : index, midx = group.items.indexOf(mark) + offset; return group.items[midx].items[iidx]; }; prototype.sibling = function(offset) { if (offset === 0) return this; offset = offset || -1; var mark = this.mark, iidx = mark.items.indexOf(this) + offset; return mark.items[iidx]; }; prototype.remove = function() { var item = this, list = item.mark.items, i = list.indexOf(item); if (i >= 0) { if (i===list.length-1) { list.pop(); } else { list.splice(i, 1); } } return item; }; prototype.touch = function() { if (this.pathCache) this.pathCache = null; }; module.exports = Item; },{}],79:[function(require,module,exports){ var Bounds = require('../util/Bounds'), canvas = require('../util/canvas'), svg = require('../util/svg'), font = require('./font'), paths = require('../path'), parse = paths.parse, boundPath = paths.bounds, areaPath = svg.path.area, linePath = svg.path.line, halfpi = Math.PI / 2, sqrt3 = Math.sqrt(3), tan30 = Math.tan(30 * Math.PI / 180), g2D = null; function context() { return g2D || (g2D = canvas.instance(1,1).getContext('2d')); } function strokeBounds(o, bounds) { if (o.stroke && o.opacity !== 0 && o.stokeOpacity !== 0) { bounds.expand(o.strokeWidth != null ? o.strokeWidth : 1); } return bounds; } function pathBounds(o, path, bounds) { if (path == null) { bounds.set(0, 0, 0, 0); } else { boundPath(path, bounds); strokeBounds(o, bounds); } return bounds; } function path(o, bounds) { var p = o.path ? o.pathCache || (o.pathCache = parse(o.path)) : null; return pathBounds(o, p, bounds).translate(o.x || 0, o.y || 0); } function area(mark, bounds) { if (mark.items.length === 0) return bounds; var items = mark.items, item = items[0], p = item.pathCache || (item.pathCache = parse(areaPath(items))); return pathBounds(item, p, bounds); } function line(mark, bounds) { if (mark.items.length === 0) return bounds; var items = mark.items, item = items[0], p = item.pathCache || (item.pathCache = parse(linePath(items))); return pathBounds(item, p, bounds); } function rect(o, bounds) { var x, y; return strokeBounds(o, bounds.set( x = o.x || 0, y = o.y || 0, (x + o.width) || 0, (y + o.height) || 0 )); } function image(o, bounds) { var x = o.x || 0, y = o.y || 0, w = o.width || 0, h = o.height || 0; x = x - (o.align === 'center' ? w/2 : (o.align === 'right' ? w : 0)); y = y - (o.baseline === 'middle' ? h/2 : (o.baseline === 'bottom' ? h : 0)); return bounds.set(x, y, x+w, y+h); } function rule(o, bounds) { var x1, y1; return strokeBounds(o, bounds.set( x1 = o.x || 0, y1 = o.y || 0, o.x2 != null ? o.x2 : x1, o.y2 != null ? o.y2 : y1 )); } function arc(o, bounds) { var cx = o.x || 0, cy = o.y || 0, ir = o.innerRadius || 0, or = o.outerRadius || 0, sa = (o.startAngle || 0) - halfpi, ea = (o.endAngle || 0) - halfpi, xmin = Infinity, xmax = -Infinity, ymin = Infinity, ymax = -Infinity, a, i, n, x, y, ix, iy, ox, oy; var angles = [sa, ea], s = sa - (sa % halfpi); for (i=0; i<4 && s<ea; ++i, s+=halfpi) { angles.push(s); } for (i=0, n=angles.length; i<n; ++i) { a = angles[i]; x = Math.cos(a); ix = ir*x; ox = or*x; y = Math.sin(a); iy = ir*y; oy = or*y; xmin = Math.min(xmin, ix, ox); xmax = Math.max(xmax, ix, ox); ymin = Math.min(ymin, iy, oy); ymax = Math.max(ymax, iy, oy); } return strokeBounds(o, bounds.set( cx + xmin, cy + ymin, cx + xmax, cy + ymax )); } function symbol(o, bounds) { var size = o.size != null ? o.size : 100, x = o.x || 0, y = o.y || 0, r, t, rx, ry; switch (o.shape) { case 'cross': t = 3 * Math.sqrt(size / 5) / 2; bounds.set(x-t, y-t, x+t, y+t); break; case 'diamond': ry = Math.sqrt(size / (2 * tan30)); rx = ry * tan30; bounds.set(x-rx, y-ry, x+rx, y+ry); break; case 'square': t = Math.sqrt(size); r = t / 2; bounds.set(x-r, y-r, x+r, y+r); break; case 'triangle-down': rx = Math.sqrt(size / sqrt3); ry = rx * sqrt3 / 2; bounds.set(x-rx, y-ry, x+rx, y+ry); break; case 'triangle-up': rx = Math.sqrt(size / sqrt3); ry = rx * sqrt3 / 2; bounds.set(x-rx, y-ry, x+rx, y+ry); break; default: r = Math.sqrt(size/Math.PI); bounds.set(x-r, y-r, x+r, y+r); } return strokeBounds(o, bounds); } function text(o, bounds, noRotate) { var g = context(), h = font.size(o), a = o.align, r = o.radius || 0, x = (o.x || 0), y = (o.y || 0), dx = (o.dx || 0), dy = (o.dy || 0) + font.offset(o) - Math.round(0.8*h), // use 4/5 offset w, t; if (r) { t = (o.theta || 0) - Math.PI/2; x += r * Math.cos(t); y += r * Math.sin(t); } // horizontal alignment g.font = font.string(o); w = g.measureText(o.text != null ? o.text : '').width; if (a === 'center') { dx -= (w / 2); } else if (a === 'right') { dx -= w; } else { // left by default, do nothing } bounds.set(dx+=x, dy+=y, dx+w, dy+h); if (o.angle && !noRotate) { bounds.rotate(o.angle*Math.PI/180, x, y); } return bounds.expand(noRotate ? 0 : 1); } function group(g, bounds, includeLegends) { var axes = g.axisItems || [], items = g.items || [], legends = g.legendItems || [], j, m; for (j=0, m=axes.length; j<m; ++j) { bounds.union(axes[j].bounds); } for (j=0, m=items.length; j<m; ++j) { bounds.union(items[j].bounds); } if (includeLegends) { for (j=0, m=legends.length; j<m; ++j) { bounds.union(legends[j].bounds); } } if (g.width || g.height) { strokeBounds(g, bounds .add(0, 0) .add(g.width || 0, g.height || 0)); } return bounds.translate(g.x || 0, g.y || 0); } var methods = { group: group, symbol: symbol, image: image, rect: rect, rule: rule, arc: arc, text: text, path: path, area: area, line: line }; methods.area.nest = true; methods.line.nest = true; function itemBounds(item, func, opt) { var type = item.mark.marktype; func = func || methods[type]; if (func.nest) item = item.mark; var curr = item.bounds, prev = item['bounds:prev'] || (item['bounds:prev'] = new Bounds()); if (curr) { prev.clear().union(curr); curr.clear(); } else { item.bounds = new Bounds(); } func(item, item.bounds, opt); if (!curr) prev.clear().union(item.bounds); return item.bounds; } var DUMMY_ITEM = {mark: null}; function markBounds(mark, bounds, opt) { var type = mark.marktype, func = methods[type], items = mark.items, hasi = items && items.length, i, n, o, b; if (func.nest) { o = hasi ? items[0] : (DUMMY_ITEM.mark = mark, DUMMY_ITEM); // no items, so fake it b = itemBounds(o, func, opt); bounds = bounds && bounds.union(b) || b; return bounds; } bounds = bounds || mark.bounds && mark.bounds.clear() || new Bounds(); if (hasi) { for (i=0, n=items.length; i<n; ++i) { bounds.union(itemBounds(items[i], func, opt)); } } return (mark.bounds = bounds); } module.exports = { mark: markBounds, item: itemBounds, text: text, group: group }; },{"../path":49,"../util/Bounds":75,"../util/canvas":80,"../util/svg":84,"./font":82}],80:[function(require,module,exports){ (function (global){ function instance(w, h) { w = w || 1; h = h || 1; var canvas; if (typeof document !== 'undefined' && document.createElement) { canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; } else { var Canvas = (typeof window !== "undefined" ? window['canvas'] : typeof global !== "undefined" ? global['canvas'] : null); if (!Canvas.prototype) return null; canvas = new Canvas(w, h); } return lineDash(canvas); } function resize(canvas, w, h, p, retina) { var g = this._ctx = canvas.getContext('2d'), s = 1; canvas.width = w + p.left + p.right; canvas.height = h + p.top + p.bottom; // if browser canvas, attempt to modify for retina display if (retina && typeof HTMLElement !== 'undefined' && canvas instanceof HTMLElement) { g.pixelratio = (s = pixelRatio(canvas) || 1); } g.setTransform(s, 0, 0, s, s*p.left, s*p.top); return canvas; } function pixelRatio(canvas) { var g = canvas.getContext('2d'); // get canvas pixel data var devicePixelRatio = window && window.devicePixelRatio || 1, backingStoreRatio = ( g.webkitBackingStorePixelRatio || g.mozBackingStorePixelRatio || g.msBackingStorePixelRatio || g.oBackingStorePixelRatio || g.backingStorePixelRatio) || 1, ratio = devicePixelRatio / backingStoreRatio; if (devicePixelRatio !== backingStoreRatio) { // set actual and visible canvas size var w = canvas.width, h = canvas.height; canvas.width = w * ratio; canvas.height = h * ratio; canvas.style.width = w + 'px'; canvas.style.height = h + 'px'; } return ratio; } function lineDash(canvas) { var g = canvas.getContext('2d'); if (g.vgLineDash) return; // already initialized! var NOOP = function() {}, NODASH = []; if (g.setLineDash) { g.vgLineDash = function(dash) { this.setLineDash(dash || NODASH); }; g.vgLineDashOffset = function(off) { this.lineDashOffset = off; }; } else if (g.webkitLineDash !== undefined) { g.vgLineDash = function(dash) { this.webkitLineDash = dash || NODASH; }; g.vgLineDashOffset = function(off) { this.webkitLineDashOffset = off; }; } else if (g.mozDash !== undefined) { g.vgLineDash = function(dash) { this.mozDash = dash; }; g.vgLineDashOffset = NOOP; } else { g.vgLineDash = NOOP; g.vgLineDashOffset = NOOP; } return canvas; } module.exports = { instance: instance, resize: resize, lineDash: lineDash }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],81:[function(require,module,exports){ // create a new DOM element function create(doc, tag, ns) { return ns ? doc.createElementNS(ns, tag) : doc.createElement(tag); } // remove element from DOM // recursively remove parent elements if empty function remove(el) { if (!el) return; var p = el.parentNode; if (p) { p.removeChild(el); if (!p.childNodes || !p.childNodes.length) remove(p); } } module.exports = { // find first child element with matching tag find: function(el, tag) { tag = tag.toLowerCase(); for (var i=0, n=el.childNodes.length; i<n; ++i) { if (el.childNodes[i].tagName.toLowerCase() === tag) { return el.childNodes[i]; } } }, // retrieve child element at given index // create & insert if doesn't exist or if tag/className do not match child: function(el, index, tag, ns, className, insert) { var a, b; a = b = el.childNodes[index]; if (!a || insert || a.tagName.toLowerCase() !== tag.toLowerCase() || className && a.getAttribute('class') != className) { a = create(el.ownerDocument, tag, ns); el.insertBefore(a, b); if (className) a.setAttribute('class', className); } return a; }, // remove all child elements at or above the given index clear: function(el, index) { var curr = el.childNodes.length; while (curr > index) { el.removeChild(el.childNodes[--curr]); } return el; }, remove: remove, // generate css class name for mark cssClass: function(mark) { return 'mark-' + mark.marktype + (mark.name ? ' '+mark.name : ''); }, // generate string for an opening xml tag // tag: the name of the xml tag // attr: hash of attribute name-value pairs to include // raw: additional raw string to include in tag markup openTag: function(tag, attr, raw) { var s = '<' + tag, key, val; if (attr) { for (key in attr) { val = attr[key]; if (val != null) { s += ' ' + key + '="' + val + '"'; } } } if (raw) s += ' ' + raw; return s + '>'; }, // generate string for closing xml tag // tag: the name of the xml tag closeTag: function(tag) { return '</' + tag + '>'; } }; },{}],82:[function(require,module,exports){ function size(item) { return item.fontSize != null ? item.fontSize : 11; } module.exports = { size: size, string: function(item, quote) { var font = item.font; if (quote && font) { font = String(font).replace(/\"/g, '\''); } return '' + (item.fontStyle ? item.fontStyle + ' ' : '') + (item.fontVariant ? item.fontVariant + ' ' : '') + (item.fontWeight ? item.fontWeight + ' ' : '') + size(item) + 'px ' + (font || 'sans-serif'); }, offset: function(item) { // perform our own font baseline calculation // why? not all browsers support SVG 1.1 'alignment-baseline' :( var baseline = item.baseline, h = size(item); return Math.round( baseline === 'top' ? 0.93*h : baseline === 'middle' ? 0.30*h : baseline === 'bottom' ? -0.21*h : 0 ); } }; },{}],83:[function(require,module,exports){ var bound = require('../util/bound'); var sets = [ 'items', 'axisItems', 'legendItems' ]; var keys = [ 'marktype', 'name', 'interactive', 'clip', 'items', 'axisItems', 'legendItems', 'layer', 'x', 'y', 'width', 'height', 'align', 'baseline', // layout 'fill', 'fillOpacity', 'opacity', // fill 'stroke', 'strokeOpacity', 'strokeWidth', 'strokeCap', // stroke 'strokeDash', 'strokeDashOffset', // stroke dash 'startAngle', 'endAngle', 'innerRadius', 'outerRadius', // arc 'interpolate', 'tension', 'orient', // area, line 'url', // image 'path', // path 'x2', 'y2', // rule 'size', 'shape', // symbol 'text', 'angle', 'theta', 'radius', 'dx', 'dy', // text 'font', 'fontSize', 'fontWeight', 'fontStyle', 'fontVariant' // font ]; function toJSON(scene, indent) { return JSON.stringify(scene, keys, indent); } function fromJSON(json) { var scene = (typeof json === 'string' ? JSON.parse(json) : json); return initialize(scene); } function initialize(scene) { var type = scene.marktype, i, n, s, m, items; for (s=0, m=sets.length; s<m; ++s) { if ((items = scene[sets[s]])) { for (i=0, n=items.length; i<n; ++i) { items[i][type ? 'mark' : 'group'] = scene; if (!type || type === 'group') { initialize(items[i]); } } } } if (type) bound.mark(scene); return scene; } module.exports = { toJSON: toJSON, fromJSON: fromJSON }; },{"../util/bound":79}],84:[function(require,module,exports){ (function (global){ var d3_svg = (typeof window !== "undefined" ? window['d3'] : typeof global !== "undefined" ? global['d3'] : null).svg; function x(o) { return o.x || 0; } function y(o) { return o.y || 0; } function xw(o) { return (o.x || 0) + (o.width || 0); } function yh(o) { return (o.y || 0) + (o.height || 0); } function size(o) { return o.size == null ? 100 : o.size; } function shape(o) { return o.shape || 'circle'; } var areav = d3_svg.area().x(x).y1(y).y0(yh), areah = d3_svg.area().y(y).x1(x).x0(xw), line = d3_svg.line().x(x).y(y); module.exports = { metadata: { 'version': '1.1', 'xmlns': 'http://www.w3.org/2000/svg', 'xmlns:xlink': 'http://www.w3.org/1999/xlink' }, path: { arc: d3_svg.arc(), symbol: d3_svg.symbol().type(shape).size(size), area: function(items) { var o = items[0]; return (o.orient === 'horizontal' ? areah : areav) .interpolate(o.interpolate || 'linear') .tension(o.tension || 0.7) (items); }, line: function(items) { var o = items[0]; return line .interpolate(o.interpolate || 'linear') .tension(o.tension || 0.7) (items); } }, textAlign: { 'left': 'start', 'center': 'middle', 'right': 'end' }, textBaseline: { 'top': 'before-edge', 'bottom': 'after-edge', 'middle': 'central' }, styles: { 'fill': 'fill', 'fillOpacity': 'fill-opacity', 'stroke': 'stroke', 'strokeWidth': 'stroke-width', 'strokeOpacity': 'stroke-opacity', 'strokeCap': 'stroke-linecap', 'strokeDash': 'stroke-dasharray', 'strokeDashOffset': 'stroke-dashoffset', 'opacity': 'opacity' }, styleProperties: [ 'fill', 'fillOpacity', 'stroke', 'strokeWidth', 'strokeOpacity', 'strokeCap', 'strokeDash', 'strokeDashOffset', 'opacity' ] }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],85:[function(require,module,exports){ var sg = require('vega-scenegraph').render, canvas = sg.canvas, svg = sg.svg.string, View = require('./View'); function HeadlessView(width, height, model) { View.call(null, width, height, model); this._type = 'canvas'; this._renderers = {canvas: canvas, svg: svg}; } var prototype = (HeadlessView.prototype = new View()); prototype.renderer = function(type) { if(type) this._type = type; return View.prototype.renderer.apply(this, arguments); }; prototype.canvas = function() { return (this._type === 'canvas') ? this._renderer.canvas() : null; }; prototype.canvasAsync = function(callback) { var r = this._renderer, view = this; function wait() { if (r.pendingImages() === 0) { view.render(); // re-render with all images callback(view.canvas()); } else { setTimeout(wait, 10); } } // if images loading, poll until ready if (this._type !== 'canvas') return null; if (r.pendingImages() > 0) { wait(); } else { callback(this.canvas()); } }; prototype.svg = function() { return (this._type === 'svg') ? this._renderer.svg() : null; }; prototype.initialize = function() { var w = this._width, h = this._height, bg = this._bgcolor, pad = this._padding, config = this.model().config(); if (this._viewport) { w = this._viewport[0] - (pad ? pad.left + pad.right : 0); h = this._viewport[1] - (pad ? pad.top + pad.bottom : 0); } this._renderer = (this._renderer || new this._io.Renderer(config.load)) .initialize(null, w, h, pad) .background(bg); return this; }; module.exports = HeadlessView; },{"./View":87,"vega-scenegraph":46}],86:[function(require,module,exports){ var dl = require('datalib'), df = require('vega-dataflow'), ChangeSet = df.ChangeSet, Base = df.Graph.prototype, Node = df.Node, // jshint ignore:line GroupBuilder = require('../scene/GroupBuilder'), visit = require('../scene/visit'), config = require('./config'); function Model(cfg) { this._defs = {}; this._predicates = {}; this._scene = null; this._node = null; this._builder = null; // Top-level scenegraph builder this._reset = {axes: false, legends: false}; this.config(cfg); Base.init.call(this); } var prototype = (Model.prototype = Object.create(Base)); prototype.constructor = Model; prototype.defs = function(defs) { if (!arguments.length) return this._defs; this._defs = defs; return this; }; prototype.config = function(cfg) { if (!arguments.length) return this._config; this._config = Object.create(config); for (var name in cfg) { var x = cfg[name], y = this._config[name]; if (dl.isObject(x) && dl.isObject(y)) { dl.extend(y, x); } else { this._config[name] = x; } } return this; }; prototype.width = function(width) { if (this._defs) this._defs.width = width; if (this._defs && this._defs.marks) this._defs.marks.width = width; if (this._scene) { this._scene.items[0].width = width; this._scene.items[0]._dirty = true; } this._reset.axes = true; return this; }; prototype.height = function(height) { if (this._defs) this._defs.height = height; if (this._defs && this._defs.marks) this._defs.marks.height = height; if (this._scene) { this._scene.items[0].height = height; this._scene.items[0]._dirty = true; } this._reset.axes = true; return this; }; prototype.node = function() { return this._node || (this._node = new Node(this)); }; prototype.data = function() { var data = Base.data.apply(this, arguments); if (arguments.length > 1) { // new Datasource this.node().addListener(data.pipeline()[0]); } return data; }; function predicates(name) { var m = this, pred = {}; if (!dl.isArray(name)) return this._predicates[name]; name.forEach(function(n) { pred[n] = m._predicates[n]; }); return pred; } prototype.predicate = function(name, predicate) { if (arguments.length === 1) return predicates.call(this, name); return (this._predicates[name] = predicate); }; prototype.predicates = function() { return this._predicates; }; prototype.scene = function(renderer) { if (!arguments.length) return this._scene; if (this._builder) this.node().removeListener(this._builder.disconnect()); this._builder = new GroupBuilder(this, this._defs.marks, this._scene={}); this.node().addListener(this._builder.connect()); var p = this._builder.pipeline(); p[p.length-1].addListener(renderer); return this; }; prototype.reset = function() { if (this._scene && this._reset.axes) { visit(this._scene, function(item) { if (item.axes) item.axes.forEach(function(axis) { axis.reset(); }); }); this._reset.axes = false; } if (this._scene && this._reset.legends) { visit(this._scene, function(item) { if (item.legends) item.legends.forEach(function(l) { l.reset(); }); }); this._reset.legends = false; } return this; }; prototype.addListener = function(l) { this.node().addListener(l); }; prototype.removeListener = function(l) { this.node().removeListener(l); }; prototype.fire = function(cs) { if (!cs) cs = ChangeSet.create(); this.propagate(cs, this.node()); }; module.exports = Model; },{"../scene/GroupBuilder":110,"../scene/visit":115,"./config":88,"datalib":24,"vega-dataflow":39}],87:[function(require,module,exports){ (function (global){ var d3 = (typeof window !== "undefined" ? window['d3'] : typeof global !== "undefined" ? global['d3'] : null), dl = require('datalib'), df = require('vega-dataflow'), sg = require('vega-scenegraph').render, log = require('vega-logging'), parseStreams = require('../parse/streams'), Encoder = require('../scene/Encoder'), Transition = require('../scene/Transition'); function View(el, width, height) { this._el = null; this._model = null; this._width = this.__width = width || 500; this._height = this.__height = height || 300; this._bgcolor = null; this._autopad = 1; this._padding = {top:0, left:0, bottom:0, right:0}; this._viewport = null; this._renderer = null; this._handler = null; this._streamer = null; // Targeted update for streaming changes this._changeset = null; this._repaint = true; // Full re-render on every re-init this._renderers = sg; this._io = null; this._api = {}; // Stash streaming data API sandboxes. } var prototype = View.prototype; prototype.model = function(model) { if (!arguments.length) return this._model; if (this._model !== model) { this._model = model; this._streamer = new df.Node(model); this._streamer._rank = -1; // HACK: To reduce re-ranking churn. this._changeset = df.ChangeSet.create(); if (this._handler) this._handler.model(model); } return this; }; // Sandboxed streaming data API function streaming(src) { var view = this, ds = this._model.data(src), name = ds.name(), listener = ds.pipeline()[0], streamer = this._streamer, api = {}; // If we have it stashed, don't create a new closure. if (this._api[src]) return this._api[src]; api.insert = function(vals) { ds.insert(dl.duplicate(vals)); // Don't pollute the environment streamer.addListener(listener); view._changeset.data[name] = 1; return api; }; api.update = function() { streamer.addListener(listener); view._changeset.data[name] = 1; return (ds.update.apply(ds, arguments), api); }; api.remove = function() { streamer.addListener(listener); view._changeset.data[name] = 1; return (ds.remove.apply(ds, arguments), api); }; api.values = function() { return ds.values(); }; return (this._api[src] = api); } prototype.data = function(data) { var v = this; if (!arguments.length) return v._model.dataValues(); else if (dl.isString(data)) return streaming.call(v, data); else if (dl.isObject(data)) { dl.keys(data).forEach(function(k) { var api = streaming.call(v, k); data[k](api); }); } return this; }; prototype.signal = function(name, value) { var m = this._model, cs = this._changeset, streamer = this._streamer, setter = name; if (!arguments.length) return m.signalValues(); else if (arguments.length == 1 && dl.isString(name)) return m.signalValues(name); if (arguments.length == 2) { setter = {}; setter[name] = value; } dl.keys(setter).forEach(function(k) { streamer.addListener(m.signal(k).value(setter[k])); cs.signals[k] = 1; cs.reflow = true; }); return this; }; prototype.width = function(width) { if (!arguments.length) return this.__width; if (this.__width !== width) { this._width = this.__width = width; this.model().width(width); this.initialize(); if (this._strict) this._autopad = 1; } return this; }; prototype.height = function(height) { if (!arguments.length) return this.__height; if (this.__height !== height) { this._height = this.__height = height; this.model().height(height); this.initialize(); if (this._strict) this._autopad = 1; } return this; }; prototype.background = function(bgcolor) { if (!arguments.length) return this._bgcolor; if (this._bgcolor !== bgcolor) { this._bgcolor = bgcolor; this.initialize(); } return this; }; prototype.padding = function(pad) { if (!arguments.length) return this._padding; if (this._padding !== pad) { if (dl.isString(pad)) { this._autopad = 1; this._padding = {top:0, left:0, bottom:0, right:0}; this._strict = (pad === 'strict'); } else { this._autopad = 0; this._padding = pad; this._strict = false; } if (this._renderer) this._renderer.resize(this._width, this._height, pad); if (this._handler) this._handler.padding(pad); } return (this._repaint = true, this); }; prototype.autopad = function(opt) { if (this._autopad < 1) return this; else this._autopad = 0; var b = this.model().scene().bounds, pad = this._padding, config = this.model().config(), inset = config.autopadInset, l = b.x1 < 0 ? Math.ceil(-b.x1) + inset : 0, t = b.y1 < 0 ? Math.ceil(-b.y1) + inset : 0, r = b.x2 > this._width ? Math.ceil(+b.x2 - this._width) + inset : 0; b = b.y2 > this._height ? Math.ceil(+b.y2 - this._height) + inset : 0; pad = {left:l, top:t, right:r, bottom:b}; if (this._strict) { this._autopad = 0; this._padding = pad; this._width = Math.max(0, this.__width - (l+r)); this._height = Math.max(0, this.__height - (t+b)); this._model.width(this._width) .height(this._height).reset(); this.initialize() .update({props:'enter'}).update({props:'update'}); } else { this.padding(pad).update(opt); } return this; }; prototype.viewport = function(size) { if (!arguments.length) return this._viewport; if (this._viewport !== size) { this._viewport = size; this.initialize(); } return this; }; prototype.renderer = function(type) { if (!arguments.length) return this._renderer; if (this._renderers[type]) type = this._renderers[type]; else if (dl.isString(type)) throw new Error('Unknown renderer: ' + type); else if (!type) throw new Error('No renderer specified'); if (this._io !== type) { this._io = type; this._renderer = null; this.initialize(); if (this._build) this.render(); } return this; }; prototype.initialize = function(el) { var v = this, prevHandler, w = v._width, h = v._height, pad = v._padding, bg = v._bgcolor, config = this.model().config(); if (!arguments.length || el === null) { el = this._el ? this._el.parentNode : null; if (!el) return this; // This View cannot init w/o an } // clear pre-existing container d3.select(el).select('div.vega').remove(); // add div container this._el = el = d3.select(el) .append('div') .attr('class', 'vega') .style('position', 'relative') .node(); if (v._viewport) { d3.select(el) .style('width', (v._viewport[0] || w)+'px') .style('height', (v._viewport[1] || h)+'px') .style('overflow', 'auto'); } // renderer sg.canvas.Renderer.RETINA = config.render.retina; v._renderer = (v._renderer || new this._io.Renderer(config.load)) .initialize(el, w, h, pad) .background(bg); // input handler prevHandler = v._handler; v._handler = new this._io.Handler() .initialize(el, pad, v); if (prevHandler) { prevHandler.handlers().forEach(function(h) { v._handler.on(h.type, h.handler); }); } else { // Register event listeners for signal stream definitions. v._detach = parseStreams(this); } return (this._repaint = true, this); }; prototype.destroy = function() { if (this._detach) this._detach(); }; function build() { var v = this; v._renderNode = new df.Node(v._model) .router(true); v._renderNode.evaluate = function(input) { log.debug(input, ['rendering']); var s = v._model.scene(), h = v._handler; if (h && h.scene) h.scene(s); if (input.trans) { input.trans.start(function(items) { v._renderer.render(s, items); }); } else if (v._repaint) { v._renderer.render(s); v._repaint = false; } else if (input.dirty.length) { v._renderer.render(s, input.dirty); } if (input.dirty.length) { input.dirty.forEach(function(i) { i._dirty = false; }); s.items[0]._dirty = false; } // For all updated datasources, clear their previous values. for (var d in input.data) { v._model.data(d).synchronize(); } return input; }; return (v._model.scene(v._renderNode), true); } prototype.update = function(opt) { opt = opt || {}; var v = this, trans = opt.duration ? new Transition(opt.duration, opt.ease) : null; var cs = v._changeset; if (trans) cs.trans = trans; if (opt.props !== undefined) { if (dl.keys(cs.data).length > 0) { throw Error( 'New data values are not reflected in the visualization.' + ' Please call view.update() before updating a specified property set.' ); } cs.reflow = true; cs.request = opt.props; } var built = v._build; v._build = v._build || build.call(this); // If specific items are specified, short-circuit dataflow graph. // Else-If there are streaming updates, perform a targeted propagation. // Otherwise, reevaluate the entire model (datasources + scene). if (opt.items && built) { Encoder.update(this._model, opt.trans, opt.props, opt.items, cs.dirty); v._renderNode.evaluate(cs); } else if (v._streamer.listeners().length && built) { v._model.propagate(cs, v._streamer); v._streamer.disconnect(); } else { v._model.fire(cs); } v._changeset = df.ChangeSet.create(); return v.autopad(opt); }; prototype.render = function(items) { this._renderer.render(this._model.scene(), items); return this; }; prototype.on = function() { this._handler.on.apply(this._handler, arguments); return this; }; prototype.onSignal = function(name, handler) { this._model.signal(name).on(handler); return this; }; prototype.off = function() { this._handler.off.apply(this._handler, arguments); return this; }; prototype.offSignal = function(name, handler) { this._model.signal(name).off(handler); return this; }; View.factory = function(model) { var HeadlessView = require('./HeadlessView'); return function(opt) { opt = opt || {}; var defs = model.defs(); var v = (opt.el ? new View() : new HeadlessView()) .model(model) .renderer(opt.renderer || 'canvas') .width(defs.width) .height(defs.height) .background(defs.background) .padding(defs.padding) .viewport(defs.viewport) .initialize(opt.el); if (opt.data) v.data(opt.data); if (opt.hover !== false && opt.el) { v.on('mouseover', function(evt, item) { if (item && item.hasPropertySet('hover')) { this.update({props:'hover', items:item}); } }) .on('mouseout', function(evt, item) { if (item && item.hasPropertySet('hover')) { this.update({props:'update', items:item}); } }); } return v; }; }; module.exports = View; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../parse/streams":105,"../scene/Encoder":109,"../scene/Transition":112,"./HeadlessView":85,"datalib":24,"vega-dataflow":39,"vega-logging":45,"vega-scenegraph":46}],88:[function(require,module,exports){ (function (global){ var d3 = (typeof window !== "undefined" ? window['d3'] : typeof global !== "undefined" ? global['d3'] : null), config = {}; config.load = { // base url for loading external data files // used only for server-side operation baseURL: '', // Allows domain restriction when using data loading via XHR. // To enable, set it to a list of allowed domains // e.g., ['wikipedia.org', 'eff.org'] domainWhiteList: false }; // inset padding for automatic padding calculation config.autopadInset = 5; // extensible scale lookup table // all d3.scale.* instances also supported config.scale = { time: d3.time.scale, utc: d3.time.scale.utc }; // default rendering settings config.render = { retina: true }; // default axis properties config.axis = { orient: 'bottom', ticks: 10, padding: 3, axisColor: '#000', gridColor: '#000', gridOpacity: 0.15, tickColor: '#000', tickLabelColor: '#000', axisWidth: 1, tickWidth: 1, tickSize: 6, tickLabelFontSize: 11, tickLabelFont: 'sans-serif', titleColor: '#000', titleFont: 'sans-serif', titleFontSize: 11, titleFontWeight: 'bold', titleOffset: 35 }; // default legend properties config.legend = { orient: 'right', offset: 20, padding: 3, gradientStrokeColor: '#888', gradientStrokeWidth: 1, gradientHeight: 16, gradientWidth: 100, labelColor: '#000', labelFontSize: 10, labelFont: 'sans-serif', labelAlign: 'left', labelBaseline: 'middle', labelOffset: 8, symbolShape: 'circle', symbolSize: 50, symbolColor: '#888', symbolStrokeWidth: 1, titleColor: '#000', titleFont: 'sans-serif', titleFontSize: 11, titleFontWeight: 'bold' }; // default color values config.color = { rgb: [128, 128, 128], lab: [50, 0, 0], hcl: [0, 0, 50], hsl: [0, 0, 0.5] }; // default scale ranges config.range = { category10: [ '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf' ], category20: [ '#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5' ], shapes: [ 'circle', 'cross', 'diamond', 'square', 'triangle-down', 'triangle-up' ] }; module.exports = config; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],89:[function(require,module,exports){ var dl = require('datalib'), parse = require('../parse'), Scale = require('../scene/Scale'), config = require('./config'); function compile(module, opt, schema) { var s = module.schema; if (!s) return; if (s.refs) dl.extend(schema.refs, s.refs); if (s.defs) dl.extend(schema.defs, s.defs); } module.exports = function(opt) { var schema = null; opt = opt || {}; // Compile if we're not loading the schema from a URL. // Load from a URL to extend the existing base schema. if (opt.url) { schema = dl.json(dl.extend({url: opt.url}, config.load)); } else { schema = { "$schema": "http://json-schema.org/draft-04/schema#", "title": "Vega Visualization Specification Language", "defs": {}, "refs": {}, "$ref": "#/defs/spec" }; dl.keys(parse).forEach(function(k) { compile(parse[k], opt, schema); }); // Scales aren't in the parser, add schema manually compile(Scale, opt, schema); } // Extend schema to support custom mark properties or property sets. if (opt.properties) dl.keys(opt.properties).forEach(function(k) { schema.defs.propset.properties[k] = {"$ref": "#/refs/"+opt.properties[k]+"Value"}; }); if (opt.propertySets) dl.keys(opt.propertySets).forEach(function(k) { schema.defs.mark.properties.properties.properties[k] = {"$ref": "#/defs/propset"}; }); return schema; }; },{"../parse":95,"../scene/Scale":111,"./config":88,"datalib":24}],90:[function(require,module,exports){ var dl = require('datalib'), axs = require('../scene/axis'); var ORIENT = { "x": "bottom", "y": "left", "top": "top", "bottom": "bottom", "left": "left", "right": "right" }; function parseAxes(model, spec, axes, group) { var config = model.config(); (spec || []).forEach(function(def, index) { axes[index] = axes[index] || axs(model); parseAxis(config, def, index, axes[index], group); }); } function parseAxis(config, def, index, axis, group) { // axis scale if (def.scale !== undefined) { axis.scale(group.scale(def.scale)); } // axis orientation axis.orient(def.orient || ORIENT[def.type]); // axis offset axis.offset(def.offset || 0); // axis layer axis.layer(def.layer || "front"); // axis grid lines axis.grid(def.grid || false); // axis title axis.title(def.title || null); // axis title offset axis.titleOffset(def.titleOffset != null ? def.titleOffset : config.axis.titleOffset); // axis values axis.tickValues(def.values || null); // axis label formatting axis.tickFormat(def.format || null); axis.tickFormatType(def.formatType || null); // axis tick subdivision axis.tickSubdivide(def.subdivide || 0); // axis tick padding axis.tickPadding(def.tickPadding || config.axis.padding); // axis tick size(s) var size = []; if (def.tickSize !== undefined) { for (var i=0; i<3; ++i) size.push(def.tickSize); } else { var ts = config.axis.tickSize; size = [ts, ts, ts]; } if (def.tickSizeMajor != null) size[0] = def.tickSizeMajor; if (def.tickSizeMinor != null) size[1] = def.tickSizeMinor; if (def.tickSizeEnd != null) size[2] = def.tickSizeEnd; if (size.length) { axis.tickSize.apply(axis, size); } // axis tick count axis.tickCount(def.ticks || config.axis.ticks); // style properties var p = def.properties; if (p && p.ticks) { axis.majorTickProperties(p.majorTicks ? dl.extend({}, p.ticks, p.majorTicks) : p.ticks); axis.minorTickProperties(p.minorTicks ? dl.extend({}, p.ticks, p.minorTicks) : p.ticks); } else { axis.majorTickProperties(p && p.majorTicks || {}); axis.minorTickProperties(p && p.minorTicks || {}); } axis.tickLabelProperties(p && p.labels || {}); axis.titleProperties(p && p.title || {}); axis.gridLineProperties(p && p.grid || {}); axis.domainProperties(p && p.axis || {}); } module.exports = parseAxes; },{"../scene/axis":113,"datalib":24}],91:[function(require,module,exports){ (function (global){ var d3 = (typeof window !== "undefined" ? window['d3'] : typeof global !== "undefined" ? global['d3'] : null); function parseBg(bg) { // return null if input is null or undefined if (bg == null) return null; // run through d3 rgb to sanity check return d3.rgb(bg) + ""; } module.exports = parseBg; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],92:[function(require,module,exports){ var dl = require('datalib'), log = require('vega-logging'), parseTransforms = require('./transforms'), parseModify = require('./modify'); function parseData(model, spec, callback) { var config = model.config(), count = 0; function loaded(d) { return function(error, data) { if (error) { log.error('LOADING FAILED: ' + d.url + ' ' + error); } else { model.data(d.name).values(dl.read(data, d.format)); } if (--count === 0) callback(); }; } // process each data set definition (spec || []).forEach(function(d) { if (d.url) { count += 1; dl.load(dl.extend({url: d.url}, config.load), loaded(d)); } parseData.datasource(model, d); }); if (count === 0) setTimeout(callback, 1); return spec; } parseData.datasource = function(model, d) { var transform = (d.transform || []).map(function(t) { return parseTransforms(model, t); }), mod = (d.modify || []).map(function(m) { return parseModify(model, m, d); }), ds = model.data(d.name, mod.concat(transform)); if (d.values) { ds.values(dl.read(d.values, d.format)); } else if (d.source) { // Derived ds will be pulsed by its src rather than the model. ds.source(d.source).addListener(ds); model.removeListener(ds.pipeline()[0]); } return ds; }; module.exports = parseData; },{"./modify":99,"./transforms":106,"datalib":24,"vega-logging":45}],93:[function(require,module,exports){ module.exports = (function() { /* * Generated by PEG.js 0.8.0. * * http://pegjs.majda.cz/ */ function peg$subclass(child, parent) { function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); } function SyntaxError(message, expected, found, offset, line, column) { this.message = message; this.expected = expected; this.found = found; this.offset = offset; this.line = line; this.column = column; this.name = "SyntaxError"; } peg$subclass(SyntaxError, Error); function parse(input) { var options = arguments.length > 1 ? arguments[1] : {}, peg$FAILED = {}, peg$startRuleFunctions = { start: peg$parsestart }, peg$startRuleFunction = peg$parsestart, peg$c0 = peg$FAILED, peg$c1 = ",", peg$c2 = { type: "literal", value: ",", description: "\",\"" }, peg$c3 = function(o, m) { return [o].concat(m); }, peg$c4 = function(o) { return [o]; }, peg$c5 = "[", peg$c6 = { type: "literal", value: "[", description: "\"[\"" }, peg$c7 = "]", peg$c8 = { type: "literal", value: "]", description: "\"]\"" }, peg$c9 = ">", peg$c10 = { type: "literal", value: ">", description: "\">\"" }, peg$c11 = function(f1, f2, o) { return {start: f1, end: f2, middle: o}; }, peg$c12 = [], peg$c13 = function(s, f) { return (s.filters = f, s); }, peg$c14 = function(s) { return s; }, peg$c15 = "(", peg$c16 = { type: "literal", value: "(", description: "\"(\"" }, peg$c17 = ")", peg$c18 = { type: "literal", value: ")", description: "\")\"" }, peg$c19 = function(m) { return {stream: m}; }, peg$c20 = "@", peg$c21 = { type: "literal", value: "@", description: "\"@\"" }, peg$c22 = ":", peg$c23 = { type: "literal", value: ":", description: "\":\"" }, peg$c24 = function(n, e) { return {event: e, name: n}; }, peg$c25 = function(m, e) { return {event: e, mark: m}; }, peg$c26 = function(t, e) { return {event: e, target: t}; }, peg$c27 = function(e) { return {event: e}; }, peg$c28 = function(s) { return {signal: s}; }, peg$c29 = "rect", peg$c30 = { type: "literal", value: "rect", description: "\"rect\"" }, peg$c31 = "symbol", peg$c32 = { type: "literal", value: "symbol", description: "\"symbol\"" }, peg$c33 = "path", peg$c34 = { type: "literal", value: "path", description: "\"path\"" }, peg$c35 = "arc", peg$c36 = { type: "literal", value: "arc", description: "\"arc\"" }, peg$c37 = "area", peg$c38 = { type: "literal", value: "area", description: "\"area\"" }, peg$c39 = "line", peg$c40 = { type: "literal", value: "line", description: "\"line\"" }, peg$c41 = "rule", peg$c42 = { type: "literal", value: "rule", description: "\"rule\"" }, peg$c43 = "image", peg$c44 = { type: "literal", value: "image", description: "\"image\"" }, peg$c45 = "text", peg$c46 = { type: "literal", value: "text", description: "\"text\"" }, peg$c47 = "group", peg$c48 = { type: "literal", value: "group", description: "\"group\"" }, peg$c49 = "mousedown", peg$c50 = { type: "literal", value: "mousedown", description: "\"mousedown\"" }, peg$c51 = "mouseup", peg$c52 = { type: "literal", value: "mouseup", description: "\"mouseup\"" }, peg$c53 = "click", peg$c54 = { type: "literal", value: "click", description: "\"click\"" }, peg$c55 = "dblclick", peg$c56 = { type: "literal", value: "dblclick", description: "\"dblclick\"" }, peg$c57 = "wheel", peg$c58 = { type: "literal", value: "wheel", description: "\"wheel\"" }, peg$c59 = "keydown", peg$c60 = { type: "literal", value: "keydown", description: "\"keydown\"" }, peg$c61 = "keypress", peg$c62 = { type: "literal", value: "keypress", description: "\"keypress\"" }, peg$c63 = "keyup", peg$c64 = { type: "literal", value: "keyup", description: "\"keyup\"" }, peg$c65 = "mousewheel", peg$c66 = { type: "literal", value: "mousewheel", description: "\"mousewheel\"" }, peg$c67 = "mousemove", peg$c68 = { type: "literal", value: "mousemove", description: "\"mousemove\"" }, peg$c69 = "mouseout", peg$c70 = { type: "literal", value: "mouseout", description: "\"mouseout\"" }, peg$c71 = "mouseover", peg$c72 = { type: "literal", value: "mouseover", description: "\"mouseover\"" }, peg$c73 = "mouseenter", peg$c74 = { type: "literal", value: "mouseenter", description: "\"mouseenter\"" }, peg$c75 = "touchstart", peg$c76 = { type: "literal", value: "touchstart", description: "\"touchstart\"" }, peg$c77 = "touchmove", peg$c78 = { type: "literal", value: "touchmove", description: "\"touchmove\"" }, peg$c79 = "touchend", peg$c80 = { type: "literal", value: "touchend", description: "\"touchend\"" }, peg$c81 = function(e) { return e; }, peg$c82 = /^[a-zA-Z0-9_\-]/, peg$c83 = { type: "class", value: "[a-zA-Z0-9_\\-]", description: "[a-zA-Z0-9_\\-]" }, peg$c84 = function(n) { return n.join(""); }, peg$c85 = /^[a-zA-Z0-9\-_ #.>+~[\]=|\^$*]/, peg$c86 = { type: "class", value: "[a-zA-Z0-9\\-_ #.>+~[\\]=|\\^$*]", description: "[a-zA-Z0-9\\-_ #.>+~[\\]=|\\^$*]" }, peg$c87 = function(c) { return c.join(""); }, peg$c88 = /^['"a-zA-Z0-9_().><=! \t-&|~]/, peg$c89 = { type: "class", value: "['\"a-zA-Z0-9_().><=! \\t-&|~]", description: "['\"a-zA-Z0-9_().><=! \\t-&|~]" }, peg$c90 = function(v) { return v.join(""); }, peg$c91 = /^[ \t\r\n]/, peg$c92 = { type: "class", value: "[ \\t\\r\\n]", description: "[ \\t\\r\\n]" }, peg$currPos = 0, peg$reportedPos = 0, peg$cachedPos = 0, peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }, peg$maxFailPos = 0, peg$maxFailExpected = [], peg$silentFails = 0, peg$result; if ("startRule" in options) { if (!(options.startRule in peg$startRuleFunctions)) { throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; } function text() { return input.substring(peg$reportedPos, peg$currPos); } function offset() { return peg$reportedPos; } function line() { return peg$computePosDetails(peg$reportedPos).line; } function column() { return peg$computePosDetails(peg$reportedPos).column; } function expected(description) { throw peg$buildException( null, [{ type: "other", description: description }], peg$reportedPos ); } function error(message) { throw peg$buildException(message, null, peg$reportedPos); } function peg$computePosDetails(pos) { function advance(details, startPos, endPos) { var p, ch; for (p = startPos; p < endPos; p++) { ch = input.charAt(p); if (ch === "\n") { if (!details.seenCR) { details.line++; } details.column = 1; details.seenCR = false; } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { details.line++; details.column = 1; details.seenCR = true; } else { details.column++; details.seenCR = false; } } } if (peg$cachedPos !== pos) { if (peg$cachedPos > pos) { peg$cachedPos = 0; peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }; } advance(peg$cachedPosDetails, peg$cachedPos, pos); peg$cachedPos = pos; } return peg$cachedPosDetails; } function peg$fail(expected) { if (peg$currPos < peg$maxFailPos) { return; } if (peg$currPos > peg$maxFailPos) { peg$maxFailPos = peg$currPos; peg$maxFailExpected = []; } peg$maxFailExpected.push(expected); } function peg$buildException(message, expected, pos) { function cleanupExpected(expected) { var i = 1; expected.sort(function(a, b) { if (a.description < b.description) { return -1; } else if (a.description > b.description) { return 1; } else { return 0; } }); while (i < expected.length) { if (expected[i - 1] === expected[i]) { expected.splice(i, 1); } else { i++; } } } function buildMessage(expected, found) { function stringEscape(s) { function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } return s .replace(/\\/g, '\\\\') .replace(/"/g, '\\"') .replace(/\x08/g, '\\b') .replace(/\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\f/g, '\\f') .replace(/\r/g, '\\r') .replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) .replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); }) .replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); }) .replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); }); } var expectedDescs = new Array(expected.length), expectedDesc, foundDesc, i; for (i = 0; i < expected.length; i++) { expectedDescs[i] = expected[i].description; } expectedDesc = expected.length > 1 ? expectedDescs.slice(0, -1).join(", ") + " or " + expectedDescs[expected.length - 1] : expectedDescs[0]; foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input"; return "Expected " + expectedDesc + " but " + foundDesc + " found."; } var posDetails = peg$computePosDetails(pos), found = pos < input.length ? input.charAt(pos) : null; if (expected !== null) { cleanupExpected(expected); } return new SyntaxError( message !== null ? message : buildMessage(expected, found), expected, found, pos, posDetails.line, posDetails.column ); } function peg$parsestart() { var s0; s0 = peg$parsemerged(); return s0; } function peg$parsemerged() { var s0, s1, s2, s3, s4, s5; s0 = peg$currPos; s1 = peg$parseordered(); if (s1 !== peg$FAILED) { s2 = peg$parsesep(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 44) { s3 = peg$c1; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c2); } } if (s3 !== peg$FAILED) { s4 = peg$parsesep(); if (s4 !== peg$FAILED) { s5 = peg$parsemerged(); if (s5 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c3(s1, s5); s0 = s1; } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseordered(); if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c4(s1); } s0 = s1; } return s0; } function peg$parseordered() { var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 91) { s1 = peg$c5; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c6); } } if (s1 !== peg$FAILED) { s2 = peg$parsesep(); if (s2 !== peg$FAILED) { s3 = peg$parsefiltered(); if (s3 !== peg$FAILED) { s4 = peg$parsesep(); if (s4 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 44) { s5 = peg$c1; peg$currPos++; } else { s5 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c2); } } if (s5 !== peg$FAILED) { s6 = peg$parsesep(); if (s6 !== peg$FAILED) { s7 = peg$parsefiltered(); if (s7 !== peg$FAILED) { s8 = peg$parsesep(); if (s8 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 93) { s9 = peg$c7; peg$currPos++; } else { s9 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c8); } } if (s9 !== peg$FAILED) { s10 = peg$parsesep(); if (s10 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 62) { s11 = peg$c9; peg$currPos++; } else { s11 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c10); } } if (s11 !== peg$FAILED) { s12 = peg$parsesep(); if (s12 !== peg$FAILED) { s13 = peg$parseordered(); if (s13 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c11(s3, s7, s13); s0 = s1; } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } if (s0 === peg$FAILED) { s0 = peg$parsefiltered(); } return s0; } function peg$parsefiltered() { var s0, s1, s2, s3; s0 = peg$currPos; s1 = peg$parsestream(); if (s1 !== peg$FAILED) { s2 = []; s3 = peg$parsefilter(); if (s3 !== peg$FAILED) { while (s3 !== peg$FAILED) { s2.push(s3); s3 = peg$parsefilter(); } } else { s2 = peg$c0; } if (s2 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c13(s1, s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parsestream(); if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c14(s1); } s0 = s1; } return s0; } function peg$parsestream() { var s0, s1, s2, s3, s4; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 40) { s1 = peg$c15; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c16); } } if (s1 !== peg$FAILED) { s2 = peg$parsemerged(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 41) { s3 = peg$c17; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c18); } } if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c19(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } if (s0 === peg$FAILED) { s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 64) { s1 = peg$c20; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c21); } } if (s1 !== peg$FAILED) { s2 = peg$parsename(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 58) { s3 = peg$c22; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s3 !== peg$FAILED) { s4 = peg$parseeventType(); if (s4 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c24(s2, s4); s0 = s1; } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parsemarkType(); if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 58) { s2 = peg$c22; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s2 !== peg$FAILED) { s3 = peg$parseeventType(); if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c25(s1, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parsecss(); if (s1 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 58) { s2 = peg$c22; peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c23); } } if (s2 !== peg$FAILED) { s3 = peg$parseeventType(); if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c26(s1, s3); s0 = s1; } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parseeventType(); if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c27(s1); } s0 = s1; if (s0 === peg$FAILED) { s0 = peg$currPos; s1 = peg$parsename(); if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c28(s1); } s0 = s1; } } } } } return s0; } function peg$parsemarkType() { var s0; if (input.substr(peg$currPos, 4) === peg$c29) { s0 = peg$c29; peg$currPos += 4; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c30); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 6) === peg$c31) { s0 = peg$c31; peg$currPos += 6; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c32); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 4) === peg$c33) { s0 = peg$c33; peg$currPos += 4; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c34); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 3) === peg$c35) { s0 = peg$c35; peg$currPos += 3; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c36); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 4) === peg$c37) { s0 = peg$c37; peg$currPos += 4; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c38); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 4) === peg$c39) { s0 = peg$c39; peg$currPos += 4; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c40); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 4) === peg$c41) { s0 = peg$c41; peg$currPos += 4; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c42); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 5) === peg$c43) { s0 = peg$c43; peg$currPos += 5; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c44); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 4) === peg$c45) { s0 = peg$c45; peg$currPos += 4; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c46); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 5) === peg$c47) { s0 = peg$c47; peg$currPos += 5; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c48); } } } } } } } } } } } return s0; } function peg$parseeventType() { var s0; if (input.substr(peg$currPos, 9) === peg$c49) { s0 = peg$c49; peg$currPos += 9; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c50); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 7) === peg$c51) { s0 = peg$c51; peg$currPos += 7; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c52); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 5) === peg$c53) { s0 = peg$c53; peg$currPos += 5; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c54); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 8) === peg$c55) { s0 = peg$c55; peg$currPos += 8; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c56); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 5) === peg$c57) { s0 = peg$c57; peg$currPos += 5; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c58); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 7) === peg$c59) { s0 = peg$c59; peg$currPos += 7; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c60); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 8) === peg$c61) { s0 = peg$c61; peg$currPos += 8; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c62); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 5) === peg$c63) { s0 = peg$c63; peg$currPos += 5; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c64); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 10) === peg$c65) { s0 = peg$c65; peg$currPos += 10; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c66); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 9) === peg$c67) { s0 = peg$c67; peg$currPos += 9; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c68); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 8) === peg$c69) { s0 = peg$c69; peg$currPos += 8; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c70); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 9) === peg$c71) { s0 = peg$c71; peg$currPos += 9; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c72); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 10) === peg$c73) { s0 = peg$c73; peg$currPos += 10; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c74); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 10) === peg$c75) { s0 = peg$c75; peg$currPos += 10; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c76); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 9) === peg$c77) { s0 = peg$c77; peg$currPos += 9; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c78); } } if (s0 === peg$FAILED) { if (input.substr(peg$currPos, 8) === peg$c79) { s0 = peg$c79; peg$currPos += 8; } else { s0 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c80); } } } } } } } } } } } } } } } } } return s0; } function peg$parsefilter() { var s0, s1, s2, s3; s0 = peg$currPos; if (input.charCodeAt(peg$currPos) === 91) { s1 = peg$c5; peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c6); } } if (s1 !== peg$FAILED) { s2 = peg$parseexpr(); if (s2 !== peg$FAILED) { if (input.charCodeAt(peg$currPos) === 93) { s3 = peg$c7; peg$currPos++; } else { s3 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c8); } } if (s3 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c81(s2); s0 = s1; } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } } else { peg$currPos = s0; s0 = peg$c0; } return s0; } function peg$parsename() { var s0, s1, s2; s0 = peg$currPos; s1 = []; if (peg$c82.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c83); } } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); if (peg$c82.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c83); } } } } else { s1 = peg$c0; } if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c84(s1); } s0 = s1; return s0; } function peg$parsecss() { var s0, s1, s2; s0 = peg$currPos; s1 = []; if (peg$c85.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c86); } } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); if (peg$c85.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c86); } } } } else { s1 = peg$c0; } if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c87(s1); } s0 = s1; return s0; } function peg$parseexpr() { var s0, s1, s2; s0 = peg$currPos; s1 = []; if (peg$c88.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c89); } } if (s2 !== peg$FAILED) { while (s2 !== peg$FAILED) { s1.push(s2); if (peg$c88.test(input.charAt(peg$currPos))) { s2 = input.charAt(peg$currPos); peg$currPos++; } else { s2 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c89); } } } } else { s1 = peg$c0; } if (s1 !== peg$FAILED) { peg$reportedPos = s0; s1 = peg$c90(s1); } s0 = s1; return s0; } function peg$parsesep() { var s0, s1; s0 = []; if (peg$c91.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c92); } } while (s1 !== peg$FAILED) { s0.push(s1); if (peg$c91.test(input.charAt(peg$currPos))) { s1 = input.charAt(peg$currPos); peg$currPos++; } else { s1 = peg$FAILED; if (peg$silentFails === 0) { peg$fail(peg$c92); } } } return s0; } peg$result = peg$startRuleFunction(); if (peg$result !== peg$FAILED && peg$currPos === input.length) { return peg$result; } else { if (peg$result !== peg$FAILED && peg$currPos < input.length) { peg$fail({ type: "end", description: "end of input" }); } throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos); } } return { SyntaxError: SyntaxError, parse: parse }; })(); },{}],94:[function(require,module,exports){ var expr = require('vega-expression'), args = ['datum', 'event', 'signals']; module.exports = expr.compiler(args, { idWhiteList: args, fieldVar: args[0], globalVar: args[2], functions: function(codegen) { var fn = expr.functions(codegen); fn.eventItem = function() { return 'event.vg.item'; }; fn.eventGroup = 'event.vg.getGroup'; fn.eventX = 'event.vg.getX'; fn.eventY = 'event.vg.getY'; fn.open = 'window.open'; return fn; } }); },{"vega-expression":43}],95:[function(require,module,exports){ module.exports = { axes: require('./axes'), background: require('./background'), data: require('./data'), events: require('./events'), expr: require('./expr'), legends: require('./legends'), mark: require('./mark'), marks: require('./marks'), modify: require('./modify'), padding: require('./padding'), predicates: require('./predicates'), properties: require('./properties'), signals: require('./signals'), spec: require('./spec'), streams: require('./streams'), transforms: require('./transforms') }; },{"./axes":90,"./background":91,"./data":92,"./events":93,"./expr":94,"./legends":96,"./mark":97,"./marks":98,"./modify":99,"./padding":100,"./predicates":101,"./properties":102,"./signals":103,"./spec":104,"./streams":105,"./transforms":106}],96:[function(require,module,exports){ var lgnd = require('../scene/legend'); function parseLegends(model, spec, legends, group) { (spec || []).forEach(function(def, index) { legends[index] = legends[index] || lgnd(model); parseLegend(def, index, legends[index], group); }); } function parseLegend(def, index, legend, group) { // legend scales legend.size (def.size ? group.scale(def.size) : null); legend.shape (def.shape ? group.scale(def.shape) : null); legend.fill (def.fill ? group.scale(def.fill) : null); legend.stroke(def.stroke ? group.scale(def.stroke) : null); // legend orientation if (def.orient) legend.orient(def.orient); // legend offset if (def.offset != null) legend.offset(def.offset); // legend title legend.title(def.title || null); // legend values legend.values(def.values || null); // legend label formatting legend.format(def.format !== undefined ? def.format : null); // style properties var p = def.properties; legend.titleProperties(p && p.title || {}); legend.labelProperties(p && p.labels || {}); legend.legendProperties(p && p.legend || {}); legend.symbolProperties(p && p.symbols || {}); legend.gradientProperties(p && p.gradient || {}); } module.exports = parseLegends; },{"../scene/legend":114}],97:[function(require,module,exports){ var dl = require('datalib'), parseProperties = require('./properties'); function parseMark(model, mark) { var props = mark.properties, group = mark.marks; // parse mark property definitions dl.keys(props).forEach(function(k) { props[k] = parseProperties(model, mark.type, props[k]); }); // parse delay function if (mark.delay) { mark.delay = parseProperties(model, mark.type, {delay: mark.delay}); } // recurse if group type if (group) { mark.marks = group.map(function(g) { return parseMark(model, g); }); } return mark; } module.exports = parseMark; },{"./properties":102,"datalib":24}],98:[function(require,module,exports){ var parseMark = require('./mark'); function parseRootMark(model, spec, width, height) { return { type: "group", width: width, height: height, scales: spec.scales || [], axes: spec.axes || [], legends: spec.legends || [], marks: (spec.marks || []).map(function(m) { return parseMark(model, m); }) }; } module.exports = parseRootMark; },{"./mark":97}],99:[function(require,module,exports){ var dl = require('datalib'), log = require('vega-logging'), df = require('vega-dataflow'), Node = df.Node, // jshint ignore:line Tuple = df.Tuple, Deps = df.Dependencies; var Types = { INSERT: "insert", REMOVE: "remove", TOGGLE: "toggle", CLEAR: "clear" }; var filter = function(field, value, src, dest) { for(var i = src.length-1; i >= 0; --i) { if (src[i][field] == value) dest.push.apply(dest, src.splice(i, 1)); } }; function parseModify(model, def, ds) { var signal = def.signal ? dl.field(def.signal) : null, signalName = signal ? signal[0] : null, predicate = def.predicate ? model.predicate(def.predicate.name || def.predicate) : null, reeval = (predicate === null), node = new Node(model).router(def.type === Types.CLEAR); node.evaluate = function(input) { if (predicate !== null) { // TODO: predicate args var db = model.dataValues(predicate.data||[]); reeval = predicate.call(predicate, {}, db, model.signalValues(predicate.signals||[]), model._predicates); } log.debug(input, [def.type+"ing", reeval]); if (!reeval) return input; var datum = {}, value = signal ? model.signalRef(def.signal) : null, d = model.data(ds.name), t = null; datum[def.field] = value; // We have to modify ds._data so that subsequent pulses contain // our dynamic data. W/o modifying ds._data, only the output // collector will contain dynamic tuples. if (def.type === Types.INSERT) { t = Tuple.ingest(datum); input.add.push(t); d._data.push(t); } else if (def.type === Types.REMOVE) { filter(def.field, value, input.add, input.rem); filter(def.field, value, input.mod, input.rem); d._data = d._data.filter(function(x) { return x[def.field] !== value; }); } else if (def.type === Types.TOGGLE) { var add = [], rem = []; filter(def.field, value, input.rem, add); filter(def.field, value, input.add, rem); filter(def.field, value, input.mod, rem); if (!(add.length || rem.length)) add.push(Tuple.ingest(datum)); input.add.push.apply(input.add, add); d._data.push.apply(d._data, add); input.rem.push.apply(input.rem, rem); d._data = d._data.filter(function(x) { return rem.indexOf(x) === -1; }); } else if (def.type === Types.CLEAR) { input.rem.push.apply(input.rem, input.add); input.rem.push.apply(input.rem, input.mod); input.add = []; input.mod = []; d._data = []; } input.fields[def.field] = 1; return input; }; if (signalName) node.dependency(Deps.SIGNALS, signalName); if (predicate) node.dependency(Deps.SIGNALS, predicate.signals); return node; } module.exports = parseModify; },{"datalib":24,"vega-dataflow":39,"vega-logging":45}],100:[function(require,module,exports){ var dl = require('datalib'); function parsePadding(pad) { if (pad == null) return "auto"; else if (dl.isString(pad)) return pad==="strict" ? "strict" : "auto"; else if (dl.isObject(pad)) return pad; var p = dl.isNumber(pad) ? pad : 20; return {top:p, left:p, right:p, bottom:p}; } module.exports = parsePadding; },{"datalib":24}],101:[function(require,module,exports){ var dl = require('datalib'); var types = { '=': parseComparator, '==': parseComparator, '!=': parseComparator, '>': parseComparator, '>=': parseComparator, '<': parseComparator, '<=': parseComparator, 'and': parseLogical, '&&': parseLogical, 'or': parseLogical, '||': parseLogical, 'in': parseIn }; var nullScale = function() { return 0; }; nullScale.invert = nullScale; function parsePredicates(model, spec) { (spec || []).forEach(function(s) { var parse = types[s.type](model, s); /* jshint evil:true */ var pred = Function("args", "db", "signals", "predicates", parse.code); pred.root = function() { return model.scene().items[0]; }; // For global scales pred.nullScale = nullScale; pred.isFunction = dl.isFunction; pred.signals = parse.signals; pred.data = parse.data; model.predicate(s.name, pred); }); return spec; } function parseSignal(signal, signals) { var s = dl.field(signal), code = "signals["+s.map(dl.str).join("][")+"]"; signals[s[0]] = 1; return code; } function parseOperands(model, operands) { var decl = [], defs = [], signals = {}, db = {}; function setSignal(s) { signals[s] = 1; } function setData(d) { db[d] = 1; } dl.array(operands).forEach(function(o, i) { var name = "o" + i, def = ""; if (o.value !== undefined) { def = dl.str(o.value); } else if (o.arg) { def = "args["+dl.str(o.arg)+"]"; } else if (o.signal) { def = parseSignal(o.signal, signals); } else if (o.predicate) { var ref = o.predicate, predName = ref && (ref.name || ref), pred = model.predicate(predName), p = "predicates["+dl.str(predName)+"]"; pred.signals.forEach(setSignal); pred.data.forEach(setData); if (dl.isObject(ref)) { dl.keys(ref).forEach(function(k) { if (k === "name") return; var i = ref[k]; def += "args["+dl.str(k)+"] = "; if (i.signal) { def += parseSignal(i.signal, signals); } else if (i.arg) { def += "args["+dl.str(i.arg)+"]"; } def += ", "; }); } def += p+".call("+p+", args, db, signals, predicates)"; } decl.push(name); defs.push(name+"=("+def+")"); }); return { code: "var " + decl.join(", ") + ";\n" + defs.join(";\n") + ";\n", signals: dl.keys(signals), data: dl.keys(db) }; } function parseComparator(model, spec) { var ops = parseOperands(model, spec.operands); if (spec.type === '=') spec.type = '=='; ops.code += "o0 = o0 instanceof Date ? o0.getTime() : o0;\n" + "o1 = o1 instanceof Date ? o1.getTime() : o1;\n"; return { code: ops.code + "return " + ["o0", "o1"].join(spec.type) + ";", signals: ops.signals, data: ops.data }; } function parseLogical(model, spec) { var ops = parseOperands(model, spec.operands), o = [], i = 0, len = spec.operands.length; while (o.push("o"+i++) < len); if (spec.type === 'and') spec.type = '&&'; else if (spec.type === 'or') spec.type = '||'; return { code: ops.code + "return " + o.join(spec.type) + ";", signals: ops.signals, data: ops.data }; } function parseIn(model, spec) { var o = [spec.item], code = ""; if (spec.range) o.push.apply(o, spec.range); if (spec.scale) { code = parseScale(spec.scale, o); } var ops = parseOperands(model, o); code = ops.code + code + "\n var ordSet = null;\n"; if (spec.data) { var field = dl.field(spec.field).map(dl.str); code += "var where = function(d) { return d["+field.join("][")+"] == o0 };\n"; code += "return db["+dl.str(spec.data)+"].filter(where).length > 0;"; } else if (spec.range) { // TODO: inclusive/exclusive range? if (spec.scale) { code += "if (scale.length == 2) {\n" + // inverting ordinal scales " ordSet = scale(o1, o2);\n" + "} else {\n" + " o1 = scale(o1);\no2 = scale(o2);\n" + "}"; } code += "return ordSet !== null ? ordSet.indexOf(o0) !== -1 :\n" + " o1 < o2 ? o1 <= o0 && o0 <= o2 : o2 <= o0 && o0 <= o1;"; } return { code: code, signals: ops.signals, data: ops.data.concat(spec.data ? [spec.data] : []) }; } // Populate ops such that ultimate scale/inversion function will be in `scale` var. function parseScale(spec, ops) { var code = "var scale = ", idx = ops.length; if (dl.isString(spec)) { ops.push({ value: spec }); code += "this.root().scale(o"+idx+")"; } else if (spec.arg) { // Scale function is being passed as an arg ops.push(spec); code += "o"+idx; } else if (spec.name) { // Full scale parameter {name: ..} ops.push(dl.isString(spec.name) ? {value: spec.name} : spec.name); code += "(this.isFunction(o"+idx+") ? o"+idx+" : "; if (spec.scope) { ops.push(spec.scope); code += "((o"+(idx+1)+".scale || this.root().scale)(o"+idx+") || this.nullScale)"; } else { code += "this.root().scale(o"+idx+")"; } code += ")"; } if (spec.invert === true) { // Allow spec.invert.arg? code += ".invert"; } return code+";\n"; } module.exports = parsePredicates; },{"datalib":24}],102:[function(require,module,exports){ (function (global){ var d3 = (typeof window !== "undefined" ? window['d3'] : typeof global !== "undefined" ? global['d3'] : null), dl = require('datalib'), log = require('vega-logging'), Tuple = require('vega-dataflow').Tuple; var DEPS = ["signals", "scales", "data", "fields"]; function properties(model, mark, spec) { var config = model.config(), code = "", names = dl.keys(spec), i, len, name, ref, vars = {}, deps = { signals: {}, scales: {}, data: {}, fields: {}, nested: [], _nRefs: {}, // Temp stash to de-dupe nested refs. reflow: false }; code += "var o = trans ? {} : item, d=0, set=this.tpl.set, t;\n" + // Stash for dl.template "signals.datum = item.datum;\n" + "signals.group = group;\n" + "signals.parent = group.datum;\n"; function handleDep(p) { if (ref[p] == null) return; var k = dl.array(ref[p]), i, n; for (i=0, n=k.length; i<n; ++i) { deps[p][k[i]] = 1; } } function handleNestedRefs(r) { var k = (r.parent ? "parent_" : "group_")+r.level; deps._nRefs[k] = r; } for (i=0, len=names.length; i<len; ++i) { ref = spec[name = names[i]]; code += (i > 0) ? "\n " : " "; if (ref.rule) { ref = rule(model, name, ref.rule); code += "\n " + ref.code; } else { ref = valueRef(config, name, ref); code += "d += set(o, "+dl.str(name)+", "+ref.val+");"; } vars[name] = true; DEPS.forEach(handleDep); deps.reflow = deps.reflow || ref.reflow; if (ref.nested.length) ref.nested.forEach(handleNestedRefs); } // If nested references are present, sort them based on their level // to speed up determination of whether encoders should be reeval'd. dl.keys(deps._nRefs).forEach(function(k) { deps.nested.push(deps._nRefs[k]); }); deps.nested.sort(function(a, b) { a = a.level; b = b.level; return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; }); if (vars.x2) { if (vars.x) { code += "\n if (o.x > o.x2) { " + "\n t = o.x;" + "\n d += set(o, 'x', o.x2);" + "\n d += set(o, 'x2', t); " + "\n };"; code += "\n d += set(o, 'width', (o.x2 - o.x));"; } else if (vars.width) { code += "\n d += set(o, 'x', (o.x2 - o.width));"; } else { code += "\n d += set(o, 'x', o.x2);"; } } if (vars.xc) { if (vars.width) { code += "\n d += set(o, 'x', (o.xc - o.width/2));" ; } else { code += "\n d += set(o, 'x', o.xc);" ; } } if (vars.y2) { if (vars.y) { code += "\n if (o.y > o.y2) { " + "\n t = o.y;" + "\n d += set(o, 'y', o.y2);" + "\n d += set(o, 'y2', t);" + "\n };"; code += "\n d += set(o, 'height', (o.y2 - o.y));"; } else if (vars.height) { code += "\n d += set(o, 'y', (o.y2 - o.height));"; } else { code += "\n d += set(o, 'y', o.y2);"; } } if (vars.yc) { if (vars.height) { code += "\n d += set(o, 'y', (o.yc - o.height/2));" ; } else { code += "\n d += set(o, 'y', o.yc);" ; } } if (hasPath(mark, vars)) code += "\n d += (item.touch(), 1);"; code += "\n if (trans) trans.interpolate(item, o);"; code += "\n return d > 0;"; try { /* jshint evil:true */ var encoder = Function('item', 'group', 'trans', 'db', 'signals', 'predicates', code); encoder.tpl = Tuple; encoder.util = dl; encoder.d3 = d3; // For color spaces dl.extend(encoder, dl.template.context); return { encode: encoder, signals: dl.keys(deps.signals), scales: dl.keys(deps.scales), data: dl.keys(deps.data), fields: dl.keys(deps.fields), nested: deps.nested, reflow: deps.reflow }; } catch (e) { log.error(e); log.log(code); } } function dependencies(a, b) { if (!dl.isObject(a)) { a = {reflow: false, nested: []}; DEPS.forEach(function(d) { a[d] = []; }); } if (dl.isObject(b)) { a.reflow = a.reflow || b.reflow; a.nested.push.apply(a.nested, b.nested); DEPS.forEach(function(d) { a[d].push.apply(a[d], b[d]); }); } return a; } function hasPath(mark, vars) { return vars.path || ((mark==='area' || mark==='line') && (vars.x || vars.x2 || vars.width || vars.y || vars.y2 || vars.height || vars.tension || vars.interpolate)); } function rule(model, name, rules) { var config = model.config(), deps = dependencies(), inputs = [], code = ''; (rules||[]).forEach(function(r, i) { var def = r.predicate, predName = def && (def.name || def), pred = model.predicate(predName), p = 'predicates['+dl.str(predName)+']', input = [], args = name+'_arg'+i, ref; if (dl.isObject(def)) { dl.keys(def).forEach(function(k) { if (k === 'name') return; var ref = valueRef(config, i, def[k]); input.push(dl.str(k)+': '+ref.val); dependencies(deps, ref); }); } ref = valueRef(config, name, r); dependencies(deps, ref); if (predName) { deps.signals.push.apply(deps.signals, pred.signals); deps.data.push.apply(deps.data, pred.data); inputs.push(args+" = {\n "+input.join(",\n ")+"\n }"); code += "if ("+p+".call("+p+","+args+", db, signals, predicates)) {" + "\n d += set(o, "+dl.str(name)+", "+ref.val+");"; code += rules[i+1] ? "\n } else " : " }"; } else { code += "{" + "\n d += set(o, "+dl.str(name)+", "+ref.val+");"+ "\n }\n"; } }); code = "var " + inputs.join(",\n ") + ";\n " + code; return (deps.code = code, deps); } function valueRef(config, name, ref) { if (ref == null) return null; if (name==='fill' || name==='stroke') { if (ref.c) { return colorRef(config, 'hcl', ref.h, ref.c, ref.l); } else if (ref.h || ref.s) { return colorRef(config, 'hsl', ref.h, ref.s, ref.l); } else if (ref.l || ref.a) { return colorRef(config, 'lab', ref.l, ref.a, ref.b); } else if (ref.r || ref.g || ref.b) { return colorRef(config, 'rgb', ref.r, ref.g, ref.b); } } // initialize value var val = null, scale = null, deps = dependencies(), sgRef = null, fRef = null, sRef = null, tmpl = {}; if (ref.template !== undefined) { val = dl.template.source(ref.template, 'signals', tmpl); dl.keys(tmpl).forEach(function(k) { var f = dl.field(k), a = f.shift(); if (a === 'parent' || a === 'group') { deps.nested.push({ parent: a === 'parent', group: a === 'group', level: 1 }); } else if (a === 'datum') { deps.fields.push(f[0]); } else { deps.signals.push(a); } }); } if (ref.value !== undefined) { val = dl.str(ref.value); } if (ref.signal !== undefined) { sgRef = dl.field(ref.signal); val = 'signals['+sgRef.map(dl.str).join('][')+']'; deps.signals.push(sgRef.shift()); } if (ref.field !== undefined) { ref.field = dl.isString(ref.field) ? {datum: ref.field} : ref.field; fRef = fieldRef(ref.field); val = fRef.val; dependencies(deps, fRef); } if (ref.scale !== undefined) { sRef = scaleRef(ref.scale); scale = sRef.val; dependencies(deps, sRef); deps.scales.push(ref.scale.name || ref.scale); // run through scale function if val specified. // if no val, scale function is predicate arg. if (val !== null || ref.band || ref.mult || ref.offset) { val = scale + (ref.band ? '.rangeBand()' : '('+(val !== null ? val : 'item.datum.data')+')'); } else { val = scale; } } // multiply, offset, return value val = '(' + (ref.mult?(dl.number(ref.mult)+' * '):'') + val + ')' + (ref.offset ? ' + ' + dl.number(ref.offset) : ''); // Collate dependencies return (deps.val = val, deps); } function colorRef(config, type, x, y, z) { var xx = x ? valueRef(config, '', x) : config.color[type][0], yy = y ? valueRef(config, '', y) : config.color[type][1], zz = z ? valueRef(config, '', z) : config.color[type][2], deps = dependencies(); [xx, yy, zz].forEach(function(v) { if (dl.isArray) return; dependencies(deps, v); }); var val = '(this.d3.' + type + '(' + [xx.val, yy.val, zz.val].join(',') + ') + "")'; return (deps.val = val, deps); } // {field: {datum: "foo"} } -> item.datum.foo // {field: {group: "foo"} } -> group.foo // {field: {parent: "foo"} } -> group.datum.foo function fieldRef(ref) { if (dl.isString(ref)) { return {val: dl.field(ref).map(dl.str).join('][')}; } // Resolve nesting/parent lookups var l = ref.level || 1, nested = (ref.group || ref.parent) && l, scope = nested ? Array(l).join('group.mark.') : '', r = fieldRef(ref.datum || ref.group || ref.parent || ref.signal), val = r.val, deps = dependencies(null, r); if (ref.datum) { val = 'item.datum['+val+']'; deps.fields.push(ref.datum); } else if (ref.group) { val = scope+'group['+val+']'; deps.nested.push({ level: l, group: true }); } else if (ref.parent) { val = scope+'group.datum['+val+']'; deps.nested.push({ level: l, parent: true }); } else if (ref.signal) { val = 'signals['+val+']'; deps.signals.push(dl.field(ref.signal)[0]); deps.reflow = true; } return (deps.val = val, deps); } // {scale: "x"} // {scale: {name: "x"}}, // {scale: fieldRef} function scaleRef(ref) { var scale = null, fr = null, deps = dependencies(); if (dl.isString(ref)) { scale = dl.str(ref); } else if (ref.name) { scale = dl.isString(ref.name) ? dl.str(ref.name) : (fr = fieldRef(ref.name)).val; } else { scale = (fr = fieldRef(ref)).val; } scale = '(item.mark._scaleRefs['+scale+'] = 1, group.scale('+scale+'))'; if (ref.invert) scale += '.invert'; // Mark scale refs as they're dealt with separately in mark._scaleRefs. if (fr) fr.nested.forEach(function(g) { g.scale = true; }); return fr ? (fr.val = scale, fr) : (deps.val = scale, deps); } module.exports = properties; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"datalib":24,"vega-dataflow":39,"vega-logging":45}],103:[function(require,module,exports){ var dl = require('datalib'), Deps = require('vega-dataflow').Dependencies, expr = require('./expr'); var RESERVED = ['datum', 'event', 'signals'] .concat(dl.keys(expr.codegen.functions)); function parseSignals(model, spec) { // process each signal definition (spec || []).forEach(function(s) { if (RESERVED.indexOf(s.name) !== -1) { throw Error('Signal name "'+s.name+'" is a '+ 'reserved keyword ('+RESERVED.join(', ')+').'); } var signal = model.signal(s.name, s.init) .verbose(s.verbose); if (s.init && s.init.expr) { s.init.expr = expr(s.init.expr); signal.value(exprVal(model, s.init)); } if (s.expr) { s.expr = expr(s.expr); signal.evaluate = function(input) { var val = exprVal(model, s); if (val !== signal.value() || signal.verbose()) { signal.value(val); input.signals[s.name] = 1; return input; } return model.doNotPropagate; }; signal.dependency(Deps.SIGNALS, s.expr.globals); s.expr.globals.forEach(function(dep) { model.signal(dep).addListener(signal); }); } }); return spec; } function exprVal(model, spec) { var e = spec.expr, val = e.fn(null, null, model.signalValues(e.globals)); return spec.scale ? parseSignals.scale(model, spec, val) : val; } parseSignals.scale = function scale(model, spec, value, datum, evt) { var def = spec.scale, name = def.name || def.signal || def, scope = def.scope, e; if (scope) { if (scope.signal) { scope = model.signalRef(scope.signal); } else if (dl.isString(scope)) { // Scope is an expression e = def._expr = (def._expr || expr(scope)); scope = e.fn(datum, evt, model.signalValues(e.globals)); } } if (!scope || !scope.scale) { scope = (scope && scope.mark) ? scope.mark.group : model.scene().items[0]; } var s = scope.scale(name); return !s ? value : (def.invert ? s.invert(value) : s(value)); }; module.exports = parseSignals; },{"./expr":94,"datalib":24,"vega-dataflow":39}],104:[function(require,module,exports){ var dl = require('datalib'), log = require('vega-logging'), Model = require('../core/Model'), View = require('../core/View'); function parseSpec(spec, callback) { var vf = arguments[arguments.length-1], viewFactory = arguments.length > 2 && dl.isFunction(vf) ? vf : View.factory, config = arguments[2] !== viewFactory ? arguments[2] : {}, model = new Model(config); function parse(spec) { // protect against subsequent spec modification spec = dl.duplicate(spec); var parsers = require('./'), width = spec.width || 500, height = spec.height || 500, viewport = spec.viewport || null; model.defs({ width: width, height: height, viewport: viewport, background: parsers.background(spec.background), padding: parsers.padding(spec.padding), signals: parsers.signals(model, spec.signals), predicates: parsers.predicates(model, spec.predicates), marks: parsers.marks(model, spec, width, height), data: parsers.data(model, spec.data, function() { callback(viewFactory(model)); }) }); } if (dl.isObject(spec)) { parse(spec); } else if (dl.isString(spec)) { var opts = dl.extend({url: spec}, model.config().load); dl.load(opts, function(err, data) { if (err) { log.error('LOADING SPECIFICATION FAILED: ' + err.statusText); } else { try { parse(JSON.parse(data)); } catch (e) { log.error('INVALID SPECIFICATION: Must be a valid JSON object. '+e); } } }); } else { log.error('INVALID SPECIFICATION: Must be a valid JSON object or URL.'); } } module.exports = parseSpec; },{"../core/Model":86,"../core/View":87,"./":95,"datalib":24,"vega-logging":45}],105:[function(require,module,exports){ (function (global){ var d3 = (typeof window !== "undefined" ? window['d3'] : typeof global !== "undefined" ? global['d3'] : null), dl = require('datalib'), df = require('vega-dataflow'), parseSignals = require('./signals'), selector = require('./events'), expr = require('./expr'); var GATEKEEPER = '_vgGATEKEEPER'; var vgEvent = { getGroup: function(name) { return name ? this.name[name] : this.group; }, getXY: function(item) { var p = {x: this.x, y: this.y}; if (typeof item === 'string') { item = this.name[item]; } for (; item; item = item.mark && item.mark.group) { p.x -= item.x || 0; p.y -= item.y || 0; } return p; }, getX: function(item) { return this.getXY(item).x; }, getY: function(item) { return this.getXY(item).y; } }; function parseStreams(view) { var model = view.model(), spec = model.defs().signals, registry = {handlers: {}, nodes: {}}, internal = dl.duplicate(registry), // Internal event processing external = dl.duplicate(registry); // External event processing (spec || []).forEach(function(sig) { var signal = model.signal(sig.name); if (sig.expr) return; // Cannot have an expr and stream definition. (sig.streams || []).forEach(function(stream) { var sel = selector.parse(stream.type), exp = expr(stream.expr); mergedStream(signal, sel, exp, stream); }); }); // We register the event listeners all together so that if multiple // signals are registered on the same event, they will receive the // new value on the same pulse. dl.keys(internal.handlers).forEach(function(type) { view.on(type, function(evt, item) { evt.preventDefault(); // stop text selection extendEvent(evt, item); fire(internal, type, (item && item.datum) || {}, evt); }); }); // add external event listeners dl.keys(external.handlers).forEach(function(type) { if (typeof window === 'undefined') return; // No external support var h = external.handlers[type], t = type.split(':'), // --> no element pseudo-selectors elt = (t[0] === 'window') ? [window] : window.document.querySelectorAll(t[0]); function handler(evt) { extendEvent(evt); fire(external, type, d3.select(this).datum(), evt); } for (var i=0; i<elt.length; ++i) { elt[i].addEventListener(t[1], handler); } h.elements = elt; h.listener = handler; }); // remove external event listeners external.detach = function() { dl.keys(external.handlers).forEach(function(type) { var h = external.handlers[type], t = type.split(':'), elt = h.elements || []; for (var i=0; i<elt.length; ++i) { elt[i].removeEventListener(t[1], h.listener); } }); }; // export detach method return external.detach; // -- helper functions ----- function extendEvent(evt, item) { var mouse = d3.mouse((d3.event=evt, view._el)), pad = view.padding(), names = {}, mark, group, i; if (item) { mark = item.mark; group = mark.marktype === 'group' ? item : mark.group; for (i=item; i!=null; i=i.mark.group) { if (i.mark.def.name) { names[i.mark.def.name] = i; } } } names.root = view.model().scene().items[0]; evt.vg = Object.create(vgEvent); evt.vg.group = group; evt.vg.item = item || {}; evt.vg.name = names; evt.vg.x = mouse[0] - pad.left; evt.vg.y = mouse[1] - pad.top; } function fire(registry, type, datum, evt) { var handlers = registry.handlers[type], node = registry.nodes[type], cs = df.ChangeSet.create(null, true), filtered = false, val, i, n, h; function invoke(f) { return !f.fn(datum, evt, model.signalValues(f.globals)); } for (i=0, n=handlers.length; i<n; ++i) { h = handlers[i]; filtered = h.filters.some(invoke); if (filtered) continue; val = h.exp.fn(datum, evt, model.signalValues(h.exp.globals)); if (h.spec.scale) { val = parseSignals.scale(model, h.spec, val, datum, evt); } if (val !== h.signal.value() || h.signal.verbose()) { h.signal.value(val); cs.signals[h.signal.name()] = 1; } } model.propagate(cs, node); } function mergedStream(sig, selector, exp, spec) { selector.forEach(function(s) { if (s.event) domEvent(sig, s, exp, spec); else if (s.signal) signal(sig, s, exp, spec); else if (s.start) orderedStream(sig, s, exp, spec); else if (s.stream) mergedStream(sig, s.stream, exp, spec); }); } function domEvent(sig, selector, exp, spec) { var evt = selector.event, name = selector.name, mark = selector.mark, target = selector.target, filters = selector.filters || [], registry = target ? external : internal, type = target ? target+':'+evt : evt, node = registry.nodes[type] || (registry.nodes[type] = new df.Node(model)), handlers = registry.handlers[type] || (registry.handlers[type] = []); if (name) { filters.push('!!event.vg.name["' + name + '"]'); // Mimic event bubbling } else if (mark) { filters.push('event.vg.item.mark && event.vg.item.mark.marktype==='+dl.str(mark)); } handlers.push({ signal: sig, exp: exp, spec: spec, filters: filters.map(function(f) { return expr(f); }) }); node.addListener(sig); } function signal(sig, selector, exp, spec) { var n = new df.Node(model); n.evaluate = function(input) { if (!input.signals[selector.signal]) return model.doNotPropagate; var val = exp.fn(null, null, model.signalValues(exp.globals)); if (spec.scale) { val = parseSignals.scale(model, spec, val); } if (val !== sig.value() || sig.verbose()) { sig.value(val); input.signals[sig.name()] = 1; input.reflow = true; } return input; }; n.dependency(df.Dependencies.SIGNALS, selector.signal); n.addListener(sig); model.signal(selector.signal).addListener(n); } function orderedStream(sig, selector, exp, spec) { var name = sig.name(), trueFn = expr('true'), falseFn = expr('false'), middle = selector.middle, filters = middle.filters || (middle.filters = []), gatekeeper = model.signal(name + GATEKEEPER, false); // Register an anonymous signal to act as a gatekeeper. Its value is // true or false depending on whether the start or end streams occur. // The middle signal then simply filters for the gatekeeper's value. mergedStream(gatekeeper, [selector.start], trueFn, {}); mergedStream(gatekeeper, [selector.end], falseFn, {}); filters.push(gatekeeper.name()); mergedStream(sig, [selector.middle], exp, spec); } } module.exports = parseStreams; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./events":93,"./expr":94,"./signals":103,"datalib":24,"vega-dataflow":39}],106:[function(require,module,exports){ var dl = require('datalib'), transforms = require('../transforms/index'); function parseTransforms(model, def) { var tx = new transforms[def.type](model); // We want to rename output fields before setting any other properties, // as subsequent properties may require output to be set (e.g. group by). if(def.output) tx.output(def.output); dl.keys(def).forEach(function(k) { if(k === 'type' || k === 'output') return; tx.param(k, def[k]); }); return tx; } module.exports = parseTransforms; },{"../transforms/index":139,"datalib":24}],107:[function(require,module,exports){ var dl = require('datalib'), df = require('vega-dataflow'), Node = df.Node, // jshint ignore:line log = require('vega-logging'), bound = require('vega-scenegraph').bound, Encoder = require('./Encoder'); function Bounder(graph, mark) { this._mark = mark; return Node.prototype.init.call(this, graph) .router(true) .reflows(true) .mutates(true); } var proto = (Bounder.prototype = new Node()); proto.evaluate = function(input) { log.debug(input, ['bounds', this._mark.marktype]); var type = this._mark.marktype, isGrp = type === 'group', items = this._mark.items, hasLegends = dl.array(this._mark.def.legends).length > 0, i, ilen, j, jlen, group, legend; if (input.add.length || input.rem.length || !items.length || input.mod.length === items.length || type === 'area' || type === 'line') { bound.mark(this._mark, null, isGrp && !hasLegends); } else { input.mod.forEach(function(item) { bound.item(item); }); } if (isGrp && hasLegends) { for (i=0, ilen=items.length; i<ilen; ++i) { group = items[i]; group._legendPositions = null; for (j=0, jlen=group.legendItems.length; j<jlen; ++j) { legend = group.legendItems[j]; Encoder.update(this._graph, input.trans, 'vg_legendPosition', legend.items, input.dirty); bound.mark(legend, null, false); } } bound.mark(this._mark, null, true); } return df.ChangeSet.create(input, true); }; module.exports = Bounder; },{"./Encoder":109,"datalib":24,"vega-dataflow":39,"vega-logging":45,"vega-scenegraph":46}],108:[function(require,module,exports){ var dl = require('datalib'), log = require('vega-logging'), Item = require('vega-scenegraph').Item, df = require('vega-dataflow'), Node = df.Node, // jshint ignore:line Deps = df.Dependencies, Tuple = df.Tuple, ChangeSet = df.ChangeSet, Sentinel = {}, Encoder = require('./Encoder'), Bounder = require('./Bounder'), parseData = require('../parse/data'); function Builder() { return arguments.length ? this.init.apply(this, arguments) : this; } var Status = Builder.STATUS = { ENTER: 'enter', UPDATE: 'update', EXIT: 'exit' }; var proto = (Builder.prototype = new Node()); proto.init = function(graph, def, mark, parent, parent_id, inheritFrom) { Node.prototype.init.call(this, graph) .router(true) .collector(true); this._def = def; this._mark = mark; this._from = (def.from ? def.from.data : null) || inheritFrom; this._ds = dl.isString(this._from) ? graph.data(this._from) : null; this._map = {}; mark.def = def; mark.marktype = def.type; mark.interactive = (def.interactive !== false); mark.items = []; if (dl.isValid(def.name)) mark.name = def.name; this._parent = parent; this._parent_id = parent_id; if (def.from && (def.from.mark || def.from.transform || def.from.modify)) { inlineDs.call(this); } // Non-group mark builders are super nodes. Encoder and Bounder remain // separate operators but are embedded and called by Builder.evaluate. this._isSuper = (this._def.type !== 'group'); this._encoder = new Encoder(this._graph, this._mark, this); this._bounder = new Bounder(this._graph, this._mark); this._output = null; // Output changeset for reactive geom as Bounder reflows if (this._ds) { this._encoder.dependency(Deps.DATA, this._from); } // Since Builders are super nodes, copy over encoder dependencies // (bounder has no registered dependencies). this.dependency(Deps.DATA, this._encoder.dependency(Deps.DATA)); this.dependency(Deps.SCALES, this._encoder.dependency(Deps.SCALES)); this.dependency(Deps.SIGNALS, this._encoder.dependency(Deps.SIGNALS)); return this; }; // Reactive geometry and mark-level transformations are handled here // because they need their group's data-joined context. function inlineDs() { var from = this._def.from, geom = from.mark, src, name, spec, sibling, output, input; if (geom) { name = ['vg', this._parent_id, geom].join('_'); spec = { name: name, transform: from.transform, modify: from.modify }; } else { src = this._graph.data(this._from); name = ['vg', this._from, this._def.type, src.listeners(true).length].join('_'); spec = { name: name, source: this._from, transform: from.transform, modify: from.modify }; } this._from = name; this._ds = parseData.datasource(this._graph, spec); var node; if (geom) { sibling = this.sibling(geom); // Bounder reflows, so we need an intermediary node to propagate // the output constructed by the Builder. node = new Node(this._graph).addListener(this._ds.listener()); node.evaluate = function() { return sibling._output; }; if (sibling._isSuper) { sibling.addListener(node); } else { sibling._bounder.addListener(node); } } else { // At this point, we have a new datasource but it is empty as // the propagation cycle has already crossed the datasources. // So, we repulse just this datasource. This should be safe // as the ds isn't connected to the scenegraph yet. output = this._ds.source().last(); input = ChangeSet.create(output); input.add = output.add; input.mod = output.mod; input.rem = output.rem; input.stamp = null; this._graph.propagate(input, this._ds.listener(), output.stamp); } } proto.ds = function() { return this._ds; }; proto.parent = function() { return this._parent; }; proto.encoder = function() { return this._encoder; }; proto.pipeline = function() { return [this]; }; proto.connect = function() { var builder = this; this._graph.connect(this.pipeline()); this._encoder._scales.forEach(function(s) { if (!(s = builder._parent.scale(s))) return; s.addListener(builder); }); if (this._parent) { if (this._isSuper) this.addListener(this._parent._collector); else this._bounder.addListener(this._parent._collector); } return this; }; proto.disconnect = function() { var builder = this; if (!this._listeners.length) return this; Node.prototype.disconnect.call(this); this._graph.disconnect(this.pipeline()); this._encoder._scales.forEach(function(s) { if (!(s = builder._parent.scale(s))) return; s.removeListener(builder); }); return this; }; proto.sibling = function(name) { return this._parent.child(name, this._parent_id); }; proto.evaluate = function(input) { log.debug(input, ['building', (this._from || this._def.from), this._def.type]); var self = this, def = this._mark.def, props = def.properties || {}, update = props.update || {}, output, fullUpdate, fcs, data, name; if (this._ds) { output = ChangeSet.create(input); // We need to determine if any encoder dependencies have been updated. // However, the encoder's data source will likely be updated, and shouldn't // trigger all items to mod. data = output.data[(name=this._ds.name())]; delete output.data[name]; fullUpdate = this._encoder.reevaluate(output); output.data[name] = data; // If a scale or signal in the update propset has been updated, // send forward all items for reencoding if we do an early return. if (fullUpdate) output.mod = this._mark.items.slice(); fcs = this._ds.last(); if (!fcs) throw Error('Builder evaluated before backing DataSource.'); if (fcs.stamp > this._stamp) { output = join.call(this, fcs, this._ds.values(), true, fullUpdate); } } else { data = dl.isFunction(this._def.from) ? this._def.from() : [Sentinel]; output = join.call(this, input, data); } // Stash output before Bounder for downstream reactive geometry. this._output = output = this._graph.evaluate(output, this._encoder); // Add any new scale references to the dependency list, and ensure // they're connected. if (update.nested && update.nested.length) { dl.keys(this._mark._scaleRefs).forEach(function(s) { var scale = self._parent.scale(s); if (!scale) return; scale.addListener(self); self.dependency(Deps.SCALES, s); self._encoder.dependency(Deps.SCALES, s); }); } // Supernodes calculate bounds too, but only on items marked dirty. if (this._isSuper) { output.mod = output.mod.filter(function(x) { return x._dirty; }); output = this._graph.evaluate(output, this._bounder); } return output; }; function newItem() { var item = Tuple.ingest(new Item(this._mark)); // For the root node's item if (this._def.width) Tuple.set(item, 'width', this._def.width); if (this._def.height) Tuple.set(item, 'height', this._def.height); return item; } function join(input, data, ds, fullUpdate) { var output = ChangeSet.create(input), keyf = keyFunction(this._def.key || (ds ? '_id' : null)), prev = this._mark.items || [], rem = ds ? input.rem : prev, mod = Tuple.idMap((!ds || fullUpdate) ? data : input.mod), next = [], i, key, len, item, datum, enter; // Only mark rems as exiting. Due to keyf, there may be an add/mod // tuple that replaces it. for (i=0, len=rem.length; i<len; ++i) { item = (rem[i] === prev[i]) ? prev[i] : keyf ? this._map[keyf(rem[i])] : rem[i]; item.status = Status.EXIT; } for(i=0, len=data.length; i<len; ++i) { datum = data[i]; item = keyf ? this._map[key = keyf(data[i])] : prev[i]; enter = item ? false : (item = newItem.call(this), true); item.status = enter ? Status.ENTER : Status.UPDATE; item.datum = datum; if (keyf) { Tuple.set(item, 'key', key); this._map[key] = item; } if (enter) { output.add.push(item); } else if (mod[datum._id]) { output.mod.push(item); } next.push(item); } for (i=0, len=rem.length; i<len; ++i) { item = (rem[i] === prev[i]) ? prev[i] : keyf ? this._map[key = keyf(rem[i])] : rem[i]; if (item.status === Status.EXIT) { item._dirty = true; input.dirty.push(item); next.push(item); output.rem.push(item); if (keyf) this._map[key] = null; } } return (this._mark.items = next, output); } function keyFunction(key) { if (key == null) return null; var f = dl.array(key).map(dl.accessor); return function(d) { for (var s='', i=0, n=f.length; i<n; ++i) { if (i>0) s += '|'; s += String(f[i](d)); } return s; }; } module.exports = Builder; },{"../parse/data":92,"./Bounder":107,"./Encoder":109,"datalib":24,"vega-dataflow":39,"vega-logging":45,"vega-scenegraph":46}],109:[function(require,module,exports){ var dl = require('datalib'), log = require('vega-logging'), df = require('vega-dataflow'), Node = df.Node, // jshint ignore:line Deps = df.Dependencies, bound = require('vega-scenegraph').bound; var EMPTY = {}; function Encoder(graph, mark, builder) { var props = mark.def.properties || {}, enter = props.enter, update = props.update, exit = props.exit; Node.prototype.init.call(this, graph); this._mark = mark; this._builder = builder; var s = this._scales = []; // Only scales used in the 'update' property set are set as // encoder depedencies to have targeted reevaluations. However, // we still want scales in 'enter' and 'exit' to be evaluated // before the encoder. if (enter) s.push.apply(s, enter.scales); if (update) { this.dependency(Deps.DATA, update.data); this.dependency(Deps.SIGNALS, update.signals); this.dependency(Deps.FIELDS, update.fields); this.dependency(Deps.SCALES, update.scales); s.push.apply(s, update.scales); } if (exit) s.push.apply(s, exit.scales); return this.mutates(true); } var proto = (Encoder.prototype = new Node()); proto.evaluate = function(input) { log.debug(input, ['encoding', this._mark.def.type]); var graph = this._graph, props = this._mark.def.properties || {}, items = this._mark.items, enter = props.enter, update = props.update, exit = props.exit, dirty = input.dirty, preds = this._graph.predicates(), sg = graph.signalValues(), // For expediency, get all signal values db = graph.dataValues(), req = input.request, group = this._mark.group, guide = group && (group.mark.axis || group.mark.legend), i, len, item, prop; if (req && !guide) { if ((prop = props[req])) { for (i=0, len=input.mod.length; i<len; ++i) { item = input.mod[i]; encode.call(this, prop, item, input.trans, db, sg, preds, dirty); } } return input; // exit early if given request } // Items marked for removal are at the tail of items. Process them first. for (i=0, len=input.rem.length; i<len; ++i) { item = input.rem[i]; if (exit) encode.call(this, exit, item, input.trans, db, sg, preds, dirty); if (input.trans && !exit) input.trans.interpolate(item, EMPTY); else if (!input.trans) items.pop(); } for (i=0, len=input.add.length; i<len; ++i) { item = input.add[i]; if (enter) encode.call(this, enter, item, input.trans, db, sg, preds, dirty); if (update) encode.call(this, update, item, input.trans, db, sg, preds, dirty); item.status = require('./Builder').STATUS.UPDATE; } if (update) { for (i=0, len=input.mod.length; i<len; ++i) { item = input.mod[i]; encode.call(this, update, item, input.trans, db, sg, preds, dirty); } } return input; }; function encode(prop, item, trans, db, sg, preds, dirty) { var enc = prop.encode, wasDirty = item._dirty, isDirty = enc.call(enc, item, item.mark.group||item, trans, db, sg, preds); item._dirty = isDirty || wasDirty; if (isDirty && !wasDirty) dirty.push(item); } // If a specified property set called, or update property set // uses nested fieldrefs, reevaluate all items. proto.reevaluate = function(pulse) { var def = this._mark.def, props = def.properties || {}, reeval = dl.isFunction(def.from) || def.orient || pulse.request || Node.prototype.reevaluate.call(this, pulse); return reeval || (props.update ? nestedRefs.call(this) : false); }; // Test if any nested refs trigger a reflow of mark items. function nestedRefs() { var refs = this._mark.def.properties.update.nested, parent = this._builder, level = 0, i = 0, len = refs.length, ref, ds, stamp; for (; i<len; ++i) { ref = refs[i]; // Scale references are resolved via this._mark._scaleRefs which are // added to dependency lists + connected in Builder.evaluate. if (ref.scale) continue; for (; level<ref.level; ++level) { parent = parent.parent(); ds = parent.ds(); } // Compare stamps to determine if a change in a group's properties // or data should trigger a reeval. We cannot check anything fancier // (e.g., pulse.fields) as the ref may use item.datum. stamp = (ref.group ? parent.encoder() : ds.last())._stamp; if (stamp > this._stamp) return true; } return false; } // Short-circuit encoder if user specifies items Encoder.update = function(graph, trans, request, items, dirty) { items = dl.array(items); var preds = graph.predicates(), db = graph.dataValues(), sg = graph.signalValues(), i, len, item, props, prop; for (i=0, len=items.length; i<len; ++i) { item = items[i]; props = item.mark.def.properties; prop = props && props[request]; if (prop) { encode.call(null, prop, item, trans, db, sg, preds, dirty); bound.item(item); } } }; module.exports = Encoder; },{"./Builder":108,"datalib":24,"vega-dataflow":39,"vega-logging":45,"vega-scenegraph":46}],110:[function(require,module,exports){ var dl = require('datalib'), df = require('vega-dataflow'), Node = df.Node, // jshint ignore:line Deps = df.Dependencies, Collector = df.Collector, log = require('vega-logging'), Builder = require('./Builder'), Scale = require('./Scale'), parseAxes = require('../parse/axes'), parseLegends = require('../parse/legends'); function GroupBuilder() { this._children = {}; this._scaler = null; this._recursor = null; this._scales = {}; this.scale = scale.bind(this); return arguments.length ? this.init.apply(this, arguments) : this; } var Types = GroupBuilder.TYPES = { GROUP: "group", MARK: "mark", AXIS: "axis", LEGEND: "legend" }; var proto = (GroupBuilder.prototype = new Builder()); proto.init = function(graph, def) { var builder = this, name; this._scaler = new Node(graph); (def.scales||[]).forEach(function(s) { s = builder.scale((name=s.name), new Scale(graph, s, builder)); builder.scale(name+":prev", s); builder._scaler.addListener(s); // Scales should be computed after group is encoded }); this._recursor = new Node(graph); this._recursor.evaluate = recurse.bind(this); var scales = (def.axes||[]).reduce(function(acc, x) { return (acc[x.scale] = 1, acc); }, {}); scales = (def.legends||[]).reduce(function(acc, x) { return (acc[x.size || x.shape || x.fill || x.stroke], acc); }, scales); this._recursor.dependency(Deps.SCALES, dl.keys(scales)); // We only need a collector for up-propagation of bounds calculation, // so only GroupBuilders, and not regular Builders, have collectors. this._collector = new Collector(graph); return Builder.prototype.init.apply(this, arguments); }; proto.evaluate = function() { var output = Builder.prototype.evaluate.apply(this, arguments), builder = this; output.add.forEach(function(group) { buildGroup.call(builder, output, group); }); return output; }; proto.pipeline = function() { return [this, this._scaler, this._recursor, this._collector, this._bounder]; }; proto.disconnect = function() { var builder = this; dl.keys(builder._children).forEach(function(group_id) { builder._children[group_id].forEach(function(c) { builder._recursor.removeListener(c.builder); c.builder.disconnect(); }); }); builder._children = {}; return Builder.prototype.disconnect.call(this); }; proto.child = function(name, group_id) { var children = this._children[group_id], i = 0, len = children.length, child; for (; i<len; ++i) { child = children[i]; if (child.type == Types.MARK && child.builder._def.name == name) break; } return child.builder; }; function recurse(input) { var builder = this, hasMarks = dl.array(this._def.marks).length > 0, hasAxes = dl.array(this._def.axes).length > 0, hasLegends = dl.array(this._def.legends).length > 0, i, j, c, len, group, pipeline, def, inline = false; for (i=0, len=input.add.length; i<len; ++i) { group = input.add[i]; if (hasMarks) buildMarks.call(this, input, group); if (hasAxes) buildAxes.call(this, input, group); if (hasLegends) buildLegends.call(this, input, group); } // Wire up new children builders in reverse to minimize graph rewrites. for (i=input.add.length-1; i>=0; --i) { group = input.add[i]; for (j=this._children[group._id].length-1; j>=0; --j) { c = this._children[group._id][j]; c.builder.connect(); pipeline = c.builder.pipeline(); def = c.builder._def; // This new child needs to be built during this propagation cycle. // We could add its builder as a listener off the _recursor node, // but try to inline it if we can to minimize graph dispatches. inline = (def.type !== Types.GROUP); inline = inline && (this._graph.data(c.from) !== undefined); inline = inline && (pipeline[pipeline.length-1].listeners().length === 1); // Reactive geom source inline = inline && (def.from && !def.from.mark); // Reactive geom target c.inline = inline; if (inline) this._graph.evaluate(input, c.builder); else this._recursor.addListener(c.builder); } } function removeTemp(c) { if (c.type == Types.MARK && !c.inline && builder._graph.data(c.from) !== undefined) { builder._recursor.removeListener(c.builder); } } function updateAxis(a) { var scale = a.scale(); if (!input.scales[scale.scaleName]) return; a.reset().def(); } function updateLegend(l) { var scale = l.size() || l.shape() || l.fill() || l.stroke(); if (!input.scales[scale.scaleName]) return; l.reset().def(); } for (i=0, len=input.mod.length; i<len; ++i) { group = input.mod[i]; // Remove temporary connection for marks that draw from a source if (hasMarks) builder._children[group._id].forEach(removeTemp); // Update axis data defs if (hasAxes) group.axes.forEach(updateAxis); // Update legend data defs if (hasLegends) group.legends.forEach(updateLegend); } function disconnectChildren(c) { builder._recursor.removeListener(c.builder); c.builder.disconnect(); } for (i=0, len=input.rem.length; i<len; ++i) { group = input.rem[i]; // For deleted groups, disconnect their children builder._children[group._id].forEach(disconnectChildren); delete builder._children[group._id]; } return input; } function scale(name, s) { var group = this; if (arguments.length === 2) return (group._scales[name] = s, s); while (s == null) { s = group._scales[name]; group = group.mark ? group.mark.group : group._parent; if (!group) break; } return s; } function buildGroup(input, group) { log.debug(input, ["building group", group._id]); group._scales = group._scales || {}; group.scale = scale.bind(group); group.items = group.items || []; this._children[group._id] = this._children[group._id] || []; group.axes = group.axes || []; group.axisItems = group.axisItems || []; group.legends = group.legends || []; group.legendItems = group.legendItems || []; } function buildMarks(input, group) { log.debug(input, ["building children marks #"+group._id]); var marks = this._def.marks, mark, from, inherit, i, len, b; for (i=0, len=marks.length; i<len; ++i) { mark = marks[i]; from = mark.from || {}; inherit = group.datum._facetID; group.items[i] = {group: group, _scaleRefs: {}}; b = (mark.type === Types.GROUP) ? new GroupBuilder() : new Builder(); b.init(this._graph, mark, group.items[i], this, group._id, inherit); this._children[group._id].push({ builder: b, from: from.data || (from.mark ? ("vg_" + group._id + "_" + from.mark) : inherit), type: Types.MARK }); } } function buildAxes(input, group) { var axes = group.axes, axisItems = group.axisItems, builder = this; parseAxes(this._graph, this._def.axes, axes, group); axes.forEach(function(a, i) { var scale = builder._def.axes[i].scale, def = a.def(), b = null; axisItems[i] = {group: group, axis: true, layer: def.layer}; b = (def.type === Types.GROUP) ? new GroupBuilder() : new Builder(); b.init(builder._graph, def, axisItems[i], builder) .dependency(Deps.SCALES, scale); builder._children[group._id].push({ builder: b, type: Types.AXIS, scale: scale }); }); } function buildLegends(input, group) { var legends = group.legends, legendItems = group.legendItems, builder = this; parseLegends(this._graph, this._def.legends, legends, group); legends.forEach(function(l, i) { var scale = l.size() || l.shape() || l.fill() || l.stroke(), def = l.def(), b = null; legendItems[i] = {group: group, legend: true}; b = (def.type === Types.GROUP) ? new GroupBuilder() : new Builder(); b.init(builder._graph, def, legendItems[i], builder) .dependency(Deps.SCALES, scale); builder._children[group._id].push({ builder: b, type: Types.LEGEND, scale: scale }); }); } module.exports = GroupBuilder; },{"../parse/axes":90,"../parse/legends":96,"./Builder":108,"./Scale":111,"datalib":24,"vega-dataflow":39,"vega-logging":45}],111:[function(require,module,exports){ (function (global){ var d3 = (typeof window !== "undefined" ? window['d3'] : typeof global !== "undefined" ? global['d3'] : null), dl = require('datalib'), df = require('vega-dataflow'), log = require('vega-logging'), Node = df.Node, // jshint ignore:line Deps = df.Dependencies, Aggregate = require('../transforms/Aggregate'); var Properties = { width: 1, height: 1 }; var Types = { LINEAR: 'linear', ORDINAL: 'ordinal', LOG: 'log', POWER: 'pow', SQRT: 'sqrt', TIME: 'time', TIME_UTC: 'utc', QUANTILE: 'quantile', QUANTIZE: 'quantize', THRESHOLD: 'threshold' }; var DataRef = { DOMAIN: 'domain', RANGE: 'range', COUNT: 'count', GROUPBY: 'groupby', MIN: 'min', MAX: 'max', VALUE: 'value', ASC: 'asc', DESC: 'desc' }; function Scale(graph, def, parent) { this._def = def; this._parent = parent; this._updated = false; return Node.prototype.init.call(this, graph).reflows(true); } var proto = (Scale.prototype = new Node()); proto.evaluate = function(input) { var self = this, fn = function(group) { scale.call(self, group); }; this._updated = false; input.add.forEach(fn); input.mod.forEach(fn); // Scales are at the end of an encoding pipeline, so they should forward a // reflow pulse. Thus, if multiple scales update in the parent group, we don't // reevaluate child marks multiple times. if (this._updated) { input.scales[this._def.name] = 1; log.debug(input, ["scale", this._def.name]); } return df.ChangeSet.create(input, true); }; // All of a scale's dependencies are registered during propagation as we parse // dataRefs. So a scale must be responsible for connecting itself to dependents. proto.dependency = function(type, deps) { if (arguments.length == 2) { var method = (type === Deps.DATA ? 'data' : 'signal'); deps = dl.array(deps); for (var i=0, len=deps.length; i<len; ++i) { this._graph[method](deps[i]).addListener(this._parent); } } return Node.prototype.dependency.call(this, type, deps); }; function scale(group) { var name = this._def.name, prev = name + ':prev', s = instance.call(this, group.scale(name)), m = s.type===Types.ORDINAL ? ordinal : quantitative, rng = range.call(this, group); m.call(this, s, rng, group); group.scale(name, s); group.scale(prev, group.scale(prev) || s); return s; } function instance(scale) { var config = this._graph.config(), type = this._def.type || Types.LINEAR; if (!scale || type !== scale.type) { var ctor = config.scale[type] || d3.scale[type]; if (!ctor) throw Error('Unrecognized scale type: ' + type); (scale = ctor()).type = scale.type || type; scale.scaleName = this._def.name; scale._prev = {}; } return scale; } function ordinal(scale, rng, group) { var def = this._def, prev = scale._prev, dataDrivenRange = false, pad = signal.call(this, def.padding) || 0, outer = def.outerPadding == null ? pad : signal.call(this, def.outerPadding), points = def.points && signal.call(this, def.points), round = signal.call(this, def.round) || def.round == null, domain, str; // range pre-processing for data-driven ranges if (dl.isObject(def.range) && !dl.isArray(def.range)) { dataDrivenRange = true; rng = dataRef.call(this, DataRef.RANGE, def.range, scale, group); } // domain domain = dataRef.call(this, DataRef.DOMAIN, def.domain, scale, group); if (domain && !dl.equal(prev.domain, domain)) { scale.domain(domain); prev.domain = domain; this._updated = true; } // range if (dl.equal(prev.range, rng)) return; // width-defined range if (def.bandWidth) { var bw = signal.call(this, def.bandWidth), len = domain.length, space = def.points ? (pad*bw) : (pad*bw*(len-1) + 2*outer), start; if (rng[0] > rng[1]) { start = rng[1] || 0; rng = [start + (bw * len + space), start]; } else { start = rng[0] || 0; rng = [start, start + (bw * len + space)]; } } str = typeof rng[0] === 'string'; if (str || rng.length > 2 || rng.length===1 || dataDrivenRange) { scale.range(rng); // color or shape values } else if (points && round) { scale.rangeRoundPoints(rng, pad); } else if (points) { scale.rangePoints(rng, pad); } else if (round) { scale.rangeRoundBands(rng, pad, outer); } else { scale.rangeBands(rng, pad, outer); } if (!scale.invert) { scale.invert = function(x, y) { if (arguments.length === 1) { return scale.domain()[d3.bisect(scale.range(), x) - 1]; } else if (arguments.length === 2) { // Invert extents if (!dl.isNumber(x) || !dl.isNumber(y)) { throw Error('Extents to ordinal invert are not numbers ('+x+', '+y+').'); } var points = [], rng = scale.range(), i = 0, len = rng.length, r; for(; i<len; ++i) { r = rng[i]; if (x < y ? x <= r && r <= y : y <= r && r <= x) { points.push(r); } } return points.map(function(p) { return scale.invert(p); }); } }; } prev.range = rng; this._updated = true; } function quantitative(scale, rng, group) { var def = this._def, prev = scale._prev, round = signal.call(this, def.round), exponent = signal.call(this, def.exponent), clamp = signal.call(this, def.clamp), nice = signal.call(this, def.nice), domain, interval; // domain domain = (def.type === Types.QUANTILE) ? dataRef.call(this, DataRef.DOMAIN, def.domain, scale, group) : domainMinMax.call(this, scale, group); if (domain && !dl.equal(prev.domain, domain)) { scale.domain(domain); prev.domain = domain; this._updated = true; } // range // vertical scales should flip by default, so use XOR here if (signal.call(this, def.range) === 'height') rng = rng.reverse(); if (dl.equal(prev.range, rng)) return; scale[round && scale.rangeRound ? 'rangeRound' : 'range'](rng); prev.range = rng; this._updated = true; // TODO: Support signals for these properties. Until then, only eval // them once. if (this._stamp > 0) return; if (exponent && def.type===Types.POWER) scale.exponent(exponent); if (clamp) scale.clamp(true); if (nice) { if (def.type === Types.TIME) { interval = d3.time[nice]; if (!interval) log.error('Unrecognized interval: ' + interval); scale.nice(interval); } else { scale.nice(); } } } function isUniques(scale) { return scale.type === Types.ORDINAL || scale.type === Types.QUANTILE; } function getRefs(def) { return def.fields || dl.array(def); } function inherits(refs) { return refs.some(function(r) { if (!r.data) return true; return r.data && dl.array(r.field).some(function(f) { return f.parent; }); }); } function getFields(ref, group) { return dl.array(ref.field).map(function(f) { return f.parent ? dl.accessor(f.parent)(group.datum) : f; // String or {'signal'} }); } // Scale datarefs can be computed over multiple schema types. // This function determines the type of aggregator created, and // what data is sent to it: values, tuples, or multi-tuples that must // be standardized into a consistent schema. function aggrType(def, scale) { var refs = getRefs(def); // If we're operating over only a single domain, send full tuples // through for efficiency (fewer accessor creations/calls) if (refs.length == 1 && dl.array(refs[0].field).length == 1) { return Aggregate.TYPES.TUPLE; } // With quantitative scales, we only care about min/max. if (!isUniques(scale)) return Aggregate.TYPES.VALUE; // If we don't sort, then we can send values directly to aggrs as well if (!def.sort) return Aggregate.TYPES.VALUE; return Aggregate.TYPES.MULTI; } function getCache(which, def, scale, group) { var refs = getRefs(def), inherit = inherits(refs), atype = aggrType(def, scale), uniques = isUniques(scale), sort = def.sort, ck = '_'+which, fields = getFields(refs[0], group); if (scale[ck] || this[ck]) return scale[ck] || this[ck]; var cache = new Aggregate(this._graph).type(atype), groupby, summarize; // If a scale's dataref doesn't inherit data from the group, we can // store the dataref aggregator at the Scale (dataflow node) level. if (inherit) { scale[ck] = cache; } else { this[ck] = cache; } if (uniques) { if (atype === Aggregate.TYPES.VALUE) { groupby = [{ name: DataRef.GROUPBY, get: dl.identity }]; summarize = {'*': DataRef.COUNT}; } else if (atype === Aggregate.TYPES.TUPLE) { groupby = [{ name: DataRef.GROUPBY, get: dl.$(fields[0]) }]; summarize = sort ? [{ field: DataRef.VALUE, get: dl.$(sort.field), ops: [sort.op] }] : {'*': DataRef.COUNT}; } else { // atype === Aggregate.TYPES.MULTI groupby = DataRef.GROUPBY; summarize = [{ field: DataRef.VALUE, ops: [sort.op] }]; } } else { groupby = []; summarize = [{ field: DataRef.VALUE, get: (atype == Aggregate.TYPES.TUPLE) ? dl.$(fields[0]) : dl.identity, ops: [DataRef.MIN, DataRef.MAX], as: [DataRef.MIN, DataRef.MAX] }]; } cache.param('groupby', groupby) .param('summarize', summarize); return (cache._lastUpdate = -1, cache); } function dataRef(which, def, scale, group) { if (def == null) { return []; } if (dl.isArray(def)) return def.map(signal.bind(this)); var self = this, graph = this._graph, refs = getRefs(def), inherit = inherits(refs), atype = aggrType(def, scale), cache = getCache.apply(this, arguments), sort = def.sort, uniques = isUniques(scale), i, rlen, j, flen, ref, fields, field, data, from, cmp; function addDep(s) { self.dependency(Deps.SIGNALS, s); } if (inherit || (!inherit && cache._lastUpdate < this._stamp)) { for (i=0, rlen=refs.length; i<rlen; ++i) { ref = refs[i]; from = ref.data || group.datum._facetID; data = graph.data(from).last(); if (data.stamp <= this._stamp) continue; fields = getFields(ref, group); for (j=0, flen=fields.length; j<flen; ++j) { field = fields[j]; if (atype === Aggregate.TYPES.VALUE) { cache.accessors(null, field); } else if (atype === Aggregate.TYPES.MULTI) { cache.accessors(field, ref.sort || sort.field); } // Else (Tuple-case) is handled by the aggregator accessors by default cache.evaluate(data); } this.dependency(Deps.DATA, from); cache.dependency(Deps.SIGNALS).forEach(addDep); } cache._lastUpdate = this._stamp; data = cache.aggr().result(); if (uniques) { if (sort) { cmp = sort.order.signal ? graph.signalRef(sort.order.signal) : sort.order; cmp = (cmp == DataRef.DESC ? '-' : '+') + sort.op + '_' + DataRef.VALUE; cmp = dl.comparator(cmp); data = data.sort(cmp); } cache._values = data.map(function(d) { return d[DataRef.GROUPBY]; }); } else { data = data[0]; cache._values = !dl.isValid(data) ? [] : [data[DataRef.MIN], data[DataRef.MAX]]; } } return cache._values; } function signal(v) { if (!v || !v.signal) return v; var s = v.signal, ref; this.dependency(Deps.SIGNALS, (ref = dl.field(s))[0]); return this._graph.signalRef(ref); } function domainMinMax(scale, group) { var def = this._def, domain = [null, null], z; if (def.domain !== undefined) { domain = (!dl.isObject(def.domain)) ? domain : dataRef.call(this, DataRef.DOMAIN, def.domain, scale, group); } z = domain.length - 1; if (def.domainMin !== undefined) { if (dl.isObject(def.domainMin)) { if (def.domainMin.signal) { domain[0] = signal.call(this, def.domainMin); } else { domain[0] = dataRef.call(this, DataRef.DOMAIN+DataRef.MIN, def.domainMin, scale, group)[0]; } } else { domain[0] = def.domainMin; } } if (def.domainMax !== undefined) { if (dl.isObject(def.domainMax)) { if (def.domainMax.signal) { domain[z] = signal.call(this, def.domainMax); } else { domain[z] = dataRef.call(this, DataRef.DOMAIN+DataRef.MAX, def.domainMax, scale, group)[1]; } } else { domain[z] = def.domainMax; } } if (def.type !== Types.LOG && def.type !== Types.TIME && (def.zero || def.zero===undefined)) { domain[0] = Math.min(0, domain[0]); domain[z] = Math.max(0, domain[z]); } return domain; } function range(group) { var def = this._def, config = this._graph.config(), rangeVal = signal.call(this, def.range), rng = [null, null]; if (rangeVal !== undefined) { if (typeof rangeVal === 'string') { if (Properties[rangeVal]) { rng = [0, group[rangeVal]]; } else if (config.range[rangeVal]) { rng = config.range[rangeVal]; } else { log.error('Unrecogized range: ' + rangeVal); return rng; } } else if (dl.isArray(rangeVal)) { rng = dl.duplicate(rangeVal).map(signal.bind(this)); } else if (dl.isObject(rangeVal)) { return null; // early exit } else { rng = [0, rangeVal]; } } if (def.rangeMin !== undefined) { rng[0] = def.rangeMin.signal ? signal.call(this, def.rangeMin) : def.rangeMin; } if (def.rangeMax !== undefined) { rng[rng.length-1] = def.rangeMax.signal ? signal.call(this, def.rangeMax) : def.rangeMax; } if (def.reverse !== undefined) { var rev = signal.call(this, def.reverse); if (dl.isObject(rev)) { rev = dl.accessor(rev.field)(group.datum); } if (rev) rng = rng.reverse(); } return rng; } module.exports = Scale; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../transforms/Aggregate":116,"datalib":24,"vega-dataflow":39,"vega-logging":45}],112:[function(require,module,exports){ (function (global){ var d3 = (typeof window !== "undefined" ? window['d3'] : typeof global !== "undefined" ? global['d3'] : null), bound = require('vega-scenegraph').bound, Tuple = require('vega-dataflow').Tuple, Status = require('./Builder').STATUS; function Transition(duration, ease) { this.duration = duration || 500; this.ease = ease && d3.ease(ease) || d3.ease('cubic-in-out'); this.updates = {next: null}; } var prototype = Transition.prototype; var skip = { 'text': 1, 'url': 1 }; prototype.interpolate = function(item, values) { var key, curr, next, interp, list = null; for (key in values) { curr = item[key]; next = values[key]; if (curr !== next) { if (skip[key] || curr === undefined) { // skip interpolation for specific keys or undefined start values Tuple.set(item, key, next); } else if (typeof curr === 'number' && !isFinite(curr)) { // for NaN or infinite numeric values, skip to final value Tuple.set(item, key, next); } else { // otherwise lookup interpolator interp = d3.interpolate(curr, next); interp.property = key; (list || (list=[])).push(interp); } } } if (list === null && item.status === Status.EXIT) { list = []; // ensure exiting items are included } if (list != null) { list.item = item; list.ease = item.mark.ease || this.ease; list.next = this.updates.next; this.updates.next = list; } return this; }; prototype.start = function(callback) { var t = this, prev = t.updates, curr = prev.next; for (; curr!=null; prev=curr, curr=prev.next) { if (curr.item.status === Status.EXIT) { // Only mark item as exited when it is removed. curr.item.status = Status.UPDATE; curr.remove = true; } } t.callback = callback; d3.timer(function(elapsed) { return step.call(t, elapsed); }); }; function step(elapsed) { var list = this.updates, prev = list, curr = prev.next, duration = this.duration, item, delay, f, e, i, n, stop = true; for (; curr!=null; prev=curr, curr=prev.next) { item = curr.item; delay = item.delay || 0; f = (elapsed - delay) / duration; if (f < 0) { stop = false; continue; } if (f > 1) f = 1; e = curr.ease(f); for (i=0, n=curr.length; i<n; ++i) { item[curr[i].property] = curr[i](e); } item.touch(); bound.item(item); if (f === 1) { if (curr.remove) { item.status = Status.EXIT; item.remove(); } prev.next = curr.next; curr = prev; } else { stop = false; } } this.callback(); return stop; } module.exports = Transition; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./Builder":108,"vega-dataflow":39,"vega-scenegraph":46}],113:[function(require,module,exports){ var dl = require('datalib'), Tuple = require('vega-dataflow').Tuple, parseMark = require('../parse/mark'); var TIME = 'time', UTC = 'utc', STRING = 'string', ORDINAL = 'ordinal', NUMBER = 'number'; function axs(model) { var scale, config = model.config(), orient = config.axis.orient, offset = 0, titleOffset = config.axis.titleOffset, axisDef = {}, layer = 'front', grid = false, title = null, tickMajorSize = config.axis.tickSize, tickMinorSize = config.axis.tickSize, tickEndSize = config.axis.tickSize, tickPadding = config.axis.padding, tickValues = null, tickFormatString = null, tickFormatType = null, tickSubdivide = 0, tickCount = config.axis.ticks, gridLineStyle = {}, tickLabelStyle = {}, majorTickStyle = {}, minorTickStyle = {}, titleStyle = {}, domainStyle = {}, m = { // Axis marks as references for updates gridLines: {}, majorTicks: {}, minorTicks: {}, tickLabels: {}, domain: {}, title: {} }; var axis = {}; function reset() { axisDef.type = null; } function ingest(d) { return {data: d}; } function getTickFormat() { var formatType = tickFormatType || inferFormatType(); return getFormatter(formatType, tickFormatString); } function inferFormatType() { switch (scale.type) { case TIME: return TIME; case UTC: return UTC; case ORDINAL: return STRING; default: return NUMBER; } } // Adapted from d3 log scale // TODO customize? replace with range-size-aware filtering? function logFilter(domain, count, f) { if (count == null) return f; var base = scale.base(), k = Math.min(base, scale.ticks().length / count), v = domain[0] > 0 ? (e = 1e-12, Math.ceil) : (e = -1e-12, Math.floor), e; function log(x) { return (domain[0] < 0 ? -Math.log(x > 0 ? 0 : -x) : Math.log(x < 0 ? 0 : x)) / Math.log(base); } function pow(x) { return domain[0] < 0 ? -Math.pow(base, -x) : Math.pow(base, x); } return function(d) { return pow(v(log(d) + e)) / d >= k ? f(d) : ''; }; } function getFormatter(formatType, str) { var fmt = dl.format, log = scale.type === 'log', domain, f; switch (formatType) { case NUMBER: domain = scale.domain(); f = fmt.auto.number(domain, tickCount, str || (log ? '.1r' : null)); return log ? logFilter(domain, tickCount, f) : f; case TIME: return (str ? fmt : fmt.auto).time(str); case UTC: return (str ? fmt : fmt.auto).utc(str); default: return String; } } function getTicks(format) { var major = tickValues || (scale.ticks ? scale.ticks(tickCount) : scale.domain()), minor = axisSubdivide(scale, major, tickSubdivide).map(ingest); major = major.map(function(d) { return (d = ingest(d), d.label = format(d.data), d); }); return [major, minor]; } axis.def = function() { if (!axisDef.type) axis_def(scale); var ticks = getTicks(getTickFormat()); var tdata = title ? [title].map(ingest) : []; axisDef.marks[0].from = function() { return grid ? ticks[0] : []; }; axisDef.marks[1].from = function() { return ticks[0]; }; axisDef.marks[2].from = function() { return ticks[1]; }; axisDef.marks[3].from = axisDef.marks[1].from; axisDef.marks[4].from = function() { return [1]; }; axisDef.marks[5].from = function() { return tdata; }; axisDef.offset = offset; axisDef.orient = orient; axisDef.layer = layer; return axisDef; }; function axis_def(scale) { // setup scale mapping var newScale, oldScale, range; if (scale.type === ORDINAL) { newScale = {scale: scale.scaleName, offset: 0.5 + scale.rangeBand()/2}; oldScale = newScale; } else { newScale = {scale: scale.scaleName, offset: 0.5}; oldScale = {scale: scale.scaleName+':prev', offset: 0.5}; } range = axisScaleRange(scale); // setup axis marks dl.extend(m.gridLines, axisTicks(config)); dl.extend(m.majorTicks, axisTicks(config)); dl.extend(m.minorTicks, axisTicks(config)); dl.extend(m.tickLabels, axisTickLabels(config)); dl.extend(m.domain, axisDomain(config)); dl.extend(m.title, axisTitle(config)); m.gridLines.properties.enter.stroke = {value: config.axis.gridColor}; m.gridLines.properties.enter.strokeOpacity = {value: config.axis.gridOpacity}; // extend axis marks based on axis orientation axisTicksExtend(orient, m.gridLines, oldScale, newScale, Infinity); axisTicksExtend(orient, m.majorTicks, oldScale, newScale, tickMajorSize); axisTicksExtend(orient, m.minorTicks, oldScale, newScale, tickMinorSize); axisLabelExtend(orient, m.tickLabels, oldScale, newScale, tickMajorSize, tickPadding); axisDomainExtend(orient, m.domain, range, tickEndSize); axisTitleExtend(orient, m.title, range, titleOffset); // TODO get offset // add / override custom style properties dl.extend(m.gridLines.properties.update, gridLineStyle); dl.extend(m.majorTicks.properties.update, majorTickStyle); dl.extend(m.minorTicks.properties.update, minorTickStyle); dl.extend(m.tickLabels.properties.update, tickLabelStyle); dl.extend(m.domain.properties.update, domainStyle); dl.extend(m.title.properties.update, titleStyle); var marks = [m.gridLines, m.majorTicks, m.minorTicks, m.tickLabels, m.domain, m.title]; dl.extend(axisDef, { type: 'group', interactive: false, properties: { enter: { encode: axisUpdate, scales: [scale.scaleName], signals: [], data: [] }, update: { encode: axisUpdate, scales: [scale.scaleName], signals: [], data: [] } } }); axisDef.marks = marks.map(function(m) { return parseMark(model, m); }); } axis.scale = function(x) { if (!arguments.length) return scale; if (scale !== x) { scale = x; reset(); } return axis; }; axis.orient = function(x) { if (!arguments.length) return orient; if (orient !== x) { orient = x in axisOrients ? x + '' : config.axis.orient; reset(); } return axis; }; axis.title = function(x) { if (!arguments.length) return title; if (title !== x) { title = x; reset(); } return axis; }; axis.tickCount = function(x) { if (!arguments.length) return tickCount; tickCount = x; return axis; }; axis.tickValues = function(x) { if (!arguments.length) return tickValues; tickValues = x; return axis; }; axis.tickFormat = function(x) { if (!arguments.length) return tickFormatString; if (tickFormatString !== x) { tickFormatString = x; reset(); } return axis; }; axis.tickFormatType = function(x) { if (!arguments.length) return tickFormatType; if (tickFormatType !== x) { tickFormatType = x; reset(); } return axis; }; axis.tickSize = function(x, y) { if (!arguments.length) return tickMajorSize; var n = arguments.length - 1, major = +x, minor = n > 1 ? +y : tickMajorSize, end = n > 0 ? +arguments[n] : tickMajorSize; if (tickMajorSize !== major || tickMinorSize !== minor || tickEndSize !== end) { reset(); } tickMajorSize = major; tickMinorSize = minor; tickEndSize = end; return axis; }; axis.tickSubdivide = function(x) { if (!arguments.length) return tickSubdivide; tickSubdivide = +x; return axis; }; axis.offset = function(x) { if (!arguments.length) return offset; offset = dl.isObject(x) ? x : +x; return axis; }; axis.tickPadding = function(x) { if (!arguments.length) return tickPadding; if (tickPadding !== +x) { tickPadding = +x; reset(); } return axis; }; axis.titleOffset = function(x) { if (!arguments.length) return titleOffset; if (titleOffset !== +x) { titleOffset = +x; reset(); } return axis; }; axis.layer = function(x) { if (!arguments.length) return layer; if (layer !== x) { layer = x; reset(); } return axis; }; axis.grid = function(x) { if (!arguments.length) return grid; if (grid !== x) { grid = x; reset(); } return axis; }; axis.gridLineProperties = function(x) { if (!arguments.length) return gridLineStyle; if (gridLineStyle !== x) { gridLineStyle = x; } return axis; }; axis.majorTickProperties = function(x) { if (!arguments.length) return majorTickStyle; if (majorTickStyle !== x) { majorTickStyle = x; } return axis; }; axis.minorTickProperties = function(x) { if (!arguments.length) return minorTickStyle; if (minorTickStyle !== x) { minorTickStyle = x; } return axis; }; axis.tickLabelProperties = function(x) { if (!arguments.length) return tickLabelStyle; if (tickLabelStyle !== x) { tickLabelStyle = x; } return axis; }; axis.titleProperties = function(x) { if (!arguments.length) return titleStyle; if (titleStyle !== x) { titleStyle = x; } return axis; }; axis.domainProperties = function(x) { if (!arguments.length) return domainStyle; if (domainStyle !== x) { domainStyle = x; } return axis; }; axis.reset = function() { reset(); return axis; }; return axis; } var axisOrients = {top: 1, right: 1, bottom: 1, left: 1}; function axisSubdivide(scale, ticks, m) { var subticks = []; if (m && ticks.length > 1) { var extent = axisScaleExtent(scale.domain()), i = -1, n = ticks.length, d = (ticks[1] - ticks[0]) / ++m, j, v; while (++i < n) { for (j = m; --j > 0;) { if ((v = +ticks[i] - j * d) >= extent[0]) { subticks.push(v); } } } for (--i, j = 0; ++j < m && (v = +ticks[i] + j * d) < extent[1];) { subticks.push(v); } } return subticks; } function axisScaleExtent(domain) { var start = domain[0], stop = domain[domain.length - 1]; return start < stop ? [start, stop] : [stop, start]; } function axisScaleRange(scale) { return scale.rangeExtent ? scale.rangeExtent() : axisScaleExtent(scale.range()); } var axisAlign = { bottom: 'center', top: 'center', left: 'right', right: 'left' }; var axisBaseline = { bottom: 'top', top: 'bottom', left: 'middle', right: 'middle' }; function axisLabelExtend(orient, labels, oldScale, newScale, size, pad) { size = Math.max(size, 0) + pad; if (orient === 'left' || orient === 'top') { size *= -1; } if (orient === 'top' || orient === 'bottom') { dl.extend(labels.properties.enter, { x: oldScale, y: {value: size}, }); dl.extend(labels.properties.update, { x: newScale, y: {value: size}, align: {value: 'center'}, baseline: {value: axisBaseline[orient]} }); } else { dl.extend(labels.properties.enter, { x: {value: size}, y: oldScale, }); dl.extend(labels.properties.update, { x: {value: size}, y: newScale, align: {value: axisAlign[orient]}, baseline: {value: 'middle'} }); } } function axisTicksExtend(orient, ticks, oldScale, newScale, size) { var sign = (orient === 'left' || orient === 'top') ? -1 : 1; if (size === Infinity) { size = (orient === 'top' || orient === 'bottom') ? {field: {group: 'height', level: 2}, mult: -sign} : {field: {group: 'width', level: 2}, mult: -sign}; } else { size = {value: sign * size}; } if (orient === 'top' || orient === 'bottom') { dl.extend(ticks.properties.enter, { x: oldScale, y: {value: 0}, y2: size }); dl.extend(ticks.properties.update, { x: newScale, y: {value: 0}, y2: size }); dl.extend(ticks.properties.exit, { x: newScale, }); } else { dl.extend(ticks.properties.enter, { x: {value: 0}, x2: size, y: oldScale }); dl.extend(ticks.properties.update, { x: {value: 0}, x2: size, y: newScale }); dl.extend(ticks.properties.exit, { y: newScale, }); } } function axisTitleExtend(orient, title, range, offset) { var mid = ~~((range[0] + range[1]) / 2), sign = (orient === 'top' || orient === 'left') ? -1 : 1; if (orient === 'bottom' || orient === 'top') { dl.extend(title.properties.update, { x: {value: mid}, y: {value: sign*offset}, angle: {value: 0} }); } else { dl.extend(title.properties.update, { x: {value: sign*offset}, y: {value: mid}, angle: {value: orient === 'left' ? -90 : 90} }); } } function axisDomainExtend(orient, domain, range, size) { var path; if (orient === 'top' || orient === 'left') { size = -1 * size; } if (orient === 'bottom' || orient === 'top') { path = 'M' + range[0] + ',' + size + 'V0H' + range[1] + 'V' + size; } else { path = 'M' + size + ',' + range[0] + 'H0V' + range[1] + 'H' + size; } domain.properties.update.path = {value: path}; } function axisUpdate(item, group, trans) { var o = trans ? {} : item, offset = item.mark.def.offset, orient = item.mark.def.orient, width = group.width, height = group.height; // TODO fallback to global w,h? if (dl.isArray(offset)) { var ofx = offset[0], ofy = offset[1]; switch (orient) { case 'left': { Tuple.set(o, 'x', -ofx); Tuple.set(o, 'y', ofy); break; } case 'right': { Tuple.set(o, 'x', width + ofx); Tuple.set(o, 'y', ofy); break; } case 'bottom': { Tuple.set(o, 'x', ofx); Tuple.set(o, 'y', height + ofy); break; } case 'top': { Tuple.set(o, 'x', ofx); Tuple.set(o, 'y', -ofy); break; } default: { Tuple.set(o, 'x', ofx); Tuple.set(o, 'y', ofy); } } } else { if (dl.isObject(offset)) { offset = -group.scale(offset.scale)(offset.value); } switch (orient) { case 'left': { Tuple.set(o, 'x', -offset); Tuple.set(o, 'y', 0); break; } case 'right': { Tuple.set(o, 'x', width + offset); Tuple.set(o, 'y', 0); break; } case 'bottom': { Tuple.set(o, 'x', 0); Tuple.set(o, 'y', height + offset); break; } case 'top': { Tuple.set(o, 'x', 0); Tuple.set(o, 'y', -offset); break; } default: { Tuple.set(o, 'x', 0); Tuple.set(o, 'y', 0); } } } if (trans) trans.interpolate(item, o); return true; } function axisTicks(config) { return { type: 'rule', interactive: false, key: 'data', properties: { enter: { stroke: {value: config.axis.tickColor}, strokeWidth: {value: config.axis.tickWidth}, opacity: {value: 1e-6} }, exit: { opacity: {value: 1e-6} }, update: { opacity: {value: 1} } } }; } function axisTickLabels(config) { return { type: 'text', interactive: true, key: 'data', properties: { enter: { fill: {value: config.axis.tickLabelColor}, font: {value: config.axis.tickLabelFont}, fontSize: {value: config.axis.tickLabelFontSize}, opacity: {value: 1e-6}, text: {field: 'label'} }, exit: { opacity: {value: 1e-6} }, update: { opacity: {value: 1} } } }; } function axisTitle(config) { return { type: 'text', interactive: true, properties: { enter: { font: {value: config.axis.titleFont}, fontSize: {value: config.axis.titleFontSize}, fontWeight: {value: config.axis.titleFontWeight}, fill: {value: config.axis.titleColor}, align: {value: 'center'}, baseline: {value: 'middle'}, text: {field: 'data'} }, update: {} } }; } function axisDomain(config) { return { type: 'path', interactive: false, properties: { enter: { x: {value: 0.5}, y: {value: 0.5}, stroke: {value: config.axis.axisColor}, strokeWidth: {value: config.axis.axisWidth} }, update: {} } }; } module.exports = axs; },{"../parse/mark":97,"datalib":24,"vega-dataflow":39}],114:[function(require,module,exports){ (function (global){ var d3 = (typeof window !== "undefined" ? window['d3'] : typeof global !== "undefined" ? global['d3'] : null), dl = require('datalib'), Gradient = require('vega-scenegraph').Gradient, parseProperties = require('../parse/properties'), parseMark = require('../parse/mark'); function lgnd(model) { var size = null, shape = null, fill = null, stroke = null, spacing = null, values = null, format = null, formatString = null, config = model.config(), title, orient = 'right', offset = config.legend.offset, padding = config.legend.padding, tickArguments = [5], legendStyle = {}, symbolStyle = {}, gradientStyle = {}, titleStyle = {}, labelStyle = {}, m = { // Legend marks as references for updates titles: {}, symbols: {}, labels: {}, gradient: {} }; var legend = {}, legendDef = {}; function reset() { legendDef.type = null; } function ingest(d, i) { return {data: d, index: i}; } legend.def = function() { var scale = size || shape || fill || stroke; format = !formatString ? null : ((scale.type === 'time') ? dl.format.time(formatString) : dl.format.number(formatString)); if (!legendDef.type) { legendDef = (scale===fill || scale===stroke) && !discrete(scale.type) ? quantDef(scale) : ordinalDef(scale); } legendDef.orient = orient; legendDef.offset = offset; legendDef.padding = padding; return legendDef; }; function discrete(type) { return type==='ordinal' || type==='quantize' || type==='quantile' || type==='threshold'; } function ordinalDef(scale) { var def = o_legend_def(size, shape, fill, stroke); // generate data var data = (values == null ? (scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain()) : values).map(ingest); var fmt = format==null ? (scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments) : String) : format; // determine spacing between legend entries var fs, range, offset, pad=5, domain = d3.range(data.length); if (size) { range = data.map(function(x) { return Math.sqrt(size(x.data)); }); offset = d3.max(range); range = range.reduce(function(a,b,i,z) { if (i > 0) a[i] = a[i-1] + z[i-1]/2 + pad; return (a[i] += b/2, a); }, [0]).map(Math.round); } else { offset = Math.round(Math.sqrt(config.legend.symbolSize)); range = spacing || (fs = labelStyle.fontSize) && (fs.value + pad) || (config.legend.labelFontSize + pad); range = domain.map(function(d,i) { return Math.round(offset/2 + i*range); }); } // account for padding and title size var sz = padding, ts; if (title) { ts = titleStyle.fontSize; sz += 5 + ((ts && ts.value) || config.legend.titleFontSize); } for (var i=0, n=range.length; i<n; ++i) range[i] += sz; // build scale for label layout var scaleSpec = { name: 'legend', type: 'ordinal', points: true, domain: domain, range: range }; // update legend def var tdata = (title ? [title] : []).map(ingest); data.forEach(function(d) { d.label = fmt(d.data); d.offset = offset; }); def.scales = [ scaleSpec ]; def.marks[0].from = function() { return tdata; }; def.marks[1].from = function() { return data; }; def.marks[2].from = def.marks[1].from; return def; } function o_legend_def(size, shape, fill, stroke) { // setup legend marks var titles = dl.extend(m.titles, vg_legendTitle(config)), symbols = dl.extend(m.symbols, vg_legendSymbols(config)), labels = dl.extend(m.labels, vg_vLegendLabels(config)); // extend legend marks vg_legendSymbolExtend(symbols, size, shape, fill, stroke); // add / override custom style properties dl.extend(titles.properties.update, titleStyle); dl.extend(symbols.properties.update, symbolStyle); dl.extend(labels.properties.update, labelStyle); // padding from legend border titles.properties.enter.x.value += padding; titles.properties.enter.y.value += padding; labels.properties.enter.x.offset += padding + 1; symbols.properties.enter.x.offset = padding + 1; labels.properties.update.x.offset += padding + 1; symbols.properties.update.x.offset = padding + 1; dl.extend(legendDef, { type: 'group', interactive: false, properties: { enter: parseProperties(model, 'group', legendStyle), vg_legendPosition: { encode: vg_legendPosition, signals: [], scales:[], data: [], fields: [] } } }); legendDef.marks = [titles, symbols, labels].map(function(m) { return parseMark(model, m); }); return legendDef; } function quantDef(scale) { var def = q_legend_def(scale), dom = scale.domain(), data = (values == null ? (scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain()) : values).map(ingest), width = (gradientStyle.width && gradientStyle.width.value) || config.legend.gradientWidth, fmt = format==null ? (scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments) : String) : format; // build scale for label layout var layoutSpec = { name: 'legend', type: scale.type, round: true, zero: false, domain: [dom[0], dom[dom.length-1]], range: [padding, width+padding] }; if (scale.type==='pow') layoutSpec.exponent = scale.exponent(); // update legend def var tdata = (title ? [title] : []).map(ingest); data.forEach(function(d,i) { d.label = fmt(d.data); d.align = i==(data.length-1) ? 'right' : i===0 ? 'left' : 'center'; }); def.scales = [ layoutSpec ]; def.marks[0].from = function() { return tdata; }; def.marks[1].from = function() { return [1]; }; def.marks[2].from = function() { return data; }; return def; } function q_legend_def(scale) { // setup legend marks var titles = dl.extend(m.titles, vg_legendTitle(config)), gradient = dl.extend(m.gradient, vg_legendGradient(config)), labels = dl.extend(m.labels, vg_hLegendLabels(config)), grad = new Gradient(); // setup color gradient var dom = scale.domain(), min = dom[0], max = dom[dom.length-1], f = scale.copy().domain([min, max]).range([0,1]); var stops = (scale.type !== 'linear' && scale.ticks) ? scale.ticks.call(scale, 15) : dom; if (min !== stops[0]) stops.unshift(min); if (max !== stops[stops.length-1]) stops.push(max); for (var i=0, n=stops.length; i<n; ++i) { grad.stop(f(stops[i]), scale(stops[i])); } gradient.properties.enter.fill = {value: grad}; // add / override custom style properties dl.extend(titles.properties.update, titleStyle); dl.extend(gradient.properties.update, gradientStyle); dl.extend(labels.properties.update, labelStyle); // account for gradient size var gp = gradient.properties, gh = gradientStyle.height, hh = (gh && gh.value) || gp.enter.height.value; labels.properties.enter.y.value = hh; labels.properties.update.y.value = hh; // account for title size as needed if (title) { var tp = titles.properties, fs = titleStyle.fontSize, sz = 4 + ((fs && fs.value) || tp.enter.fontSize.value); gradient.properties.enter.y.value += sz; labels.properties.enter.y.value += sz; gradient.properties.update.y.value += sz; labels.properties.update.y.value += sz; } // padding from legend border titles.properties.enter.x.value += padding; titles.properties.enter.y.value += padding; gradient.properties.enter.x.value += padding; gradient.properties.enter.y.value += padding; labels.properties.enter.y.value += padding; gradient.properties.update.x.value += padding; gradient.properties.update.y.value += padding; labels.properties.update.y.value += padding; dl.extend(legendDef, { type: 'group', interactive: false, properties: { enter: parseProperties(model, 'group', legendStyle), vg_legendPosition: { encode: vg_legendPosition, signals: [], scales: [], data: [], fields: [] } } }); legendDef.marks = [titles, gradient, labels].map(function(m) { return parseMark(model, m); }); return legendDef; } legend.size = function(x) { if (!arguments.length) return size; if (size !== x) { size = x; reset(); } return legend; }; legend.shape = function(x) { if (!arguments.length) return shape; if (shape !== x) { shape = x; reset(); } return legend; }; legend.fill = function(x) { if (!arguments.length) return fill; if (fill !== x) { fill = x; reset(); } return legend; }; legend.stroke = function(x) { if (!arguments.length) return stroke; if (stroke !== x) { stroke = x; reset(); } return legend; }; legend.title = function(x) { if (!arguments.length) return title; if (title !== x) { title = x; reset(); } return legend; }; legend.format = function(x) { if (!arguments.length) return formatString; if (formatString !== x) { formatString = x; reset(); } return legend; }; legend.spacing = function(x) { if (!arguments.length) return spacing; if (spacing !== +x) { spacing = +x; reset(); } return legend; }; legend.orient = function(x) { if (!arguments.length) return orient; orient = x in vg_legendOrients ? x + '' : config.legend.orient; return legend; }; legend.offset = function(x) { if (!arguments.length) return offset; offset = +x; return legend; }; legend.values = function(x) { if (!arguments.length) return values; values = x; return legend; }; legend.legendProperties = function(x) { if (!arguments.length) return legendStyle; legendStyle = x; return legend; }; legend.symbolProperties = function(x) { if (!arguments.length) return symbolStyle; symbolStyle = x; return legend; }; legend.gradientProperties = function(x) { if (!arguments.length) return gradientStyle; gradientStyle = x; return legend; }; legend.labelProperties = function(x) { if (!arguments.length) return labelStyle; labelStyle = x; return legend; }; legend.titleProperties = function(x) { if (!arguments.length) return titleStyle; titleStyle = x; return legend; }; legend.reset = function() { reset(); return legend; }; return legend; } var vg_legendOrients = {right: 1, left: 1}; function vg_legendPosition(item, group, trans, db, signals, predicates) { var o = trans ? {} : item, gx, offset = item.mark.def.offset, orient = item.mark.def.orient, pad = item.mark.def.padding * 2, lw = ~~item.bounds.width() + (item.width ? 0 : pad), lh = ~~item.bounds.height() + (item.height ? 0 : pad), pos = group._legendPositions || (group._legendPositions = {right: 0.5, left: 0.5}); o.x = 0.5; o.width = lw; o.y = pos[orient]; pos[orient] += (o.height = lh); // HACK: use to estimate group bounds during animated transition if (!trans && group.bounds) { group.bounds.delta = group.bounds.x2 - group.width; } switch (orient) { case 'left': { gx = group.bounds ? group.bounds.x1 : 0; o.x += gx - offset - lw; break; } case 'right': { gx = group.width + (group.bounds && trans ? group.bounds.delta : 0); o.x += gx + offset; break; } } if (trans) trans.interpolate(item, o); var enc = item.mark.def.properties.enter.encode; enc.call(enc, item, group, trans, db, signals, predicates); return true; } function vg_legendSymbolExtend(mark, size, shape, fill, stroke) { var e = mark.properties.enter, u = mark.properties.update; if (size) e.size = u.size = {scale: size.scaleName, field: 'data'}; if (shape) e.shape = u.shape = {scale: shape.scaleName, field: 'data'}; if (fill) e.fill = u.fill = {scale: fill.scaleName, field: 'data'}; if (stroke) e.stroke = u.stroke = {scale: stroke.scaleName, field: 'data'}; } function vg_legendTitle(config) { var cfg = config.legend; return { type: 'text', interactive: false, key: 'data', properties: { enter: { x: {value: 0}, y: {value: 0}, fill: {value: cfg.titleColor}, font: {value: cfg.titleFont}, fontSize: {value: cfg.titleFontSize}, fontWeight: {value: cfg.titleFontWeight}, baseline: {value: 'top'}, text: {field: 'data'}, opacity: {value: 1e-6} }, exit: { opacity: {value: 1e-6} }, update: { opacity: {value: 1} } } }; } function vg_legendSymbols(config) { var cfg = config.legend; return { type: 'symbol', interactive: false, key: 'data', properties: { enter: { x: {field: 'offset', mult: 0.5}, y: {scale: 'legend', field: 'index'}, shape: {value: cfg.symbolShape}, size: {value: cfg.symbolSize}, stroke: {value: cfg.symbolColor}, strokeWidth: {value: cfg.symbolStrokeWidth}, opacity: {value: 1e-6} }, exit: { opacity: {value: 1e-6} }, update: { x: {field: 'offset', mult: 0.5}, y: {scale: 'legend', field: 'index'}, opacity: {value: 1} } } }; } function vg_vLegendLabels(config) { var cfg = config.legend; return { type: 'text', interactive: false, key: 'data', properties: { enter: { x: {field: 'offset', offset: 5}, y: {scale: 'legend', field: 'index'}, fill: {value: cfg.labelColor}, font: {value: cfg.labelFont}, fontSize: {value: cfg.labelFontSize}, align: {value: cfg.labelAlign}, baseline: {value: cfg.labelBaseline}, text: {field: 'label'}, opacity: {value: 1e-6} }, exit: { opacity: {value: 1e-6} }, update: { opacity: {value: 1}, x: {field: 'offset', offset: 5}, y: {scale: 'legend', field: 'index'}, } } }; } function vg_legendGradient(config) { var cfg = config.legend; return { type: 'rect', interactive: false, properties: { enter: { x: {value: 0}, y: {value: 0}, width: {value: cfg.gradientWidth}, height: {value: cfg.gradientHeight}, stroke: {value: cfg.gradientStrokeColor}, strokeWidth: {value: cfg.gradientStrokeWidth}, opacity: {value: 1e-6} }, exit: { opacity: {value: 1e-6} }, update: { x: {value: 0}, y: {value: 0}, opacity: {value: 1} } } }; } function vg_hLegendLabels(config) { var cfg = config.legend; return { type: 'text', interactive: false, key: 'data', properties: { enter: { x: {scale: 'legend', field: 'data'}, y: {value: 20}, dy: {value: 2}, fill: {value: cfg.labelColor}, font: {value: cfg.labelFont}, fontSize: {value: cfg.labelFontSize}, align: {field: 'align'}, baseline: {value: 'top'}, text: {field: 'label'}, opacity: {value: 1e-6} }, exit: { opacity: {value: 1e-6} }, update: { x: {scale: 'legend', field: 'data'}, y: {value: 20}, opacity: {value: 1} } } }; } module.exports = lgnd; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../parse/mark":97,"../parse/properties":102,"datalib":24,"vega-scenegraph":46}],115:[function(require,module,exports){ module.exports = function visit(node, func) { var i, n, s, m, items; if (func(node)) return true; var sets = ['items', 'axisItems', 'legendItems']; for (s=0, m=sets.length; s<m; ++s) { if ((items = node[sets[s]])) { for (i=0, n=items.length; i<n; ++i) { if (visit(items[i], func)) return true; } } } }; },{}],116:[function(require,module,exports){ var dl = require('datalib'), df = require('vega-dataflow'), log = require('vega-logging'), ChangeSet = df.ChangeSet, Tuple = df.Tuple, Deps = df.Dependencies, Transform = require('./Transform'), Facetor = require('./Facetor'); function Aggregate(graph) { Transform.prototype.init.call(this, graph); Transform.addParameters(this, { groupby: {type: 'array<field>'}, summarize: { type: 'custom', set: function(summarize) { var signalDeps = {}, tx = this._transform, i, len, f, fields, name, ops; if (!dl.isArray(fields = summarize)) { // Object syntax from dl fields = []; for (name in summarize) { ops = dl.array(summarize[name]); fields.push({field: name, ops: ops}); } } function sg(x) { if (x.signal) signalDeps[x.signal] = 1; } for (i=0, len=fields.length; i<len; ++i) { f = fields[i]; if (f.field.signal) { signalDeps[f.field.signal] = 1; } dl.array(f.ops).forEach(sg); dl.array(f.as).forEach(sg); } tx._fields = fields; tx._aggr = null; tx.dependency(Deps.SIGNALS, dl.keys(signalDeps)); return tx; } } }); this._aggr = null; // dl.Aggregator this._input = null; // Used by Facetor._on_keep. this._args = null; // To cull re-computation. this._fields = []; this._out = []; this._type = TYPES.TUPLE; this._acc = {groupby: dl.true, value: dl.true}; return this.router(true); } var prototype = (Aggregate.prototype = Object.create(Transform.prototype)); prototype.constructor = Aggregate; var TYPES = Aggregate.TYPES = { VALUE: 1, TUPLE: 2, MULTI: 3 }; Aggregate.VALID_OPS = [ 'values', 'count', 'valid', 'missing', 'distinct', 'sum', 'mean', 'average', 'variance', 'variancep', 'stdev', 'stdevp', 'median', 'q1', 'q3', 'modeskew', 'min', 'max', 'argmin', 'argmax' ]; prototype.type = function(type) { return (this._type = type, this); }; prototype.accessors = function(groupby, value) { var acc = this._acc; acc.groupby = dl.$(groupby) || dl.true; acc.value = dl.$(value) || dl.true; }; prototype.aggr = function() { if (this._aggr) return this._aggr; var g = this._graph, hasGetter = false, args = [], groupby = this.param('groupby').field, value = function(x) { return x.signal ? g.signalRef(x.signal) : x; }; // Prepare summarize fields. var fields = this._fields.map(function(f) { var field = { name: value(f.field), as: dl.array(f.as), ops: dl.array(value(f.ops)).map(value), get: f.get }; hasGetter = hasGetter || field.get != null; args.push(field.name); return field; }); // If there is an arbitrary getter, all bets are off. // Otherwise, we can check argument fields to cull re-computation. groupby.forEach(function(g) { if (g.get) hasGetter = true; args.push(g.name || g); }); this._args = hasGetter || !fields.length ? null : args; if (!fields.length) fields = {'*': 'values'}; // Instatiate our aggregator instance. // Facetor is a special subclass that can facet into data pipelines. var aggr = this._aggr = new Facetor() .groupby(groupby) .stream(true) .summarize(fields); // Collect output fields sets by this aggregate. this._out = getFields(aggr); // If we are processing tuples, key them by '_id'. if (this._type !== TYPES.VALUE) { aggr.key('_id'); } return aggr; }; function getFields(aggr) { // Collect the output fields set by this aggregate. var f = [], i, n, j, m, dims, vals, meas; dims = aggr._dims; for (i=0, n=dims.length; i<n; ++i) { f.push(dims[i].name); } vals = aggr._aggr; for (i=0, n=vals.length; i<n; ++i) { meas = vals[i].measures.fields; for (j=0, m=meas.length; j<m; ++j) { f.push(meas[j]); } } return f; } prototype.transform = function(input, reset) { log.debug(input, ['aggregate']); this._input = input; // Used by Facetor._on_keep. var output = ChangeSet.create(input), aggr = this.aggr(), out = this._out, args = this._args, reeval = true, p = Tuple.prev, add, rem, mod, i; // Upon reset, retract prior tuples and re-initialize. if (reset) { output.rem.push.apply(output.rem, aggr.result()); aggr.clear(); this._aggr = null; aggr = this.aggr(); } // Get update methods according to input type. if (this._type === TYPES.TUPLE) { add = function(x) { aggr._add(x); Tuple.prev_init(x); }; rem = function(x) { aggr._rem(p(x)); }; mod = function(x) { aggr._mod(x, p(x)); }; } else { var gby = this._acc.groupby, val = this._acc.value, get = this._type === TYPES.VALUE ? val : function(x) { return { _id: x._id, groupby: gby(x), value: val(x) }; }; add = function(x) { aggr._add(get(x)); Tuple.prev_init(x); }; rem = function(x) { aggr._rem(get(p(x))); }; mod = function(x) { aggr._mod(get(x), get(p(x))); }; } input.add.forEach(add); if (reset) { // A signal change triggered reflow. Add everything. // No need for rem, we cleared the aggregator. input.mod.forEach(add); } else { input.rem.forEach(rem); // If possible, check argument fields to see if we need to re-process mods. if (args) for (i=0, reeval=false; i<args.length; ++i) { if (input.fields[args[i]]) { reeval = true; break; } } if (reeval) input.mod.forEach(mod); } // Indicate output fields and return aggregate tuples. for (i=0; i<out.length; ++i) { output.fields[out[i]] = 1; } return aggr.changes(output); }; module.exports = Aggregate; },{"./Facetor":122,"./Transform":135,"datalib":24,"vega-dataflow":39,"vega-logging":45}],117:[function(require,module,exports){ var Base = require('./Transform').prototype; function BatchTransform() { // Nearest appropriate collector. // Set by the dataflow Graph during connection. this._collector = null; } var prototype = (BatchTransform.prototype = Object.create(Base)); prototype.constructor = BatchTransform; prototype.init = function(graph) { Base.init.call(this, graph); return this.batch(true); }; prototype.transform = function(input) { return this.batchTransform(input, this._collector.data()); }; prototype.batchTransform = function(/* input, data */) { }; module.exports = BatchTransform; },{"./Transform":135}],118:[function(require,module,exports){ var bins = require('datalib').bins, Tuple = require('vega-dataflow').Tuple, log = require('vega-logging'), Transform = require('./Transform'); function Bin(graph) { Transform.prototype.init.call(this, graph); Transform.addParameters(this, { field: {type: 'field'}, min: {type: 'value'}, max: {type: 'value'}, base: {type: 'value', default: 10}, maxbins: {type: 'value', default: 20}, step: {type: 'value'}, steps: {type: 'value'}, minstep: {type: 'value'}, div: {type: 'array<value>', default: [5, 2]} }); this._output = {bin: 'bin'}; return this.mutates(true); } var prototype = (Bin.prototype = Object.create(Transform.prototype)); prototype.constructor = Bin; prototype.transform = function(input) { log.debug(input, ['binning']); var output = this._output.bin, step = this.param('step'), steps = this.param('steps'), minstep = this.param('minstep'), get = this.param('field').accessor, opt = { min: this.param('min'), max: this.param('max'), base: this.param('base'), maxbins: this.param('maxbins'), div: this.param('div') }; if (step) opt.step = step; if (steps) opt.steps = steps; if (minstep) opt.minstep = minstep; var b = bins(opt); function update(d) { var v = get(d); v = v == null ? null : b.start + b.step * ~~((v - b.start) / b.step); Tuple.set(d, output, v); } input.add.forEach(update); input.mod.forEach(update); input.rem.forEach(update); return input; }; module.exports = Bin; },{"./Transform":135,"datalib":24,"vega-dataflow":39,"vega-logging":45}],119:[function(require,module,exports){ var df = require('vega-dataflow'), Tuple = df.Tuple, log = require('vega-logging'), Transform = require('./Transform'); function CountPattern(graph) { Transform.prototype.init.call(this, graph); Transform.addParameters(this, { field: {type: 'field', default: 'data'}, pattern: {type: 'value', default: '[\\w\']+'}, case: {type: 'value', default: 'lower'}, stopwords: {type: 'value', default: ''} }); this._output = {text: 'text', count: 'count'}; return this.router(true); } var prototype = (CountPattern.prototype = Object.create(Transform.prototype)); prototype.constructor = CountPattern; prototype.transform = function(input, reset) { log.debug(input, ['countpattern']); var get = this.param('field').accessor, pattern = this.param('pattern'), stop = this.param('stopwords'), rem = false; // update parameters if (this._stop !== stop) { this._stop = stop; this._stop_re = new RegExp('^' + stop + '$', 'i'); reset = true; } if (this._pattern !== pattern) { this._pattern = pattern; this._match = new RegExp(this._pattern, 'g'); reset = true; } if (reset) this._counts = {}; function curr(t) { return (Tuple.prev_init(t), get(t)); } function prev(t) { return get(Tuple.prev(t)); } this._add(input.add, curr); if (!reset) this._rem(input.rem, prev); if (reset || (rem = input.fields[get.field])) { if (rem) this._rem(input.mod, prev); this._add(input.mod, curr); } // generate output tuples return this._changeset(input); }; prototype._changeset = function(input) { var counts = this._counts, tuples = this._tuples || (this._tuples = {}), change = df.ChangeSet.create(input), out = this._output, w, t, c; for (w in counts) { t = tuples[w]; c = counts[w] || 0; if (!t && c) { tuples[w] = (t = Tuple.ingest({})); t[out.text] = w; t[out.count] = c; change.add.push(t); } else if (c === 0) { if (t) change.rem.push(t); delete counts[w]; delete tuples[w]; } else if (t[out.count] !== c) { Tuple.set(t, out.count, c); change.mod.push(t); } } return change; }; prototype._tokenize = function(text) { switch (this.param('case')) { case 'upper': text = text.toUpperCase(); break; case 'lower': text = text.toLowerCase(); break; } return text.match(this._match); }; prototype._add = function(tuples, get) { var counts = this._counts, stop = this._stop_re, tok, i, j, t; for (j=0; j<tuples.length; ++j) { tok = this._tokenize(get(tuples[j])); for (i=0; i<tok.length; ++i) { if (!stop.test(t=tok[i])) { counts[t] = 1 + (counts[t] || 0); } } } }; prototype._rem = function(tuples, get) { var counts = this._counts, stop = this._stop_re, tok, i, j, t; for (j=0; j<tuples.length; ++j) { tok = this._tokenize(get(tuples[j])); for (i=0; i<tok.length; ++i) { if (!stop.test(t=tok[i])) { counts[t] -= 1; } } } }; module.exports = CountPattern; },{"./Transform":135,"vega-dataflow":39,"vega-logging":45}],120:[function(require,module,exports){ var df = require('vega-dataflow'), ChangeSet = df.ChangeSet, Tuple = df.Tuple, log = require('vega-logging'), Transform = require('./Transform'), BatchTransform = require('./BatchTransform'); function Cross(graph) { BatchTransform.prototype.init.call(this, graph); Transform.addParameters(this, { with: {type: 'data'}, diagonal: {type: 'value', default: 'true'} }); this._output = {'left': 'a', 'right': 'b'}; this._lastRem = null; // Most recent stamp that rem occured. this._lastWith = null; // Last time we crossed w/withds. this._ids = {}; this._cache = {}; return this.router(true); } var prototype = (Cross.prototype = Object.create(BatchTransform.prototype)); prototype.constructor = Cross; // Each cached incoming tuple also has a stamp to track if we need to do // lazy filtering of removed tuples. function cache(x, t) { var c = this._cache[x._id] = this._cache[x._id] || {c: [], s: this._stamp}; c.c.push(t); } function add(output, left, data, diag, x) { var i = 0, len = data.length, t, y, id; for (; i<len; ++i) { y = data[i]; id = left ? x._id+'_'+y._id : y._id+'_'+x._id; if (this._ids[id]) continue; if (x._id == y._id && !diag) continue; t = Tuple.ingest({}); t[this._output.left] = left ? x : y; t[this._output.right] = left ? y : x; output.add.push(t); cache.call(this, x, t); cache.call(this, y, t); this._ids[id] = 1; } } function mod(output, left, x) { var cross = this, c = this._cache[x._id]; if (this._lastRem > c.s) { // Removed tuples haven't been filtered yet c.c = c.c.filter(function(y) { var t = y[cross._output[left ? 'right' : 'left']]; return cross._cache[t._id] !== null; }); c.s = this._lastRem; } output.mod.push.apply(output.mod, c.c); } function rem(output, x) { output.rem.push.apply(output.rem, this._cache[x._id].c); this._cache[x._id] = null; this._lastRem = this._stamp; } function upFields(input, output) { if (input.add.length || input.rem.length) { output.fields[this._output.left] = 1; output.fields[this._output.right] = 1; } } prototype.batchTransform = function(input, data) { log.debug(input, ['crossing']); var w = this.param('with'), diag = this.param('diagonal'), selfCross = (!w.name), woutput = selfCross ? input : w.source.last(), wdata = selfCross ? data : w.source.values(), output = ChangeSet.create(input), r = rem.bind(this, output); input.rem.forEach(r); input.add.forEach(add.bind(this, output, true, wdata, diag)); if (!selfCross && woutput.stamp > this._lastWith) { woutput.rem.forEach(r); woutput.add.forEach(add.bind(this, output, false, data, diag)); woutput.mod.forEach(mod.bind(this, output, false)); upFields.call(this, woutput, output); this._lastWith = woutput.stamp; } // Mods need to come after all removals have been run. input.mod.forEach(mod.bind(this, output, true)); upFields.call(this, input, output); return output; }; module.exports = Cross; },{"./BatchTransform":117,"./Transform":135,"vega-dataflow":39,"vega-logging":45}],121:[function(require,module,exports){ var Transform = require('./Transform'), Aggregate = require('./Aggregate'); function Facet(graph) { Transform.addParameters(this, { transform: { type: "custom", set: function(pipeline) { return (this._transform._pipeline = pipeline, this._transform); }, get: function() { var parse = require('../parse/transforms'), facet = this._transform; return facet._pipeline.map(function(t) { return parse(facet._graph, t); }); } } }); this._pipeline = []; Aggregate.call(this, graph); } var prototype = (Facet.prototype = Object.create(Aggregate.prototype)); prototype.constructor = Facet; prototype.aggr = function() { return Aggregate.prototype.aggr.call(this).facet(this); }; module.exports = Facet; },{"../parse/transforms":106,"./Aggregate":116,"./Transform":135}],122:[function(require,module,exports){ var dl = require('datalib'), Aggregator = dl.Aggregator, Base = Aggregator.prototype, df = require('vega-dataflow'), Tuple = df.Tuple, log = require('vega-logging'), facetID = 0; function Facetor() { Aggregator.call(this); this._facet = null; } var prototype = (Facetor.prototype = Object.create(Base)); prototype.constructor = Facetor; prototype.facet = function(f) { return arguments.length ? (this._facet = f, this) : this._facet; }; prototype._ingest = function(t) { return Tuple.ingest(t, null); }; prototype._assign = Tuple.set; function disconnect_cell(facet) { log.debug({}, ['disconnecting cell', this.tuple._id]); var pipeline = this.ds.pipeline(); facet.removeListener(pipeline[0]); facet._graph.disconnect(pipeline); } prototype._newcell = function(x, key) { var cell = Base._newcell.call(this, x, key), facet = this._facet; if (facet) { var graph = facet._graph, tuple = cell.tuple, pipeline = facet.param('transform'); cell.ds = graph.data(tuple._facetID, pipeline, tuple); cell.disconnect = disconnect_cell; facet.addListener(pipeline[0]); } return cell; }; prototype._newtuple = function(x, key) { var t = Base._newtuple.call(this, x); if (this._facet) { Tuple.set(t, 'key', key); Tuple.set(t, '_facetID', 'vg_'+ (++facetID)); } return t; }; prototype.clear = function() { if (this._facet) { for (var k in this._cells) { this._cells[k].disconnect(this._facet); } } return Base.clear.call(this); }; prototype._on_add = function(x, cell) { if (this._facet) cell.ds._input.add.push(x); }; prototype._on_rem = function(x, cell) { if (this._facet) cell.ds._input.rem.push(x); }; prototype._on_mod = function(x, prev, cell0, cell1) { if (this._facet) { // Propagate tuples if (cell0 === cell1) { cell0.ds._input.mod.push(x); } else { cell0.ds._input.rem.push(x); cell1.ds._input.add.push(x); } } }; prototype._on_drop = function(cell) { if (this._facet) cell.disconnect(this._facet); }; prototype._on_keep = function(cell) { // propagate sort, signals, fields, etc. if (this._facet) df.ChangeSet.copy(this._input, cell.ds._input); }; module.exports = Facetor; },{"datalib":24,"vega-dataflow":39,"vega-logging":45}],123:[function(require,module,exports){ var df = require('vega-dataflow'), Deps = df.Dependencies, log = require('vega-logging'), Transform = require('./Transform'); function Filter(graph) { Transform.prototype.init.call(this, graph); Transform.addParameters(this, {test: {type: 'expr'}}); this._skip = {}; return this.router(true); } var prototype = (Filter.prototype = Object.create(Transform.prototype)); prototype.constructor = Filter; prototype.transform = function(input) { log.debug(input, ['filtering']); var output = df.ChangeSet.create(input), graph = this._graph, skip = this._skip, test = this.param('test'), signals = graph.signalValues(this.dependency(Deps.SIGNALS)); input.rem.forEach(function(x) { if (skip[x._id] !== 1) output.rem.push(x); else skip[x._id] = 0; }); input.add.forEach(function(x) { if (test(x, null, signals)) output.add.push(x); else skip[x._id] = 1; }); input.mod.forEach(function(x) { var b = test(x, null, signals), s = (skip[x._id] === 1); if (b && s) { skip[x._id] = 0; output.add.push(x); } else if (b && !s) { output.mod.push(x); } else if (!b && s) { // do nothing, keep skip true } else { // !b && !s output.rem.push(x); skip[x._id] = 1; } }); return output; }; module.exports = Filter; },{"./Transform":135,"vega-dataflow":39,"vega-logging":45}],124:[function(require,module,exports){ var df = require('vega-dataflow'), Tuple = df.Tuple, log = require('vega-logging'), Transform = require('./Transform'); function Fold(graph) { Transform.prototype.init.call(this, graph); Transform.addParameters(this, { fields: {type: 'array<field>'} }); this._output = {key: 'key', value: 'value'}; this._cache = {}; return this.router(true); } var prototype = (Fold.prototype = Object.create(Transform.prototype)); prototype.constructor = Fold; prototype._reset = function(input, output) { for (var id in this._cache) { output.rem.push.apply(output.rem, this._cache[id]); } this._cache = {}; }; prototype._tuple = function(x, i, len) { var list = this._cache[x._id] || (this._cache[x._id] = Array(len)); return list[i] ? Tuple.rederive(x, list[i]) : (list[i] = Tuple.derive(x)); }; prototype._fn = function(data, on, out) { var i, j, n, m, d, t; for (i=0, n=data.length; i<n; ++i) { d = data[i]; for (j=0, m=on.field.length; j<m; ++j) { t = this._tuple(d, j, m); Tuple.set(t, this._output.key, on.field[j]); Tuple.set(t, this._output.value, on.accessor[j](d)); out.push(t); } } }; prototype.transform = function(input, reset) { log.debug(input, ['folding']); var fold = this, on = this.param('fields'), output = df.ChangeSet.create(input); if (reset) this._reset(input, output); this._fn(input.add, on, output.add); this._fn(input.mod, on, reset ? output.add : output.mod); input.rem.forEach(function(x) { output.rem.push.apply(output.rem, fold._cache[x._id]); fold._cache[x._id] = null; }); // If we're only propagating values, don't mark key/value as updated. if (input.add.length || input.rem.length || on.field.some(function(f) { return !!input.fields[f]; })) { output.fields[this._output.key] = 1; output.fields[this._output.value] = 1; } return output; }; module.exports = Fold; },{"./Transform":135,"vega-dataflow":39,"vega-logging":45}],125:[function(require,module,exports){ (function (global){ var d3 = (typeof window !== "undefined" ? window['d3'] : typeof global !== "undefined" ? global['d3'] : null), df = require('vega-dataflow'), Tuple = df.Tuple, ChangeSet = df.ChangeSet, log = require('vega-logging'), Transform = require('./Transform'); function Force(graph) { Transform.prototype.init.call(this, graph); this._prev = null; this._interactive = false; this._setup = true; this._nodes = []; this._links = []; this._layout = d3.layout.force(); Transform.addParameters(this, { size: {type: 'array<value>', default: [500, 500]}, bound: {type: 'value', default: true}, links: {type: 'data'}, // TODO: for now force these to be value params only (pun-intended) // Can update to include fields after Parameter refactoring. linkStrength: {type: 'value', default: 1}, linkDistance: {type: 'value', default: 20}, charge: {type: 'value', default: -30}, chargeDistance: {type: 'value', default: Infinity}, friction: {type: 'value', default: 0.9}, theta: {type: 'value', default: 0.8}, gravity: {type: 'value', default: 0.1}, alpha: {type: 'value', default: 0.1}, iterations: {type: 'value', default: 500}, interactive: {type: 'value', default: this._interactive}, active: {type: 'value', default: this._prev}, fixed: {type: 'data'} }); this._output = { 'x': 'layout_x', 'y': 'layout_y' }; return this.mutates(true); } var prototype = (Force.prototype = Object.create(Transform.prototype)); prototype.constructor = Force; prototype.transform = function(nodeInput, reset) { log.debug(nodeInput, ['force']); reset = reset - (nodeInput.signals.active ? 1 : 0); // get variables var interactive = this.param('interactive'), linkSource = this.param('links').source, linkInput = linkSource.last(), active = this.param('active'), output = this._output, layout = this._layout, nodes = this._nodes, links = this._links; // configure nodes, links and layout if (linkInput.stamp < nodeInput.stamp) linkInput = null; this.configure(nodeInput, linkInput, interactive, reset); // run batch layout if (!interactive) { var iterations = this.param('iterations'); for (var i=0; i<iterations; ++i) layout.tick(); layout.stop(); } // update node positions this.update(active); // re-up alpha on parameter change if (reset || active !== this._prev && active && active.update) { layout.alpha(this.param('alpha')); // re-start layout } // update active node status, if (active !== this._prev) { this._prev = active; } // process removed nodes or edges if (nodeInput.rem.length) { layout.nodes(this._nodes = Tuple.idFilter(nodes, nodeInput.rem)); } if (linkInput && linkInput.rem.length) { layout.links(this._links = Tuple.idFilter(links, linkInput.rem)); } // return changeset nodeInput.fields[output.x] = 1; nodeInput.fields[output.y] = 1; return nodeInput; }; prototype.configure = function(nodeInput, linkInput, interactive, reset) { // check if we need to run configuration var layout = this._layout, update = this._setup || nodeInput.add.length || linkInput && linkInput.add.length || interactive !== this._interactive || this.param('charge') !== layout.charge() || this.param('linkStrength') !== layout.linkStrength() || this.param('linkDistance') !== layout.linkDistance(); if (update || reset) { // a parameter changed, so update tick-only parameters layout .size(this.param('size')) .chargeDistance(this.param('chargeDistance')) .theta(this.param('theta')) .gravity(this.param('gravity')) .friction(this.param('friction')); } if (!update) return; // if no more updates needed, return now this._setup = false; this._interactive = interactive; var force = this, graph = this._graph, nodes = this._nodes, links = this._links, a, i; // process added nodes for (a=nodeInput.add, i=0; i<a.length; ++i) { nodes.push({tuple: a[i]}); } // process added edges if (linkInput) for (a=linkInput.add, i=0; i<a.length; ++i) { // TODO add configurable source/target accessors // TODO support lookup by node id // TODO process 'mod' of edge source or target? links.push({ tuple: a[i], source: nodes[a[i].source], target: nodes[a[i].target] }); } // setup handler for force layout tick events var tickHandler = !interactive ? null : function() { // re-schedule the transform, force reflow graph.propagate(ChangeSet.create(null, true), force); }; // configure the rest of the layout layout .linkStrength(this.param('linkStrength')) .linkDistance(this.param('linkDistance')) .charge(this.param('charge')) .nodes(nodes) .links(links) .on('tick', tickHandler) .start().alpha(this.param('alpha')); }; prototype.update = function(active) { var output = this._output, bound = this.param('bound'), fixed = this.param('fixed'), size = this.param('size'), nodes = this._nodes, lut = {}, id, i, n, t, x, y; if (fixed && fixed.source) { // TODO: could cache and update as needed? fixed = fixed.source.values(); for (i=0, n=fixed.length; i<n; ++i) { lut[fixed[i].id] = 1; } } for (i=0; i<nodes.length; ++i) { n = nodes[i]; t = n.tuple; id = t._id; if (active && active.id === id) { n.fixed = 1; if (active.update) { n.x = n.px = active.x; n.y = n.py = active.y; } } else { n.fixed = lut[id] || 0; } x = bound ? Math.max(0, Math.min(n.x, size[0])) : n.x; y = bound ? Math.max(0, Math.min(n.y, size[1])) : n.y; Tuple.set(t, output.x, x); Tuple.set(t, output.y, y); } }; module.exports = Force; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./Transform":135,"vega-dataflow":39,"vega-logging":45}],126:[function(require,module,exports){ var df = require('vega-dataflow'), Tuple = df.Tuple, Deps = df.Dependencies, log = require('vega-logging'), Transform = require('./Transform'); function Formula(graph) { Transform.prototype.init.call(this, graph); Transform.addParameters(this, { field: {type: 'value'}, expr: {type: 'expr'} }); return this.mutates(true); } var prototype = (Formula.prototype = Object.create(Transform.prototype)); prototype.constructor = Formula; prototype.transform = function(input) { log.debug(input, ['formulating']); var g = this._graph, field = this.param('field'), expr = this.param('expr'), signals = g.signalValues(this.dependency(Deps.SIGNALS)); function set(x) { Tuple.set(x, field, expr(x, null, signals)); } input.add.forEach(set); if (this.reevaluate(input)) { input.mod.forEach(set); } input.fields[field] = 1; return input; }; module.exports = Formula; },{"./Transform":135,"vega-dataflow":39,"vega-logging":45}],127:[function(require,module,exports){ (function (global){ var d3 = (typeof window !== "undefined" ? window['d3'] : typeof global !== "undefined" ? global['d3'] : null), dl = require('datalib'), Tuple = require('vega-dataflow').Tuple, log = require('vega-logging'), Transform = require('./Transform'); function Geo(graph) { Transform.prototype.init.call(this, graph); Transform.addParameters(this, Geo.Parameters); Transform.addParameters(this, { lon: {type: 'field'}, lat: {type: 'field'} }); this._output = { 'x': 'layout_x', 'y': 'layout_y' }; return this.mutates(true); } Geo.Parameters = { projection: {type: 'value', default: 'mercator'}, center: {type: 'array<value>'}, translate: {type: 'array<value>'}, rotate: {type: 'array<value>'}, scale: {type: 'value'}, precision: {type: 'value'}, clipAngle: {type: 'value'}, clipExtent: {type: 'value'} }; Geo.d3Projection = function() { var p = this.param('projection'), param = Geo.Parameters, proj, name, value; if (p !== this._mode) { this._mode = p; this._projection = d3.geo[p](); } proj = this._projection; for (name in param) { if (name === 'projection' || !proj[name]) continue; value = this.param(name); if (value === undefined || (dl.isArray(value) && value.length === 0)) { continue; } if (value !== proj[name]()) { proj[name](value); } } return proj; }; var prototype = (Geo.prototype = Object.create(Transform.prototype)); prototype.constructor = Geo; prototype.transform = function(input) { log.debug(input, ['geo']); var output = this._output, lon = this.param('lon').accessor, lat = this.param('lat').accessor, proj = Geo.d3Projection.call(this); function set(t) { var ll = [lon(t), lat(t)]; var xy = proj(ll) || [null, null]; Tuple.set(t, output.x, xy[0]); Tuple.set(t, output.y, xy[1]); } input.add.forEach(set); if (this.reevaluate(input)) { input.mod.forEach(set); input.rem.forEach(set); } input.fields[output.x] = 1; input.fields[output.y] = 1; return input; }; module.exports = Geo; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./Transform":135,"datalib":24,"vega-dataflow":39,"vega-logging":45}],128:[function(require,module,exports){ (function (global){ var d3 = (typeof window !== "undefined" ? window['d3'] : typeof global !== "undefined" ? global['d3'] : null), dl = require('datalib'), Tuple = require('vega-dataflow').Tuple, log = require('vega-logging'), Geo = require('./Geo'), Transform = require('./Transform'); function GeoPath(graph) { Transform.prototype.init.call(this, graph); Transform.addParameters(this, Geo.Parameters); Transform.addParameters(this, { field: {type: 'field', default: null}, }); this._output = { 'path': 'layout_path' }; return this.mutates(true); } var prototype = (GeoPath.prototype = Object.create(Transform.prototype)); prototype.constructor = GeoPath; prototype.transform = function(input) { log.debug(input, ['geopath']); var output = this._output, geojson = this.param('field').accessor || dl.identity, proj = Geo.d3Projection.call(this), path = d3.geo.path().projection(proj); function set(t) { Tuple.set(t, output.path, path(geojson(t))); } input.add.forEach(set); if (this.reevaluate(input)) { input.mod.forEach(set); input.rem.forEach(set); } input.fields[output.path] = 1; return input; }; module.exports = GeoPath; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./Geo":127,"./Transform":135,"datalib":24,"vega-dataflow":39,"vega-logging":45}],129:[function(require,module,exports){ var Tuple = require('vega-dataflow').Tuple, log = require('vega-logging'), Transform = require('./Transform'); function LinkPath(graph) { Transform.prototype.init.call(this, graph); Transform.addParameters(this, { sourceX: {type: 'field', default: '_source.layout_x'}, sourceY: {type: 'field', default: '_source.layout_y'}, targetX: {type: 'field', default: '_target.layout_x'}, targetY: {type: 'field', default: '_target.layout_y'}, tension: {type: 'value', default: 0.2}, shape: {type: 'value', default: 'line'} }); this._output = {'path': 'layout_path'}; return this.mutates(true); } var prototype = (LinkPath.prototype = Object.create(Transform.prototype)); prototype.constructor = LinkPath; function line(sx, sy, tx, ty) { return 'M' + sx + ',' + sy + 'L' + tx + ',' + ty; } function curve(sx, sy, tx, ty, tension) { var dx = tx - sx, dy = ty - sy, ix = tension * (dx + dy), iy = tension * (dy - dx); return 'M' + sx + ',' + sy + 'C' + (sx+ix) + ',' + (sy+iy) + ' ' + (tx+iy) + ',' + (ty-ix) + ' ' + tx + ',' + ty; } function diagonalX(sx, sy, tx, ty) { var m = (sx + tx) / 2; return 'M' + sx + ',' + sy + 'C' + m + ',' + sy + ' ' + m + ',' + ty + ' ' + tx + ',' + ty; } function diagonalY(sx, sy, tx, ty) { var m = (sy + ty) / 2; return 'M' + sx + ',' + sy + 'C' + sx + ',' + m + ' ' + tx + ',' + m + ' ' + tx + ',' + ty; } var shapes = { line: line, curve: curve, diagonal: diagonalX, diagonalX: diagonalX, diagonalY: diagonalY }; prototype.transform = function(input) { log.debug(input, ['linkpath']); var output = this._output, shape = shapes[this.param('shape')] || shapes.line, sourceX = this.param('sourceX').accessor, sourceY = this.param('sourceY').accessor, targetX = this.param('targetX').accessor, targetY = this.param('targetY').accessor, tension = this.param('tension'); function set(t) { var path = shape(sourceX(t), sourceY(t), targetX(t), targetY(t), tension); Tuple.set(t, output.path, path); } input.add.forEach(set); if (this.reevaluate(input)) { input.mod.forEach(set); input.rem.forEach(set); } input.fields[output.path] = 1; return input; }; module.exports = LinkPath; },{"./Transform":135,"vega-dataflow":39,"vega-logging":45}],130:[function(require,module,exports){ var Tuple = require('vega-dataflow').Tuple, log = require('vega-logging'), Transform = require('./Transform'); function Lookup(graph) { Transform.prototype.init.call(this, graph); Transform.addParameters(this, { on: {type: 'data'}, onKey: {type: 'field', default: null}, as: {type: 'array<value>'}, keys: {type: 'array<field>', default: ['data']}, default: {type: 'value'} }); return this.mutates(true); } var prototype = (Lookup.prototype = Object.create(Transform.prototype)); prototype.constructor = Lookup; prototype.transform = function(input, reset) { log.debug(input, ['lookup']); var on = this.param('on'), onLast = on.source.last(), onData = on.source.values(), onKey = this.param('onKey'), onF = onKey.field, keys = this.param('keys'), get = keys.accessor, as = this.param('as'), defaultValue = this.param('default'), lut = this._lut, i, v; // build lookup table on init, withKey modified, or tuple add/rem if (lut == null || this._on !== onF || onF && onLast.fields[onF] || onLast.add.length || onLast.rem.length) { if (onF) { // build hash from withKey field onKey = onKey.accessor; for (lut={}, i=0; i<onData.length; ++i) { lut[onKey(v = onData[i])] = v; } } else { // otherwise, use index-based lookup lut = onData; } this._lut = lut; this._on = onF; reset = true; } function set(t) { for (var i=0; i<get.length; ++i) { var v = lut[get[i](t)] || defaultValue; Tuple.set(t, as[i], v); } } input.add.forEach(set); var run = keys.field.some(function(f) { return input.fields[f]; }); if (run || reset) { input.mod.forEach(set); input.rem.forEach(set); } as.forEach(function(k) { input.fields[k] = 1; }); return input; }; module.exports = Lookup; },{"./Transform":135,"vega-dataflow":39,"vega-logging":45}],131:[function(require,module,exports){ var dl = require('datalib'), Deps = require('vega-dataflow').Dependencies, expr = require('../parse/expr'); var arrayType = /array/i, dataType = /data/i, fieldType = /field/i, exprType = /expr/i, valType = /value/i; function Parameter(name, type, transform) { this._name = name; this._type = type; this._transform = transform; // If parameter is defined w/signals, it must be resolved // on every pulse. this._value = []; this._accessors = []; this._resolution = false; this._signals = {}; } var prototype = Parameter.prototype; function get() { var isArray = arrayType.test(this._type), isData = dataType.test(this._type), isField = fieldType.test(this._type); var val = isArray ? this._value : this._value[0], acc = isArray ? this._accessors : this._accessors[0]; if (!dl.isValid(acc) && valType.test(this._type)) { return val; } else { return isData ? { name: val, source: acc } : isField ? { field: val, accessor: acc } : val; } } prototype.get = function() { var graph = this._transform._graph, isData = dataType.test(this._type), isField = fieldType.test(this._type), s, idx, val; // If we don't require resolution, return the value immediately. if (!this._resolution) return get.call(this); if (isData) { this._accessors = this._value.map(function(v) { return graph.data(v); }); return get.call(this); // TODO: support signal as dataTypes } for (s in this._signals) { idx = this._signals[s]; val = graph.signalRef(s); if (isField) { this._accessors[idx] = this._value[idx] != val ? dl.accessor(val) : this._accessors[idx]; } this._value[idx] = val; } return get.call(this); }; prototype.set = function(value) { var p = this, isExpr = exprType.test(this._type), isData = dataType.test(this._type), isField = fieldType.test(this._type); this._value = dl.array(value).map(function(v, i) { if (dl.isString(v)) { if (isExpr) { var e = expr(v); p._transform.dependency(Deps.FIELDS, e.fields); p._transform.dependency(Deps.SIGNALS, e.globals); return e.fn; } else if (isField) { // Backwards compatibility p._accessors[i] = dl.accessor(v); p._transform.dependency(Deps.FIELDS, dl.field(v)); } else if (isData) { p._resolution = true; p._transform.dependency(Deps.DATA, v); } return v; } else if (v.value !== undefined) { return v.value; } else if (v.field !== undefined) { p._accessors[i] = dl.accessor(v.field); p._transform.dependency(Deps.FIELDS, dl.field(v.field)); return v.field; } else if (v.signal !== undefined) { p._resolution = true; p._signals[v.signal] = i; p._transform.dependency(Deps.SIGNALS, v.signal); return v.signal; } return v; }); return p._transform; }; module.exports = Parameter; },{"../parse/expr":94,"datalib":24,"vega-dataflow":39}],132:[function(require,module,exports){ var dl = require('datalib'), Tuple = require('vega-dataflow').Tuple, log = require('vega-logging'), Transform = require('./Transform'), BatchTransform = require('./BatchTransform'); function Pie(graph) { BatchTransform.prototype.init.call(this, graph); Transform.addParameters(this, { field: {type: 'field', default: null}, startAngle: {type: 'value', default: 0}, endAngle: {type: 'value', default: 2 * Math.PI}, sort: {type: 'value', default: false} }); this._output = { 'start': 'layout_start', 'end': 'layout_end', 'mid': 'layout_mid' }; return this.mutates(true); } var prototype = (Pie.prototype = Object.create(BatchTransform.prototype)); prototype.constructor = Pie; function ones() { return 1; } prototype.batchTransform = function(input, data) { log.debug(input, ['pie']); var output = this._output, field = this.param('field').accessor || ones, start = this.param('startAngle'), stop = this.param('endAngle'), sort = this.param('sort'); var values = data.map(field), a = start, k = (stop - start) / dl.sum(values), index = dl.range(data.length), i, t, v; if (sort) { index.sort(function(a, b) { return values[a] - values[b]; }); } for (i=0; i<index.length; ++i) { t = data[index[i]]; v = values[index[i]]; Tuple.set(t, output.start, a); Tuple.set(t, output.mid, (a + 0.5 * v * k)); Tuple.set(t, output.end, (a += v * k)); } input.fields[output.start] = 1; input.fields[output.end] = 1; input.fields[output.mid] = 1; return input; }; module.exports = Pie; },{"./BatchTransform":117,"./Transform":135,"datalib":24,"vega-dataflow":39,"vega-logging":45}],133:[function(require,module,exports){ var dl = require('datalib'), log = require('vega-logging'), Transform = require('./Transform'); function Sort(graph) { Transform.prototype.init.call(this, graph); Transform.addParameters(this, {by: {type: 'array<field>'} }); this.router(true); } var prototype = (Sort.prototype = Object.create(Transform.prototype)); prototype.constructor = Sort; prototype.transform = function(input) { log.debug(input, ['sorting']); if (input.add.length || input.mod.length || input.rem.length) { input.sort = dl.comparator(this.param('by').field); } return input; }; module.exports = Sort; },{"./Transform":135,"datalib":24,"vega-logging":45}],134:[function(require,module,exports){ var dl = require('datalib'), Tuple = require('vega-dataflow').Tuple, log = require('vega-logging'), Transform = require('./Transform'), BatchTransform = require('./BatchTransform'); function Stack(graph) { BatchTransform.prototype.init.call(this, graph); Transform.addParameters(this, { groupby: {type: 'array<field>'}, sortby: {type: 'array<field>'}, field: {type: 'field'}, offset: {type: 'value', default: 'zero'} }); this._output = { 'start': 'layout_start', 'end': 'layout_end', 'mid': 'layout_mid' }; return this.mutates(true); } var prototype = (Stack.prototype = Object.create(BatchTransform.prototype)); prototype.constructor = Stack; prototype.batchTransform = function(input, data) { log.debug(input, ['stacking']); var groupby = this.param('groupby').accessor, sortby = dl.comparator(this.param('sortby').field), field = this.param('field').accessor, offset = this.param('offset'), output = this._output; // partition, sum, and sort the stack groups var groups = partition(data, groupby, sortby, field); // compute stack layouts per group for (var i=0, max=groups.max; i<groups.length; ++i) { var group = groups[i], sum = group.sum, off = offset==='center' ? (max - sum)/2 : 0, scale = offset==='normalize' ? (1/sum) : 1, j, x, a, b = off, v = 0; // set stack coordinates for each datum in group for (j=0; j<group.length; ++j) { x = group[j]; a = b; // use previous value for start point v += field(x); b = scale * v + off; // compute end point Tuple.set(x, output.start, a); Tuple.set(x, output.end, b); Tuple.set(x, output.mid, 0.5 * (a + b)); } } input.fields[output.start] = 1; input.fields[output.end] = 1; input.fields[output.mid] = 1; return input; }; function partition(data, groupby, sortby, field) { var groups = [], get = function(f) { return f(x); }, map, i, x, k, g, s, max; // partition data points into stack groups if (groupby == null) { groups.push(data.slice()); } else { for (map={}, i=0; i<data.length; ++i) { x = data[i]; k = groupby.map(get); g = map[k] || (groups.push(map[k] = []), map[k]); g.push(x); } } // compute sums of groups, sort groups as needed for (k=0, max=0; k<groups.length; ++k) { g = groups[k]; for (i=0, s=0; i<g.length; ++i) { s += field(g[i]); } g.sum = s; if (s > max) max = s; if (sortby != null) g.sort(sortby); } groups.max = max; return groups; } module.exports = Stack; },{"./BatchTransform":117,"./Transform":135,"datalib":24,"vega-dataflow":39,"vega-logging":45}],135:[function(require,module,exports){ var df = require('vega-dataflow'), Base = df.Node.prototype, // jshint ignore:line Deps = df.Dependencies, Parameter = require('./Parameter'); function Transform(graph) { if (graph) Base.init.call(this, graph); } Transform.addParameters = function(proto, params) { proto._parameters = proto._parameters || {}; for (var name in params) { var p = params[name], param = new Parameter(name, p.type, proto); proto._parameters[name] = param; if (p.type === 'custom') { if (p.set) param.set = p.set.bind(param); if (p.get) param.get = p.get.bind(param); } if (p.hasOwnProperty('default')) param.set(p.default); } }; var prototype = (Transform.prototype = Object.create(Base)); prototype.constructor = Transform; prototype.param = function(name, value) { var param = this._parameters[name]; return (param === undefined) ? this : (arguments.length === 1) ? param.get() : param.set(value); }; // Perform transformation. Subclasses should override. prototype.transform = function(input/*, reset */) { return input; }; prototype.evaluate = function(input) { // Many transforms store caches that must be invalidated if // a signal value has changed. var reset = this._stamp < input.stamp && this.dependency(Deps.SIGNALS).reduce(function(c, s) { return c += input.signals[s] ? 1 : 0; }, 0); return this.transform(input, reset); }; prototype.output = function(map) { for (var key in this._output) { if (map[key] !== undefined) { this._output[key] = map[key]; } } return this; }; module.exports = Transform; },{"./Parameter":131,"vega-dataflow":39}],136:[function(require,module,exports){ (function (global){ var d3 = (typeof window !== "undefined" ? window['d3'] : typeof global !== "undefined" ? global['d3'] : null), dl = require('datalib'), Tuple = require('vega-dataflow').Tuple, log = require('vega-logging'), Transform = require('./Transform'), BatchTransform = require('./BatchTransform'); var defaultRatio = 0.5 * (1 + Math.sqrt(5)); function Treemap(graph) { BatchTransform.prototype.init.call(this, graph); Transform.addParameters(this, { // hierarchy parameters sort: {type: 'array<field>', default: ['-value']}, children: {type: 'field', default: 'children'}, field: {type: 'field', default: 'value'}, // treemap parameters size: {type: 'array<value>', default: [500, 500]}, round: {type: 'value', default: true}, sticky: {type: 'value', default: false}, ratio: {type: 'value', default: defaultRatio}, padding: {type: 'value', default: null}, mode: {type: 'value', default: 'squarify'} }); this._layout = d3.layout.treemap(); this._output = { 'x': 'layout_x', 'y': 'layout_y', 'width': 'layout_width', 'height': 'layout_height', 'depth': 'layout_depth', }; return this.mutates(true); } var prototype = (Treemap.prototype = Object.create(BatchTransform.prototype)); prototype.constructor = Treemap; prototype.batchTransform = function(input, data) { log.debug(input, ['treemap']); // get variables var layout = this._layout, output = this._output; // configure layout layout .sort(dl.comparator(this.param('sort').field)) .children(this.param('children').accessor) .value(this.param('field').accessor) .size(this.param('size')) .round(this.param('round')) .sticky(this.param('sticky')) .ratio(this.param('ratio')) .padding(this.param('padding')) .mode(this.param('mode')) .nodes(data[0]); // copy layout values to nodes data.forEach(function(n) { Tuple.set(n, output.x, n.x); Tuple.set(n, output.y, n.y); Tuple.set(n, output.width, n.dx); Tuple.set(n, output.height, n.dy); Tuple.set(n, output.depth, n.depth); }); // return changeset input.fields[output.x] = 1; input.fields[output.y] = 1; input.fields[output.width] = 1; input.fields[output.height] = 1; return input; }; module.exports = Treemap; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./BatchTransform":117,"./Transform":135,"datalib":24,"vega-dataflow":39,"vega-logging":45}],137:[function(require,module,exports){ (function (global){ var d3 = (typeof window !== "undefined" ? window['d3'] : typeof global !== "undefined" ? global['d3'] : null), Tuple = require('vega-dataflow/src/Tuple'), log = require('vega-logging'), Transform = require('./Transform'), BatchTransform = require('./BatchTransform'); function Voronoi(graph) { BatchTransform.prototype.init.call(this, graph); Transform.addParameters(this, { clipExtent: {type: 'array<value>', default: [[-1e5,-1e5],[1e5,1e5]]}, x: {type: 'field', default: 'layout_x'}, y: {type: 'field', default: 'layout_y'} }); this._layout = d3.geom.voronoi(); this._output = {'path': 'layout_path'}; return this.mutates(true); } var prototype = (Voronoi.prototype = Object.create(BatchTransform.prototype)); prototype.constructor = Voronoi; prototype.batchTransform = function(input, data) { log.debug(input, ['voronoi']); // get variables var pathname = this._output.path; // configure layout var polygons = this._layout .clipExtent(this.param('clipExtent')) .x(this.param('x').accessor) .y(this.param('y').accessor) (data); // build and assign path strings for (var i=0; i<data.length; ++i) { Tuple.set(data[i], pathname, 'M' + polygons[i].join('L') + 'Z'); } // return changeset input.fields[pathname] = 1; return input; }; module.exports = Voronoi; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./BatchTransform":117,"./Transform":135,"vega-dataflow/src/Tuple":38,"vega-logging":45}],138:[function(require,module,exports){ (function (global){ var dl = require('datalib'), d3 = (typeof window !== "undefined" ? window['d3'] : typeof global !== "undefined" ? global['d3'] : null), d3_cloud = (typeof window !== "undefined" ? window['d3']['layout']['cloud'] : typeof global !== "undefined" ? global['d3']['layout']['cloud'] : null), Tuple = require('vega-dataflow/src/Tuple'), log = require('vega-logging'), Transform = require('./Transform'), BatchTransform = require('./BatchTransform'); function Wordcloud(graph) { BatchTransform.prototype.init.call(this, graph); Transform.addParameters(this, { size: {type: 'array<value>', default: [900, 500]}, text: {type: 'field', default: 'data'}, rotate: {type: 'field|value', default: 0}, font: {type: 'field|value', default: {value: 'sans-serif'}}, fontSize: {type: 'field|value', default: 14}, fontStyle: {type: 'field|value', default: {value: 'normal'}}, fontWeight: {type: 'field|value', default: {value: 'normal'}}, fontScale: {type: 'array<value>', default: [10, 50]}, padding: {type: 'value', default: 1}, spiral: {type: 'value', default: 'archimedean'} }); this._layout = d3_cloud(); this._output = { 'x': 'layout_x', 'y': 'layout_y', 'font': 'layout_font', 'fontSize': 'layout_fontSize', 'fontStyle': 'layout_fontStyle', 'fontWeight': 'layout_fontWeight', 'rotate': 'layout_rotate', }; return this.mutates(true); } var prototype = (Wordcloud.prototype = Object.create(BatchTransform.prototype)); prototype.constructor = Wordcloud; function get(p) { return (p && p.accessor) || p; } function wrap(tuple) { var x = Object.create(tuple); x._tuple = tuple; return x; } prototype.batchTransform = function(input, data) { log.debug(input, ['wordcloud']); // get variables var layout = this._layout, output = this._output, fontSize = this.param('fontSize'), range = fontSize.accessor && this.param('fontScale'), size, scale; fontSize = fontSize.accessor || d3.functor(fontSize); // create font size scaling function as needed if (range.length) { scale = d3.scale.sqrt() .domain(dl.extent(data, size=fontSize)) .range(range); fontSize = function(x) { return scale(size(x)); }; } // configure layout layout .size(this.param('size')) .text(get(this.param('text'))) .padding(this.param('padding')) .spiral(this.param('spiral')) .rotate(get(this.param('rotate'))) .font(get(this.param('font'))) .fontStyle(get(this.param('fontStyle'))) .fontWeight(get(this.param('fontWeight'))) .fontSize(fontSize) .words(data.map(wrap)) // wrap to avoid tuple writes .on('end', function(words) { var size = layout.size(), dx = size[0] >> 1, dy = size[1] >> 1, w, t, i, len; for (i=0, len=words.length; i<len; ++i) { w = words[i]; t = w._tuple; Tuple.set(t, output.x, w.x + dx); Tuple.set(t, output.y, w.y + dy); Tuple.set(t, output.font, w.font); Tuple.set(t, output.fontSize, w.size); Tuple.set(t, output.fontStyle, w.style); Tuple.set(t, output.fontWeight, w.weight); Tuple.set(t, output.rotate, w.rotate); } }) .start(); // return changeset for (var key in output) input.fields[output[key]] = 1; return input; }; module.exports = Wordcloud; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./BatchTransform":117,"./Transform":135,"datalib":24,"vega-dataflow/src/Tuple":38,"vega-logging":45}],139:[function(require,module,exports){ module.exports = { aggregate: require('./Aggregate'), bin: require('./Bin'), cross: require('./Cross'), countpattern: require('./CountPattern'), linkpath: require('./LinkPath'), facet: require('./Facet'), filter: require('./Filter'), fold: require('./Fold'), force: require('./Force'), formula: require('./Formula'), geo: require('./Geo'), geopath: require('./GeoPath'), lookup: require('./Lookup'), pie: require('./Pie'), sort: require('./Sort'), stack: require('./Stack'), treemap: require('./Treemap'), voronoi: require('./Voronoi'), wordcloud: require('./Wordcloud') }; },{"./Aggregate":116,"./Bin":118,"./CountPattern":119,"./Cross":120,"./Facet":121,"./Filter":123,"./Fold":124,"./Force":125,"./Formula":126,"./Geo":127,"./GeoPath":128,"./LinkPath":129,"./Lookup":130,"./Pie":132,"./Sort":133,"./Stack":134,"./Treemap":136,"./Voronoi":137,"./Wordcloud":138}]},{},[1])(1) }); //# sourceMappingURL=vega.js.map
vertex_ui/src/components/Navbar/Navbar.js
zapcoop/vertex
import React from 'react'; import { PropTypes } from 'prop-types'; import { Navbar as ReactBootstrapNavbar } from 'react-bootstrap'; import { OutsideClick } from 'components'; import classNames from 'classnames'; import classes from './Navbar.scss'; import updateChildElementOfType from './../utils/updateChildElementOfType'; const Navbar = props => { const { className, children, ...otherProps } = props; const navbarClass = classNames(className, classes.navbar); const updatedChildren = updateChildElementOfType( children, [OutsideClick], [ { targetType: Navbar.Collapse, props: prevProps => ({ className: `${prevProps.className} ${classes.navbarCollapse}`, }), }, ], ); return ( <ReactBootstrapNavbar className={navbarClass} {...otherProps}> {updatedChildren} </ReactBootstrapNavbar> ); }; export default Navbar;
wp-content/themes/euclid_theme/euclid/vafpress/public/js/vendor/jquery-1.8.3.min.js
How2ForFree/development
/*! jQuery v1.8.3 jquery.com | jquery.org/license */ (function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r<i;r++)v.event.add(t,n,u[n][r])}o.data&&(o.data=v.extend({},o.data))}function Ot(e,t){var n;if(t.nodeType!==1)return;t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),n==="object"?(t.parentNode&&(t.outerHTML=e.outerHTML),v.support.html5Clone&&e.innerHTML&&!v.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):n==="input"&&Et.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):n==="option"?t.selected=e.defaultSelected:n==="input"||n==="textarea"?t.defaultValue=e.defaultValue:n==="script"&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(v.expando)}function Mt(e){return typeof e.getElementsByTagName!="undefined"?e.getElementsByTagName("*"):typeof e.querySelectorAll!="undefined"?e.querySelectorAll("*"):[]}function _t(e){Et.test(e.type)&&(e.defaultChecked=e.checked)}function Qt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Jt.length;while(i--){t=Jt[i]+n;if(t in e)return t}return r}function Gt(e,t){return e=t||e,v.css(e,"display")==="none"||!v.contains(e.ownerDocument,e)}function Yt(e,t){var n,r,i=[],s=0,o=e.length;for(;s<o;s++){n=e[s];if(!n.style)continue;i[s]=v._data(n,"olddisplay"),t?(!i[s]&&n.style.display==="none"&&(n.style.display=""),n.style.display===""&&Gt(n)&&(i[s]=v._data(n,"olddisplay",nn(n.nodeName)))):(r=Dt(n,"display"),!i[s]&&r!=="none"&&v._data(n,"olddisplay",r))}for(s=0;s<o;s++){n=e[s];if(!n.style)continue;if(!t||n.style.display==="none"||n.style.display==="")n.style.display=t?i[s]||"":"none"}return e}function Zt(e,t,n){var r=Rt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function en(e,t,n,r){var i=n===(r?"border":"content")?4:t==="width"?1:0,s=0;for(;i<4;i+=2)n==="margin"&&(s+=v.css(e,n+$t[i],!0)),r?(n==="content"&&(s-=parseFloat(Dt(e,"padding"+$t[i]))||0),n!=="margin"&&(s-=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0)):(s+=parseFloat(Dt(e,"padding"+$t[i]))||0,n!=="padding"&&(s+=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0));return s}function tn(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=!0,s=v.support.boxSizing&&v.css(e,"boxSizing")==="border-box";if(r<=0||r==null){r=Dt(e,t);if(r<0||r==null)r=e.style[t];if(Ut.test(r))return r;i=s&&(v.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+en(e,t,n||(s?"border":"content"),i)+"px"}function nn(e){if(Wt[e])return Wt[e];var t=v("<"+e+">").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write("<!doctype html><html><body>"),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u<a;u++)r=o[u],s=/^\+/.test(r),s&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[s?"unshift":"push"](n)}}function kn(e,n,r,i,s,o){s=s||n.dataTypes[0],o=o||{},o[s]=!0;var u,a=e[s],f=0,l=a?a.length:0,c=e===Sn;for(;f<l&&(c||!u);f++)u=a[f](n,r,i),typeof u=="string"&&(!c||o[u]?u=t:(n.dataTypes.unshift(u),u=kn(e,n,r,i,u,o)));return(c||!u)&&!o["*"]&&(u=kn(e,n,r,i,"*",o)),u}function Ln(e,n){var r,i,s=v.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((s[r]?e:i||(i={}))[r]=n[r]);i&&v.extend(!0,e,i)}function An(e,n,r){var i,s,o,u,a=e.contents,f=e.dataTypes,l=e.responseFields;for(s in l)s in r&&(n[l[s]]=r[s]);while(f[0]==="*")f.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(s in a)if(a[s]&&a[s].test(i)){f.unshift(s);break}if(f[0]in r)o=f[0];else{for(s in r){if(!f[0]||e.converters[s+" "+f[0]]){o=s;break}u||(u=s)}o=o||u}if(o)return o!==f[0]&&f.unshift(o),r[o]}function On(e,t){var n,r,i,s,o=e.dataTypes.slice(),u=o[0],a={},f=0;e.dataFilter&&(t=e.dataFilter(t,e.dataType));if(o[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=o[++f];)if(i!=="*"){if(u!=="*"&&u!==i){n=a[u+" "+i]||a["* "+i];if(!n)for(r in a){s=r.split(" ");if(s[1]===i){n=a[u+" "+s[0]]||a["* "+s[0]];if(n){n===!0?n=a[r]:a[r]!==!0&&(i=s[0],o.splice(f--,0,i));break}}}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(l){return{state:"parsererror",error:n?l:"No conversion from "+u+" to "+i}}}u=i}return{state:"success",data:t}}function Fn(){try{return new e.XMLHttpRequest}catch(t){}}function In(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function $n(){return setTimeout(function(){qn=t},0),qn=v.now()}function Jn(e,t){v.each(t,function(t,n){var r=(Vn[t]||[]).concat(Vn["*"]),i=0,s=r.length;for(;i<s;i++)if(r[i].call(e,t,n))return})}function Kn(e,t,n){var r,i=0,s=0,o=Xn.length,u=v.Deferred().always(function(){delete a.elem}),a=function(){var t=qn||$n(),n=Math.max(0,f.startTime+f.duration-t),r=n/f.duration||0,i=1-r,s=0,o=f.tweens.length;for(;s<o;s++)f.tweens[s].run(i);return u.notifyWith(e,[f,i,n]),i<1&&o?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:v.extend({},t),opts:v.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:qn||$n(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=v.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(i),i},stop:function(t){var n=0,r=t?f.tweens.length:0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;Qn(l,f.opts.specialEasing);for(;i<o;i++){r=Xn[i].call(f,e,l,f.opts);if(r)return r}return Jn(f,l),v.isFunction(f.opts.start)&&f.opts.start.call(e,f),v.fx.timer(v.extend(a,{anim:f,queue:f.opts.queue,elem:e})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function Qn(e,t){var n,r,i,s,o;for(n in e){r=v.camelCase(n),i=t[r],s=e[n],v.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=v.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function Gn(e,t,n){var r,i,s,o,u,a,f,l,c,h=this,p=e.style,d={},m=[],g=e.nodeType&&Gt(e);n.queue||(l=v._queueHooks(e,"fx"),l.unqueued==null&&(l.unqueued=0,c=l.empty.fire,l.empty.fire=function(){l.unqueued||c()}),l.unqueued++,h.always(function(){h.always(function(){l.unqueued--,v.queue(e,"fx").length||l.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],v.css(e,"display")==="inline"&&v.css(e,"float")==="none"&&(!v.support.inlineBlockNeedsLayout||nn(e.nodeName)==="inline"?p.display="inline-block":p.zoom=1)),n.overflow&&(p.overflow="hidden",v.support.shrinkWrapBlocks||h.done(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t){s=t[r];if(Un.exec(s)){delete t[r],a=a||s==="toggle";if(s===(g?"hide":"show"))continue;m.push(r)}}o=m.length;if(o){u=v._data(e,"fxshow")||v._data(e,"fxshow",{}),"hidden"in u&&(g=u.hidden),a&&(u.hidden=!g),g?v(e).show():h.done(function(){v(e).hide()}),h.done(function(){var t;v.removeData(e,"fxshow",!0);for(t in d)v.style(e,t,d[t])});for(r=0;r<o;r++)i=m[r],f=h.createTween(i,g?u[i]:0),d[i]=u[i]||v.style(e,i),i in u||(u[i]=f.start,g&&(f.end=f.start,f.start=i==="width"||i==="height"?1:0))}}function Yn(e,t,n,r,i){return new Yn.prototype.init(e,t,n,r,i)}function Zn(e,t){var n,r={height:e},i=0;t=t?1:0;for(;i<4;i+=2-t)n=$t[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function tr(e){return v.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:!1}var n,r,i=e.document,s=e.location,o=e.navigator,u=e.jQuery,a=e.$,f=Array.prototype.push,l=Array.prototype.slice,c=Array.prototype.indexOf,h=Object.prototype.toString,p=Object.prototype.hasOwnProperty,d=String.prototype.trim,v=function(e,t){return new v.fn.init(e,t,n)},m=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,g=/\S/,y=/\s+/,b=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,w=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a<f;a++)if((e=arguments[a])!=null)for(n in e){r=u[n],i=e[n];if(u===i)continue;l&&i&&(v.isPlainObject(i)||(s=v.isArray(i)))?(s?(s=!1,o=r&&v.isArray(r)?r:[]):o=r&&v.isPlainObject(r)?r:{},u[n]=v.extend(l,o,i)):i!==t&&(u[n]=i)}return u},v.extend({noConflict:function(t){return e.$===v&&(e.$=a),t&&e.jQuery===v&&(e.jQuery=u),v},isReady:!1,readyWait:1,holdReady:function(e){e?v.readyWait++:v.ready(!0)},ready:function(e){if(e===!0?--v.readyWait:v.isReady)return;if(!i.body)return setTimeout(v.ready,1);v.isReady=!0;if(e!==!0&&--v.readyWait>0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s<o;)if(n.apply(e[s++],r)===!1)break}else if(u){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;s<o;)if(n.call(e[s],s,e[s++])===!1)break;return e},trim:d&&!d.call("\ufeff\u00a0")?function(e){return e==null?"":d.call(e)}:function(e){return e==null?"":(e+"").replace(b,"")},makeArray:function(e,t){var n,r=t||[];return e!=null&&(n=v.type(e),e.length==null||n==="string"||n==="function"||n==="regexp"||v.isWindow(e)?f.call(r,e):v.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(c)return c.call(t,e,n);r=t.length,n=n?n<0?Math.max(0,r+n):n:0;for(;n<r;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,s=0;if(typeof r=="number")for(;s<r;s++)e[i++]=n[s];else while(n[s]!==t)e[i++]=n[s++];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length;n=!!n;for(;s<o;s++)r=!!t(e[s],s),n!==r&&i.push(e[s]);return i},map:function(e,n,r){var i,s,o=[],u=0,a=e.length,f=e instanceof v||a!==t&&typeof a=="number"&&(a>0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u<a;u++)i=n(e[u],u,r),i!=null&&(o[o.length]=i);else for(s in e)i=n(e[s],s,r),i!=null&&(o[o.length]=i);return o.concat.apply([],o)},guid:1,proxy:function(e,n){var r,i,s;return typeof n=="string"&&(r=e[n],n=e,e=r),v.isFunction(e)?(i=l.call(arguments,2),s=function(){return e.apply(n,i.concat(l.call(arguments)))},s.guid=e.guid=e.guid||v.guid++,s):t},access:function(e,n,r,i,s,o,u){var a,f=r==null,l=0,c=e.length;if(r&&typeof r=="object"){for(l in r)v.access(e,n,l,r[l],1,o,i);s=1}else if(i!==t){a=u===t&&v.isFunction(i),f&&(a?(a=n,n=function(e,t,n){return a.call(v(e),n)}):(n.call(e,i),n=null));if(n)for(;l<c;l++)n(e[l],r,a?i.call(e[l],l,n(e[l],r)):i,u);s=1}return s?e:f?n.call(e):c?n(e[0],r):o},now:function(){return(new Date).getTime()}}),v.ready.promise=function(t){if(!r){r=v.Deferred();if(i.readyState==="complete")setTimeout(v.ready,1);else if(i.addEventListener)i.addEventListener("DOMContentLoaded",A,!1),e.addEventListener("load",v.ready,!1);else{i.attachEvent("onreadystatechange",A),e.attachEvent("onload",v.ready);var n=!1;try{n=e.frameElement==null&&i.documentElement}catch(s){}n&&n.doScroll&&function o(){if(!v.isReady){try{n.doScroll("left")}catch(e){return setTimeout(o,50)}v.ready()}}()}}return r.promise(t)},v.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){O["[object "+t+"]"]=t.toLowerCase()}),n=v(i);var M={};v.Callbacks=function(e){e=typeof e=="string"?M[e]||_(e):v.extend({},e);var n,r,i,s,o,u,a=[],f=!e.once&&[],l=function(t){n=e.memory&&t,r=!0,u=s||0,s=0,o=a.length,i=!0;for(;a&&u<o;u++)if(a[u].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}i=!1,a&&(f?f.length&&l(f.shift()):n?a=[]:c.disable())},c={add:function(){if(a){var t=a.length;(function r(t){v.each(t,function(t,n){var i=v.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this},remove:function(){return a&&v.each(arguments,function(e,t){var n;while((n=v.inArray(t,a,n))>-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&v.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}}),v.support=function(){var t,n,r,s,o,u,a,f,l,c,h,p=i.createElement("div");p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i<s;i++)delete r[t[i]];if(!(n?B:v.isEmptyObject)(r))return}}if(!n){delete u[a].data;if(!B(u[a]))return}o?v.cleanData([e],!0):v.support.deleteExpando||u!=u.window?delete u[a]:u[a]=null},_data:function(e,t,n){return v.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&v.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),v.fn.extend({data:function(e,n){var r,i,s,o,u,a=this[0],f=0,l=null;if(e===t){if(this.length){l=v.data(a);if(a.nodeType===1&&!v._data(a,"parsedAttrs")){s=a.attributes;for(u=s.length;f<u;f++)o=s[f].name,o.indexOf("data-")||(o=v.camelCase(o.substring(5)),H(a,o,l[o]));v._data(a,"parsedAttrs",!0)}}return l}return typeof e=="object"?this.each(function(){v.data(this,e)}):(r=e.split(".",2),r[1]=r[1]?"."+r[1]:"",i=r[1]+"!",v.access(this,function(n){if(n===t)return l=this.triggerHandler("getData"+i,[r[0]]),l===t&&a&&(l=v.data(a,e),l=H(a,e,l)),l===t&&r[1]?this.data(r[0]):l;r[1]=n,this.each(function(){var t=v(this);t.triggerHandler("setData"+i,r),v.data(this,e,n),t.triggerHandler("changeData"+i,r)})},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length<r?v.queue(this[0],e):n===t?this:this.each(function(){var t=v.queue(this,e,n);v._queueHooks(this,e),e==="fx"&&t[0]!=="inprogress"&&v.dequeue(this,e)})},dequeue:function(e){return this.each(function(){v.dequeue(this,e)})},delay:function(e,t){return e=v.fx?v.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,s=v.Deferred(),o=this,u=this.length,a=function(){--i||s.resolveWith(o,[o])};typeof e!="string"&&(n=e,e=t),e=e||"fx";while(u--)r=v._data(o[u],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(a));return a(),s.promise(n)}});var j,F,I,q=/[\t\r\n]/g,R=/\r/g,U=/^(?:button|input)$/i,z=/^(?:button|input|object|select|textarea)$/i,W=/^a(?:rea|)$/i,X=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,V=v.support.getSetAttribute;v.fn.extend({attr:function(e,t){return v.access(this,v.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n<r;n++){i=this[n];if(i.nodeType===1)if(!i.className&&t.length===1)i.className=e;else{s=" "+i.className+" ";for(o=0,u=t.length;o<u;o++)s.indexOf(" "+t[o]+" ")<0&&(s+=t[o]+" ");i.className=v.trim(s)}}}return this},removeClass:function(e){var n,r,i,s,o,u,a;if(v.isFunction(e))return this.each(function(t){v(this).removeClass(e.call(this,t,this.className))});if(e&&typeof e=="string"||e===t){n=(e||"").split(y);for(u=0,a=this.length;u<a;u++){i=this[u];if(i.nodeType===1&&i.className){r=(" "+i.className+" ").replace(q," ");for(s=0,o=n.length;s<o;s++)while(r.indexOf(" "+n[s]+" ")>=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(q," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a<u;a++){n=r[a];if((n.selected||a===i)&&(v.support.optDisabled?!n.disabled:n.getAttribute("disabled")===null)&&(!n.parentNode.disabled||!v.nodeName(n.parentNode,"optgroup"))){t=v(n).val();if(s)return t;o.push(t)}}return o},set:function(e,t){var n=v.makeArray(t);return v(e).find("option").each(function(){this.selected=v.inArray(v(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o<r.length;o++)i=r[o],i&&(n=v.propFix[i]||i,s=X.test(i),s||v.attr(e,i,""),e.removeAttribute(V?i:n),s&&n in e&&(e[n]=!1))}},attrHooks:{type:{set:function(e,t){if(U.test(e.nodeName)&&e.parentNode)v.error("type property can't be changed");else if(!v.support.radioValue&&t==="radio"&&v.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return j&&v.nodeName(e,"button")?j.get(e,t):t in e?e.value:null},set:function(e,t,n){if(j&&v.nodeName(e,"button"))return j.set(e,t,n);e.value=t}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,s,o,u=e.nodeType;if(!e||u===3||u===8||u===2)return;return o=u!==1||!v.isXMLDoc(e),o&&(n=v.propFix[n]||n,s=v.propHooks[n]),r!==t?s&&"set"in s&&(i=s.set(e,r,n))!==t?i:e[n]=r:s&&"get"in s&&(i=s.get(e,n))!==null?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):z.test(e.nodeName)||W.test(e.nodeName)&&e.href?0:t}}}}),F={get:function(e,n){var r,i=v.prop(e,n);return i===!0||typeof i!="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?v.removeAttr(e,n):(r=v.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},V||(I={name:!0,id:!0,coords:!0},j=v.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(I[n]?r.value!=="":r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=i.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},v.each(["width","height"],function(e,t){v.attrHooks[t]=v.extend(v.attrHooks[t],{set:function(e,n){if(n==="")return e.setAttribute(t,"auto"),n}})}),v.attrHooks.contenteditable={get:j.get,set:function(e,t,n){t===""&&(t="false"),j.set(e,t,n)}}),v.support.hrefNormalized||v.each(["href","src","width","height"],function(e,n){v.attrHooks[n]=v.extend(v.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})}),v.support.style||(v.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=t+""}}),v.support.optSelected||(v.propHooks.selected=v.extend(v.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),v.support.enctype||(v.propFix.enctype="encoding"),v.support.checkOn||v.each(["radio","checkbox"],function(){v.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}}),v.each(["radio","checkbox"],function(){v.valHooks[this]=v.extend(v.valHooks[this],{set:function(e,t){if(v.isArray(t))return e.checked=v.inArray(v(e).val(),t)>=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f<n.length;f++){l=J.exec(n[f])||[],c=l[1],h=(l[2]||"").split(".").sort(),g=v.event.special[c]||{},c=(s?g.delegateType:g.bindType)||c,g=v.event.special[c]||{},p=v.extend({type:c,origType:l[1],data:i,handler:r,guid:r.guid,selector:s,needsContext:s&&v.expr.match.needsContext.test(s),namespace:h.join(".")},d),m=a[c];if(!m){m=a[c]=[],m.delegateCount=0;if(!g.setup||g.setup.call(e,i,h,u)===!1)e.addEventListener?e.addEventListener(c,u,!1):e.attachEvent&&e.attachEvent("on"+c,u)}g.add&&(g.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),s?m.splice(m.delegateCount++,0,p):m.push(p),v.event.global[c]=!0}e=null},global:{},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,m,g=v.hasData(e)&&v._data(e);if(!g||!(h=g.events))return;t=v.trim(Z(t||"")).split(" ");for(s=0;s<t.length;s++){o=J.exec(t[s])||[],u=a=o[1],f=o[2];if(!u){for(u in h)v.event.remove(e,u+t[s],n,r,!0);continue}p=v.event.special[u]||{},u=(r?p.delegateType:p.bindType)||u,d=h[u]||[],l=d.length,f=f?new RegExp("(^|\\.)"+f.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(c=0;c<d.length;c++)m=d[c],(i||a===m.origType)&&(!n||n.guid===m.guid)&&(!f||f.test(m.namespace))&&(!r||r===m.selector||r==="**"&&m.selector)&&(d.splice(c--,1),m.selector&&d.delegateCount--,p.remove&&p.remove.call(e,m));d.length===0&&l!==d.length&&((!p.teardown||p.teardown.call(e,f,g.handle)===!1)&&v.removeEvent(e,u,g.handle),delete h[u])}v.isEmptyObject(h)&&(delete g.handle,v.removeData(e,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,s,o){if(!s||s.nodeType!==3&&s.nodeType!==8){var u,a,f,l,c,h,p,d,m,g,y=n.type||n,b=[];if(Y.test(y+v.event.triggered))return;y.indexOf("!")>=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f<m.length&&!n.isPropagationStopped();f++)l=m[f][0],n.type=m[f][1],d=(v._data(l,"events")||{})[n.type]&&v._data(l,"handle"),d&&d.apply(l,r),d=h&&l[h],d&&v.acceptData(l)&&d.apply&&d.apply(l,r)===!1&&n.preventDefault();return n.type=y,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(s.ownerDocument,r)===!1)&&(y!=="click"||!v.nodeName(s,"a"))&&v.acceptData(s)&&h&&s[y]&&(y!=="focus"&&y!=="blur"||n.target.offsetWidth!==0)&&!v.isWindow(s)&&(c=s[h],c&&(s[h]=null),v.event.triggered=y,s[y](),v.event.triggered=t,c&&(s[h]=c)),n.result}return},dispatch:function(n){n=v.event.fix(n||e.event);var r,i,s,o,u,a,f,c,h,p,d=(v._data(this,"events")||{})[n.type]||[],m=d.delegateCount,g=l.call(arguments),y=!n.exclusive&&!n.namespace,b=v.event.special[n.type]||{},w=[];g[0]=n,n.delegateTarget=this;if(b.preDispatch&&b.preDispatch.call(this,n)===!1)return;if(m&&(!n.button||n.type!=="click"))for(s=n.target;s!=this;s=s.parentNode||this)if(s.disabled!==!0||n.type!=="click"){u={},f=[];for(r=0;r<m;r++)c=d[r],h=c.selector,u[h]===t&&(u[h]=c.needsContext?v(h,this).index(s)>=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r<w.length&&!n.isPropagationStopped();r++){a=w[r],n.currentTarget=a.elem;for(i=0;i<a.matches.length&&!n.isImmediatePropagationStopped();i++){c=a.matches[i];if(y||!n.namespace&&!c.namespace||n.namespace_re&&n.namespace_re.test(c.namespace))n.data=c.data,n.handleObj=c,o=((v.event.special[c.origType]||{}).handle||c.handler).apply(a.elem,g),o!==t&&(n.result=o,o===!1&&(n.preventDefault(),n.stopPropagation()))}}return b.postDispatch&&b.postDispatch.call(this,n),n.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return e.which==null&&(e.which=t.charCode!=null?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,s,o,u=n.button,a=n.fromElement;return e.pageX==null&&n.clientX!=null&&(r=e.target.ownerDocument||i,s=r.documentElement,o=r.body,e.pageX=n.clientX+(s&&s.scrollLeft||o&&o.scrollLeft||0)-(s&&s.clientLeft||o&&o.clientLeft||0),e.pageY=n.clientY+(s&&s.scrollTop||o&&o.scrollTop||0)-(s&&s.clientTop||o&&o.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?n.toElement:a),!e.which&&u!==t&&(e.which=u&1?1:u&2?3:u&4?2:0),e}},fix:function(e){if(e[v.expando])return e;var t,n,r=e,s=v.event.fixHooks[e.type]||{},o=s.props?this.props.concat(s.props):this.props;e=v.Event(r);for(t=o.length;t;)n=o[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||i),e.target.nodeType===3&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){v.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=v.extend(new v.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?v.event.trigger(i,null,t):v.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},v.event.handle=v.event.dispatch,v.removeEvent=i.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]=="undefined"&&(e[r]=null),e.detachEvent(r,n))},v.Event=function(e,t){if(!(this instanceof v.Event))return new v.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?tt:et):this.type=e,t&&v.extend(this,t),this.timeStamp=e&&e.timeStamp||v.now(),this[v.expando]=!0},v.Event.prototype={preventDefault:function(){this.isDefaultPrevented=tt;var e=this.originalEvent;if(!e)return;e.preventDefault?e.preventDefault():e.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=tt;var e=this.originalEvent;if(!e)return;e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=tt,this.stopPropagation()},isDefaultPrevented:et,isPropagationStopped:et,isImmediatePropagationStopped:et},v.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){v.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj,o=s.selector;if(!i||i!==r&&!v.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),v.support.submitBubbles||(v.event.special.submit={setup:function(){if(v.nodeName(this,"form"))return!1;v.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=v.nodeName(n,"input")||v.nodeName(n,"button")?n.form:t;r&&!v._data(r,"_submit_attached")&&(v.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),v._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&v.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){if(v.nodeName(this,"form"))return!1;v.event.remove(this,"._submit")}}),v.support.changeBubbles||(v.event.special.change={setup:function(){if($.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")v.event.add(this,"propertychange._change",function(e){e.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),v.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),v.event.simulate("change",this,e,!0)});return!1}v.event.add(this,"beforeactivate._change",function(e){var t=e.target;$.test(t.nodeName)&&!v._data(t,"_change_attached")&&(v.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&v.event.simulate("change",this.parentNode,e,!0)}),v._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;if(this!==t||e.isSimulated||e.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return e.handleObj.handler.apply(this,arguments)},teardown:function(){return v.event.remove(this,"._change"),!$.test(this.nodeName)}}),v.support.focusinBubbles||v.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){v.event.simulate(t,e.target,v.event.fix(e),!0)};v.event.special[t]={setup:function(){n++===0&&i.addEventListener(e,r,!0)},teardown:function(){--n===0&&i.removeEventListener(e,r,!0)}}}),v.fn.extend({on:function(e,n,r,i,s){var o,u;if(typeof e=="object"){typeof n!="string"&&(r=r||n,n=t);for(u in e)this.on(u,n,r,e[u],s);return this}r==null&&i==null?(i=n,r=n=t):i==null&&(typeof n=="string"?(i=r,r=t):(i=r,r=n,n=t));if(i===!1)i=et;else if(!i)return this;return s===1&&(o=i,i=function(e){return v().off(e),o.apply(this,arguments)},i.guid=o.guid||(o.guid=v.guid++)),this.each(function(){v.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,s;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,v(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if(typeof e=="object"){for(s in e)this.off(s,n,e[s]);return this}if(n===!1||typeof n=="function")r=n,n=t;return r===!1&&(r=et),this.each(function(){v.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},live:function(e,t,n){return v(this.context).on(e,this.selector,t,n),this},die:function(e,t){return v(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length===1?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){v.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0])return v.event.trigger(e,t,this[0],!0)},toggle:function(e){var t=arguments,n=e.guid||v.guid++,r=0,i=function(n){var i=(v._data(this,"lastToggle"+e.guid)||0)%r;return v._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};i.guid=n;while(r<t.length)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),v.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){v.fn[t]=function(e,n){return n==null&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u<a;u++)if(s=e[u])if(!n||n(s,r,i))o.push(s),f&&t.push(u);return o}function ct(e,t,n,r,i,s){return r&&!r[d]&&(r=ct(r)),i&&!i[d]&&(i=ct(i,s)),N(function(s,o,u,a){var f,l,c,h=[],p=[],d=o.length,v=s||dt(t||"*",u.nodeType?[u]:u,[]),m=e&&(s||!t)?lt(v,h,e,u,a):v,g=n?i||(s?e:d||r)?[]:o:m;n&&n(m,g,u,a);if(r){f=lt(g,p),r(f,[],u,a),l=f.length;while(l--)if(c=f[l])g[p[l]]=!(m[p[l]]=c)}if(s){if(i||e){if(i){f=[],l=g.length;while(l--)(c=g[l])&&f.push(m[l]=c);i(null,g=[],f,a)}l=g.length;while(l--)(c=g[l])&&(f=i?T.call(s,c):h[l])>-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a<s;a++)if(n=i.relative[e[a].type])h=[at(ft(h),n)];else{n=i.filter[e[a].type].apply(null,e[a].matches);if(n[d]){r=++a;for(;r<s;r++)if(i.relative[e[r].type])break;return ct(a>1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a<r&&ht(e.slice(a,r)),r<s&&ht(e=e.slice(r)),r<s&&e.join(""))}h.push(n)}return ft(h)}function pt(e,t){var r=t.length>0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r<i;r++)nt(e,t[r],n);return n}function vt(e,t,n,r,s){var o,u,f,l,c,h=ut(e),p=h.length;if(!r&&h.length===1){u=h[0]=h[0].slice(0);if(u.length>2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;t<n;t++)if(this[t]===e)return t;return-1},N=function(e,t){return e[d]=t==null||t,e},C=function(){var e={},t=[];return N(function(n,r){return t.push(n)>i.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="<a name='"+d+"'></a><div name='"+d+"'></div>",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:st(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:st(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}},f=y.compareDocumentPosition?function(e,t){return e===t?(l=!0,0):(!e.compareDocumentPosition||!t.compareDocumentPosition?e.compareDocumentPosition:e.compareDocumentPosition(t)&4)?-1:1}:function(e,t){if(e===t)return l=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],s=[],o=e.parentNode,u=t.parentNode,a=o;if(o===u)return ot(e,t);if(!o)return-1;if(!u)return 1;while(a)i.unshift(a),a=a.parentNode;a=u;while(a)s.unshift(a),a=a.parentNode;n=i.length,r=s.length;for(var f=0;f<n&&f<r;f++)if(i[f]!==s[f])return ot(i[f],s[f]);return f===n?ot(e,s[f],-1):ot(i[f],t,1)},[0,0].sort(f),h=!l,nt.uniqueSort=function(e){var t,n=[],r=1,i=0;l=h,e.sort(f);if(l){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e},nt.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},a=nt.compile=function(e,t){var n,r=[],i=[],s=A[d][e+" "];if(!s){t||(t=ut(e)),n=t.length;while(n--)s=ht(t[n]),s[d]?r.push(s):i.push(s);s=A(e,pt(i,r))}return s},g.querySelectorAll&&function(){var e,t=vt,n=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,i=[":focus"],s=[":active"],u=y.matchesSelector||y.mozMatchesSelector||y.webkitMatchesSelector||y.oMatchesSelector||y.msMatchesSelector;K(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t<n;t++)if(v.contains(u[t],this))return!0});o=this.pushStack("","find",e);for(t=0,n=this.length;t<n;t++){r=o.length,v.find(e,this[t],o);if(t>0)for(i=r;i<o.length;i++)for(s=0;s<r;s++)if(o[s]===o[i]){o.splice(i--,1);break}}return o},has:function(e){var t,n=v(e,this),r=n.length;return this.filter(function(){for(t=0;t<r;t++)if(v.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1),"not",e)},filter:function(e){return this.pushStack(ft(this,e,!0),"filter",e)},is:function(e){return!!e&&(typeof e=="string"?st.test(e)?v(e,this.context).index(this[0])>=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r<i;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&n.nodeType!==11){if(o?o.index(n)>-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/<tbody/i,gt=/<|&#?\w+;/,yt=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,wt=new RegExp("<(?:"+ct+")[\\s/>]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Nt={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X<div>","</div>"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1></$2>");try{for(;r<i;r++)n=this[r]||{},n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(s){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return ut(this[0])?this.length?this.pushStack(v(v.isFunction(e)?e():e),"replaceWith",e):this:v.isFunction(e)?this.each(function(t){var n=v(this),r=n.html();n.replaceWith(e.call(this,t,r))}):(typeof e!="string"&&(e=v(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;v(this).remove(),t?v(t).before(e):v(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,s,o,u,a=0,f=e[0],l=[],c=this.length;if(!v.support.checkClone&&c>1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a<c;a++)r.call(n&&v.nodeName(this[a],"table")?Lt(this[a],"tbody"):this[a],a===u?o:v.clone(o,!0,!0))}o=s=null,l.length&&v.each(l,function(e,t){t.src?v.ajax?v.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):v.error("no ajax"):v.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Tt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),v.buildFragment=function(e,n,r){var s,o,u,a=e[0];return n=n||i,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,e.length===1&&typeof a=="string"&&a.length<512&&n===i&&a.charAt(0)==="<"&&!bt.test(a)&&(v.support.checkClone||!St.test(a))&&(v.support.html5Clone||!wt.test(a))&&(o=!0,s=v.fragments[a],u=s!==t),s||(s=n.createDocumentFragment(),v.clean(e,n,s,r),o&&(v.fragments[a]=u&&s)),{fragment:s,cacheable:o}},v.fragments={},v.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){v.fn[e]=function(n){var r,i=0,s=[],o=v(n),u=o.length,a=this.length===1&&this[0].parentNode;if((a==null||a&&a.nodeType===11&&a.childNodes.length===1)&&u===1)return o[t](this[0]),this;for(;i<u;i++)r=(i>0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1></$2>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]==="<table>"&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("<div>").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],Vn[n]=Vn[n]||[],Vn[n].unshift(t)},prefilter:function(e,t){t?Xn.unshift(e):Xn.push(e)}}),v.Tween=Yn,Yn.prototype={constructor:Yn,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(v.cssNumber[n]?"":"px")},cur:function(){var e=Yn.propHooks[this.prop];return e&&e.get?e.get(this):Yn.propHooks._default.get(this)},run:function(e){var t,n=Yn.propHooks[this.prop];return this.options.duration?this.pos=t=v.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Yn.propHooks._default.set(this),this}},Yn.prototype.init.prototype=Yn.prototype,Yn.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=v.css(e.elem,e.prop,!1,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){v.fx.step[e.prop]?v.fx.step[e.prop](e):e.elem.style&&(e.elem.style[v.cssProps[e.prop]]!=null||v.cssHooks[e.prop])?v.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Yn.propHooks.scrollTop=Yn.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},v.each(["toggle","show","hide"],function(e,t){var n=v.fn[t];v.fn[t]=function(r,i,s){return r==null||typeof r=="boolean"||!e&&v.isFunction(r)&&v.isFunction(i)?n.apply(this,arguments):this.animate(Zn(t,!0),r,i,s)}}),v.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Gt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=v.isEmptyObject(e),s=v.speed(t,n,r),o=function(){var t=Kn(this,v.extend({},e),s);i&&t.stop(!0)};return i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return typeof e!="string"&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=e!=null&&e+"queueHooks",s=v.timers,o=v._data(this);if(n)o[n]&&o[n].stop&&i(o[n]);else for(n in o)o[n]&&o[n].stop&&Wn.test(n)&&i(o[n]);for(n=s.length;n--;)s[n].elem===this&&(e==null||s[n].queue===e)&&(s[n].anim.stop(r),t=!1,s.splice(n,1));(t||!r)&&v.dequeue(this,e)})}}),v.each({slideDown:Zn("show"),slideUp:Zn("hide"),slideToggle:Zn("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){v.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),v.speed=function(e,t,n){var r=e&&typeof e=="object"?v.extend({},e):{complete:n||!n&&t||v.isFunction(e)&&e,duration:e,easing:n&&t||t&&!v.isFunction(t)&&t};r.duration=v.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in v.fx.speeds?v.fx.speeds[r.duration]:v.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){v.isFunction(r.old)&&r.old.call(this),r.queue&&v.dequeue(this,r.queue)},r},v.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},v.timers=[],v.fx=Yn.prototype.init,v.fx.tick=function(){var e,n=v.timers,r=0;qn=v.now();for(;r<n.length;r++)e=n[r],!e()&&n[r]===e&&n.splice(r--,1);n.length||v.fx.stop(),qn=t},v.fx.timer=function(e){e()&&v.timers.push(e)&&!Rn&&(Rn=setInterval(v.fx.tick,v.fx.interval))},v.fx.interval=13,v.fx.stop=function(){clearInterval(Rn),Rn=null},v.fx.speeds={slow:600,fast:200,_default:400},v.fx.step={},v.expr&&v.expr.filters&&(v.expr.filters.animated=function(e){return v.grep(v.timers,function(t){return e===t.elem}).length});var er=/^(?:body|html)$/i;v.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){v.offset.setOffset(this,e,t)});var n,r,i,s,o,u,a,f={top:0,left:0},l=this[0],c=l&&l.ownerDocument;if(!c)return;return(r=c.body)===l?v.offset.bodyOffset(l):(n=c.documentElement,v.contains(n,l)?(typeof l.getBoundingClientRect!="undefined"&&(f=l.getBoundingClientRect()),i=tr(c),s=n.clientTop||r.clientTop||0,o=n.clientLeft||r.clientLeft||0,u=i.pageYOffset||n.scrollTop,a=i.pageXOffset||n.scrollLeft,{top:f.top+u-s,left:f.left+a-o}):f)},v.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return v.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(v.css(e,"marginTop"))||0,n+=parseFloat(v.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=v.css(e,"position");r==="static"&&(e.style.position="relative");var i=v(e),s=i.offset(),o=v.css(e,"top"),u=v.css(e,"left"),a=(r==="absolute"||r==="fixed")&&v.inArray("auto",[o,u])>-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window);
test/components/AboutTest.js
unicredit/react-boilerplate
import React from 'react'; import { shallow, mount } from 'enzyme'; import { expect } from 'chai'; import About from '../../src/components/About' describe('<About />', () => { it('renders a <div>', () => { const wrapper = shallow(<About />); expect(wrapper.find('div')).to.have.length(1); }); });
src/ButtonRaised/index.js
DuckyTeam/ducky-components
import React from 'react'; import PropTypes from 'prop-types'; import Typography from '../Typography'; import classNames from 'classnames'; import styles from './styles.css'; function ButtonRaised(props) { return ( <button className={classNames(styles.raised, { [styles.darkBackground]: props.theme === 'dark', [props.className]: props.className })} disabled={Boolean(props.disabled)} onClick={props.onClick} type={props.type} > <Typography className={classNames(styles.text, { [styles.darkText]: props.theme === 'dark' })} > {props.children} </Typography> </button> ); } ButtonRaised.propTypes = { children: PropTypes.node, className: PropTypes.string, disabled: PropTypes.bool, onClick: PropTypes.func, theme: PropTypes.string, type: PropTypes.string }; export default ButtonRaised;
docs/src/pages/components/progress/LinearQuery.js
allanalexandre/material-ui
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import LinearProgress from '@material-ui/core/LinearProgress'; const useStyles = makeStyles({ root: { flexGrow: 1, }, }); function LinearQuery() { const classes = useStyles(); return ( <div className={classes.root}> <LinearProgress variant="query" /> <br /> <LinearProgress color="secondary" variant="query" /> </div> ); } export default LinearQuery;
ajax/libs/flocks.js/1.4.0/flocks.min.js
amoyeh/cdnjs
if("undefined"===typeof React)var React=require("react"); (function(){function h(a){return"[object Array]"===Object.prototype.toString.call(a)}function l(a){return"undefined"===typeof a}function v(a){return"object"!==typeof a||"[object Array]"===Object.prototype.toString.call(a)?!1:!0}function b(a,c){if("string"===typeof a)if(~"warn debug error log info exception assert".split(" ").indexOf(a,0))console[a]("Flocks2 ["+a+"] "+c.toString());else console.log("Flocks2 [Unknown level] "+c.toString());else l(d.flocks2Config)?console.log("Flocks2 pre-config ["+ a.toString()+"] "+c.toString()):d.flocks2Config.log_level>=a&&console.log("Flocks2 ["+a.toString()+"] "+c.toString())}function m(){b(3," - Flocks2 attempting update");if(!w)return b(1," x Flocks2 skipped update: root is not initialized"),null;if(n)return b(1," x Flocks2 skipped update: lock count updateBlocks is non-zero"),null;if(!x(d))return b(0," ! Flocks2 rolling back update: handler rejected propset"),d=e,null;e=d;b(3," - Flocks2 update passed");"detatched"===e.flocks2Config.target?b(3," - Flocks2 skipping render because explicitly detatched"): (b(3," - Flocks2 rendering"),React.render(React.createFactory(q)({flocks2context:d}),e.flocks2Config.target));b(3," - Flocks2 update complete; finalizing");y();return!0}function z(a,c){if("string"!==typeof a)throw c||"Argument must be a string";}function A(a,c){if(!h(a))throw c||"Argument must be an array";}function B(a,c){if(!v(a))throw c||"Argument must be a non-array object";}function C(a,c,b){var d;if(!h(a))throw"Path must be an array!";if(0===a.length)return c;if(1===a.length)return d=c[a[0]], c[a[0]]=b,d;if(-1!==["string","number"].indexOf(typeof a[0]))return d=a.splice(1,Number.MAX_VALUE),C(d,c[a[0]],b)}function D(a,c){A(a,"Flocks2 setByPathh/2 must take an array for its key");b(1,' - Flocks2 setByPath "'+a.join("|")+'"');C(a,d,c);m()}function r(a,c){b(3," - Flocks2 multi-set");if("string"===typeof a)z(a,"Flocks2 set/2 must take a string for its key"),d[a]=c,b(1,' - Flocks2 setByKey "'+a+'"'),m();else{if(h(a))return D(a,c);throw"Flocks2 set/1,2 key must be a string or an array";}} function E(a){b(3," - Flocks2 multi-get");if("string"===typeof a)return e[a];if(h(a))return t(a);throw"Flocks2 get/1 key must be a string or an array";}function J(a){return e[a]}function F(a,c){var b;if(!h(a))throw"path must be an array!";if(0===a.length)return c;if(1===a.length)return c[a[0]];if(-1!==["string","number"].indexOf(typeof a[0]))return b=a.splice(1,Number.MAX_VALUE),F(b,c[a[0]])}function t(a){return F(a,e)}function G(a){console.log("ERROR: stub called!");B(a,"Flocks2 update/1 must take a plain object")} function K(){++n}function H(){if(0>=n)throw"unlock()ed with no lock!";--n;m()}function u(a){var c=a.constructor(),b;if(null===a||"object"!==typeof a)return a;for(b in a)a.hasOwnProperty(b)&&(c[b]=a[b]);return c}function I(a){if(l(a))return[p];if(h(a)){if(~a.indexOf(p,0))return a;a=u(a);a.push(p);return a}throw"Original mixin list must be an array or undefined!";}var p,k,w=!1,n=0,q,x=function(a){return!0},y=function(){return!0},e={},d={};k={flocks2context:React.PropTypes.object};p={contextTypes:k, childContextTypes:k,componentWillMount:function(){b(1," - Flocks2 component will mount: "+this.constructor.displayName);b(3,l(this.props.flocks2context)?" - No F2 Context Prop":" - F2 Context Prop found");b(3,l(this.context.flocks2context)?" - No F2 Context":" - F2 Context found");this.props.flocks2context&&(this.context.flocks2context=this.props.flocks2context);this.fupdate=function(a){return G(a)};this.fget=function(a){return E(a)};this.fgetkey=function(a){return e[a]};this.fgetpath=function(a){return t(a)}; this.fset=function(a,b){return r(a,b)};this.fsetpath=function(a,b){return r(a,b)};this.flock=function(){++n};this.funlock=function(){return H()};this.fctx=this.context.flocks2context},getChildContext:function(){return this.context}};k={version:"1.4.0",createClass:function(a){a.mixins=I(a.mixins);return React.createClass(a)},mount:function(a,c){var g=a||{},e=c||{},f=function(){console.log("ERROR: stub called!");m()},f={override:f,clear:f,get:E,get_key:J,get_path:t,set:r,set_path:D,update:G,lock:K, unlock:H};g.log_level=g.log_level||-1;q=g.control;e.flocks2Config=g;d=e;b(1,"Flocks2 root creation begins");if(!q)throw"Flocks2 fatal error: must provide a control in create/2 FlocksConfig";g.handler&&(x=g.handler,b(3," - Flocks2 handler assigned"));g.finalizer&&(y=g.finalizer,b(3," - Flocks2 finalizer assigned"));g.preventAutoContext?b(2," - Flocks2 skipping auto-context"):(b(2," - Flocks2 engaging auto-context"),this.fctx=u(d));b(3,"Flocks2 creation finished; initializing");w=!0;m();b(3,"Flocks2 expose updater"); this.fupd=f;this.fset=f.set;this.fgetkey=f.get_key;this.fgetpath=f.get_path;this.flock=f.lock;this.funlock=f.unlock;this.fupdate=f.update;b(3,"Flocks2 initialization finished");return f},clone:u,isArray:h,isUndefined:l,isNonArrayObject:v,enforceString:z,enforceArray:A,enforceNonArrayObject:B,atLeastFlocks:I,plumbing:p};"undefined"!==typeof module?module.exports=k:window.flocks=k})();
src/webpack-demos/demo15/App.js
atlantis1024/webpack-notes
import React, { Component } from 'react'; export default class App extends Component { render() { return ( <h1>Hello World</h1> ); } }
misc/jquery.js
ekilfeather/open-storyscope
/*! * jQuery JavaScript Library v1.4.4 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu Nov 11 19:04:53 2010 -0500 */ (function(E,B){function ka(a,b,d){if(d===B&&a.nodeType===1){d=a.getAttribute("data-"+b);if(typeof d==="string"){try{d=d==="true"?true:d==="false"?false:d==="null"?null:!c.isNaN(d)?parseFloat(d):Ja.test(d)?c.parseJSON(d):d}catch(e){}c.data(a,b,d)}else d=B}return d}function U(){return false}function ca(){return true}function la(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function Ka(a){var b,d,e,f,h,l,k,o,x,r,A,C=[];f=[];h=c.data(this,this.nodeType?"events":"__events__");if(typeof h==="function")h= h.events;if(!(a.liveFired===this||!h||!h.live||a.button&&a.type==="click")){if(a.namespace)A=RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)");a.liveFired=this;var J=h.live.slice(0);for(k=0;k<J.length;k++){h=J[k];h.origType.replace(X,"")===a.type?f.push(h.selector):J.splice(k--,1)}f=c(a.target).closest(f,a.currentTarget);o=0;for(x=f.length;o<x;o++){r=f[o];for(k=0;k<J.length;k++){h=J[k];if(r.selector===h.selector&&(!A||A.test(h.namespace))){l=r.elem;e=null;if(h.preType==="mouseenter"|| h.preType==="mouseleave"){a.type=h.preType;e=c(a.relatedTarget).closest(h.selector)[0]}if(!e||e!==l)C.push({elem:l,handleObj:h,level:r.level})}}}o=0;for(x=C.length;o<x;o++){f=C[o];if(d&&f.level>d)break;a.currentTarget=f.elem;a.data=f.handleObj.data;a.handleObj=f.handleObj;A=f.handleObj.origHandler.apply(f.elem,arguments);if(A===false||a.isPropagationStopped()){d=f.level;if(A===false)b=false;if(a.isImmediatePropagationStopped())break}}return b}}function Y(a,b){return(a&&a!=="*"?a+".":"")+b.replace(La, "`").replace(Ma,"&")}function ma(a,b,d){if(c.isFunction(b))return c.grep(a,function(f,h){return!!b.call(f,h,f)===d});else if(b.nodeType)return c.grep(a,function(f){return f===b===d});else if(typeof b==="string"){var e=c.grep(a,function(f){return f.nodeType===1});if(Na.test(b))return c.filter(b,e,!d);else b=c.filter(b,e)}return c.grep(a,function(f){return c.inArray(f,b)>=0===d})}function na(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var e=c.data(a[d++]),f=c.data(this, e);if(e=e&&e.events){delete f.handle;f.events={};for(var h in e)for(var l in e[h])c.event.add(this,h,e[h][l],e[h][l].data)}}})}function Oa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function oa(a,b,d){var e=b==="width"?a.offsetWidth:a.offsetHeight;if(d==="border")return e;c.each(b==="width"?Pa:Qa,function(){d||(e-=parseFloat(c.css(a,"padding"+this))||0);if(d==="margin")e+=parseFloat(c.css(a, "margin"+this))||0;else e-=parseFloat(c.css(a,"border"+this+"Width"))||0});return e}function da(a,b,d,e){if(c.isArray(b)&&b.length)c.each(b,function(f,h){d||Ra.test(a)?e(a,h):da(a+"["+(typeof h==="object"||c.isArray(h)?f:"")+"]",h,d,e)});else if(!d&&b!=null&&typeof b==="object")c.isEmptyObject(b)?e(a,""):c.each(b,function(f,h){da(a+"["+f+"]",h,d,e)});else e(a,b)}function S(a,b){var d={};c.each(pa.concat.apply([],pa.slice(0,b)),function(){d[this]=a});return d}function qa(a){if(!ea[a]){var b=c("<"+ a+">").appendTo("body"),d=b.css("display");b.remove();if(d==="none"||d==="")d="block";ea[a]=d}return ea[a]}function fa(a){return c.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var t=E.document,c=function(){function a(){if(!b.isReady){try{t.documentElement.doScroll("left")}catch(j){setTimeout(a,1);return}b.ready()}}var b=function(j,s){return new b.fn.init(j,s)},d=E.jQuery,e=E.$,f,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,l=/\S/,k=/^\s+/,o=/\s+$/,x=/\W/,r=/\d/,A=/^<(\w+)\s*\/?>(?:<\/\1>)?$/, C=/^[\],:{}\s]*$/,J=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,w=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,I=/(?:^|:|,)(?:\s*\[)+/g,L=/(webkit)[ \/]([\w.]+)/,g=/(opera)(?:.*version)?[ \/]([\w.]+)/,i=/(msie) ([\w.]+)/,n=/(mozilla)(?:.*? rv:([\w.]+))?/,m=navigator.userAgent,p=false,q=[],u,y=Object.prototype.toString,F=Object.prototype.hasOwnProperty,M=Array.prototype.push,N=Array.prototype.slice,O=String.prototype.trim,D=Array.prototype.indexOf,R={};b.fn=b.prototype={init:function(j, s){var v,z,H;if(!j)return this;if(j.nodeType){this.context=this[0]=j;this.length=1;return this}if(j==="body"&&!s&&t.body){this.context=t;this[0]=t.body;this.selector="body";this.length=1;return this}if(typeof j==="string")if((v=h.exec(j))&&(v[1]||!s))if(v[1]){H=s?s.ownerDocument||s:t;if(z=A.exec(j))if(b.isPlainObject(s)){j=[t.createElement(z[1])];b.fn.attr.call(j,s,true)}else j=[H.createElement(z[1])];else{z=b.buildFragment([v[1]],[H]);j=(z.cacheable?z.fragment.cloneNode(true):z.fragment).childNodes}return b.merge(this, j)}else{if((z=t.getElementById(v[2]))&&z.parentNode){if(z.id!==v[2])return f.find(j);this.length=1;this[0]=z}this.context=t;this.selector=j;return this}else if(!s&&!x.test(j)){this.selector=j;this.context=t;j=t.getElementsByTagName(j);return b.merge(this,j)}else return!s||s.jquery?(s||f).find(j):b(s).find(j);else if(b.isFunction(j))return f.ready(j);if(j.selector!==B){this.selector=j.selector;this.context=j.context}return b.makeArray(j,this)},selector:"",jquery:"1.4.4",length:0,size:function(){return this.length}, toArray:function(){return N.call(this,0)},get:function(j){return j==null?this.toArray():j<0?this.slice(j)[0]:this[j]},pushStack:function(j,s,v){var z=b();b.isArray(j)?M.apply(z,j):b.merge(z,j);z.prevObject=this;z.context=this.context;if(s==="find")z.selector=this.selector+(this.selector?" ":"")+v;else if(s)z.selector=this.selector+"."+s+"("+v+")";return z},each:function(j,s){return b.each(this,j,s)},ready:function(j){b.bindReady();if(b.isReady)j.call(t,b);else q&&q.push(j);return this},eq:function(j){return j=== -1?this.slice(j):this.slice(j,+j+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(N.apply(this,arguments),"slice",N.call(arguments).join(","))},map:function(j){return this.pushStack(b.map(this,function(s,v){return j.call(s,v,s)}))},end:function(){return this.prevObject||b(null)},push:M,sort:[].sort,splice:[].splice};b.fn.init.prototype=b.fn;b.extend=b.fn.extend=function(){var j,s,v,z,H,G=arguments[0]||{},K=1,Q=arguments.length,ga=false; if(typeof G==="boolean"){ga=G;G=arguments[1]||{};K=2}if(typeof G!=="object"&&!b.isFunction(G))G={};if(Q===K){G=this;--K}for(;K<Q;K++)if((j=arguments[K])!=null)for(s in j){v=G[s];z=j[s];if(G!==z)if(ga&&z&&(b.isPlainObject(z)||(H=b.isArray(z)))){if(H){H=false;v=v&&b.isArray(v)?v:[]}else v=v&&b.isPlainObject(v)?v:{};G[s]=b.extend(ga,v,z)}else if(z!==B)G[s]=z}return G};b.extend({noConflict:function(j){E.$=e;if(j)E.jQuery=d;return b},isReady:false,readyWait:1,ready:function(j){j===true&&b.readyWait--; if(!b.readyWait||j!==true&&!b.isReady){if(!t.body)return setTimeout(b.ready,1);b.isReady=true;if(!(j!==true&&--b.readyWait>0))if(q){var s=0,v=q;for(q=null;j=v[s++];)j.call(t,b);b.fn.trigger&&b(t).trigger("ready").unbind("ready")}}},bindReady:function(){if(!p){p=true;if(t.readyState==="complete")return setTimeout(b.ready,1);if(t.addEventListener){t.addEventListener("DOMContentLoaded",u,false);E.addEventListener("load",b.ready,false)}else if(t.attachEvent){t.attachEvent("onreadystatechange",u);E.attachEvent("onload", b.ready);var j=false;try{j=E.frameElement==null}catch(s){}t.documentElement.doScroll&&j&&a()}}},isFunction:function(j){return b.type(j)==="function"},isArray:Array.isArray||function(j){return b.type(j)==="array"},isWindow:function(j){return j&&typeof j==="object"&&"setInterval"in j},isNaN:function(j){return j==null||!r.test(j)||isNaN(j)},type:function(j){return j==null?String(j):R[y.call(j)]||"object"},isPlainObject:function(j){if(!j||b.type(j)!=="object"||j.nodeType||b.isWindow(j))return false;if(j.constructor&& !F.call(j,"constructor")&&!F.call(j.constructor.prototype,"isPrototypeOf"))return false;for(var s in j);return s===B||F.call(j,s)},isEmptyObject:function(j){for(var s in j)return false;return true},error:function(j){throw j;},parseJSON:function(j){if(typeof j!=="string"||!j)return null;j=b.trim(j);if(C.test(j.replace(J,"@").replace(w,"]").replace(I,"")))return E.JSON&&E.JSON.parse?E.JSON.parse(j):(new Function("return "+j))();else b.error("Invalid JSON: "+j)},noop:function(){},globalEval:function(j){if(j&& l.test(j)){var s=t.getElementsByTagName("head")[0]||t.documentElement,v=t.createElement("script");v.type="text/javascript";if(b.support.scriptEval)v.appendChild(t.createTextNode(j));else v.text=j;s.insertBefore(v,s.firstChild);s.removeChild(v)}},nodeName:function(j,s){return j.nodeName&&j.nodeName.toUpperCase()===s.toUpperCase()},each:function(j,s,v){var z,H=0,G=j.length,K=G===B||b.isFunction(j);if(v)if(K)for(z in j){if(s.apply(j[z],v)===false)break}else for(;H<G;){if(s.apply(j[H++],v)===false)break}else if(K)for(z in j){if(s.call(j[z], z,j[z])===false)break}else for(v=j[0];H<G&&s.call(v,H,v)!==false;v=j[++H]);return j},trim:O?function(j){return j==null?"":O.call(j)}:function(j){return j==null?"":j.toString().replace(k,"").replace(o,"")},makeArray:function(j,s){var v=s||[];if(j!=null){var z=b.type(j);j.length==null||z==="string"||z==="function"||z==="regexp"||b.isWindow(j)?M.call(v,j):b.merge(v,j)}return v},inArray:function(j,s){if(s.indexOf)return s.indexOf(j);for(var v=0,z=s.length;v<z;v++)if(s[v]===j)return v;return-1},merge:function(j, s){var v=j.length,z=0;if(typeof s.length==="number")for(var H=s.length;z<H;z++)j[v++]=s[z];else for(;s[z]!==B;)j[v++]=s[z++];j.length=v;return j},grep:function(j,s,v){var z=[],H;v=!!v;for(var G=0,K=j.length;G<K;G++){H=!!s(j[G],G);v!==H&&z.push(j[G])}return z},map:function(j,s,v){for(var z=[],H,G=0,K=j.length;G<K;G++){H=s(j[G],G,v);if(H!=null)z[z.length]=H}return z.concat.apply([],z)},guid:1,proxy:function(j,s,v){if(arguments.length===2)if(typeof s==="string"){v=j;j=v[s];s=B}else if(s&&!b.isFunction(s)){v= s;s=B}if(!s&&j)s=function(){return j.apply(v||this,arguments)};if(j)s.guid=j.guid=j.guid||s.guid||b.guid++;return s},access:function(j,s,v,z,H,G){var K=j.length;if(typeof s==="object"){for(var Q in s)b.access(j,Q,s[Q],z,H,v);return j}if(v!==B){z=!G&&z&&b.isFunction(v);for(Q=0;Q<K;Q++)H(j[Q],s,z?v.call(j[Q],Q,H(j[Q],s)):v,G);return j}return K?H(j[0],s):B},now:function(){return(new Date).getTime()},uaMatch:function(j){j=j.toLowerCase();j=L.exec(j)||g.exec(j)||i.exec(j)||j.indexOf("compatible")<0&&n.exec(j)|| [];return{browser:j[1]||"",version:j[2]||"0"}},browser:{}});b.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(j,s){R["[object "+s+"]"]=s.toLowerCase()});m=b.uaMatch(m);if(m.browser){b.browser[m.browser]=true;b.browser.version=m.version}if(b.browser.webkit)b.browser.safari=true;if(D)b.inArray=function(j,s){return D.call(s,j)};if(!/\s/.test("\u00a0")){k=/^[\s\xA0]+/;o=/[\s\xA0]+$/}f=b(t);if(t.addEventListener)u=function(){t.removeEventListener("DOMContentLoaded",u, false);b.ready()};else if(t.attachEvent)u=function(){if(t.readyState==="complete"){t.detachEvent("onreadystatechange",u);b.ready()}};return E.jQuery=E.$=b}();(function(){c.support={};var a=t.documentElement,b=t.createElement("script"),d=t.createElement("div"),e="script"+c.now();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var f=d.getElementsByTagName("*"),h=d.getElementsByTagName("a")[0],l=t.createElement("select"), k=l.appendChild(t.createElement("option"));if(!(!f||!f.length||!h)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(h.getAttribute("style")),hrefNormalized:h.getAttribute("href")==="/a",opacity:/^0.55$/.test(h.style.opacity),cssFloat:!!h.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:k.selected,deleteExpando:true,optDisabled:false,checkClone:false, scriptEval:false,noCloneEvent:true,boxModel:null,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableHiddenOffsets:true};l.disabled=true;c.support.optDisabled=!k.disabled;b.type="text/javascript";try{b.appendChild(t.createTextNode("window."+e+"=1;"))}catch(o){}a.insertBefore(b,a.firstChild);if(E[e]){c.support.scriptEval=true;delete E[e]}try{delete b.test}catch(x){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function r(){c.support.noCloneEvent= false;d.detachEvent("onclick",r)});d.cloneNode(true).fireEvent("onclick")}d=t.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=t.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var r=t.createElement("div");r.style.width=r.style.paddingLeft="1px";t.body.appendChild(r);c.boxModel=c.support.boxModel=r.offsetWidth===2;if("zoom"in r.style){r.style.display="inline";r.style.zoom= 1;c.support.inlineBlockNeedsLayout=r.offsetWidth===2;r.style.display="";r.innerHTML="<div style='width:4px;'></div>";c.support.shrinkWrapBlocks=r.offsetWidth!==2}r.innerHTML="<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";var A=r.getElementsByTagName("td");c.support.reliableHiddenOffsets=A[0].offsetHeight===0;A[0].style.display="";A[1].style.display="none";c.support.reliableHiddenOffsets=c.support.reliableHiddenOffsets&&A[0].offsetHeight===0;r.innerHTML="";t.body.removeChild(r).style.display= "none"});a=function(r){var A=t.createElement("div");r="on"+r;var C=r in A;if(!C){A.setAttribute(r,"return;");C=typeof A[r]==="function"}return C};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=f=h=null}})();var ra={},Ja=/^(?:\{.*\}|\[.*\])$/;c.extend({cache:{},uuid:0,expando:"jQuery"+c.now(),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},data:function(a,b,d){if(c.acceptData(a)){a=a==E?ra:a;var e=a.nodeType,f=e?a[c.expando]:null,h= c.cache;if(!(e&&!f&&typeof b==="string"&&d===B)){if(e)f||(a[c.expando]=f=++c.uuid);else h=a;if(typeof b==="object")if(e)h[f]=c.extend(h[f],b);else c.extend(h,b);else if(e&&!h[f])h[f]={};a=e?h[f]:h;if(d!==B)a[b]=d;return typeof b==="string"?a[b]:a}}},removeData:function(a,b){if(c.acceptData(a)){a=a==E?ra:a;var d=a.nodeType,e=d?a[c.expando]:a,f=c.cache,h=d?f[e]:e;if(b){if(h){delete h[b];d&&c.isEmptyObject(h)&&c.removeData(a)}}else if(d&&c.support.deleteExpando)delete a[c.expando];else if(a.removeAttribute)a.removeAttribute(c.expando); else if(d)delete f[e];else for(var l in a)delete a[l]}},acceptData:function(a){if(a.nodeName){var b=c.noData[a.nodeName.toLowerCase()];if(b)return!(b===true||a.getAttribute("classid")!==b)}return true}});c.fn.extend({data:function(a,b){var d=null;if(typeof a==="undefined"){if(this.length){var e=this[0].attributes,f;d=c.data(this[0]);for(var h=0,l=e.length;h<l;h++){f=e[h].name;if(f.indexOf("data-")===0){f=f.substr(5);ka(this[0],f,d[f])}}}return d}else if(typeof a==="object")return this.each(function(){c.data(this, a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(b===B){d=this.triggerHandler("getData"+k[1]+"!",[k[0]]);if(d===B&&this.length){d=c.data(this[0],a);d=ka(this[0],a,d)}return d===B&&k[1]?this.data(k[0]):d}else return this.each(function(){var o=c(this),x=[k[0],b];o.triggerHandler("setData"+k[1]+"!",x);c.data(this,a,b);o.triggerHandler("changeData"+k[1]+"!",x)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var e= c.data(a,b);if(!d)return e||[];if(!e||c.isArray(d))e=c.data(a,b,c.makeArray(d));else e.push(d);return e}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),e=d.shift();if(e==="inprogress")e=d.shift();if(e){b==="fx"&&d.unshift("inprogress");e.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===B)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this, a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var sa=/[\n\t]/g,ha=/\s+/,Sa=/\r/g,Ta=/^(?:href|src|style)$/,Ua=/^(?:button|input)$/i,Va=/^(?:button|input|object|select|textarea)$/i,Wa=/^a(?:rea)?$/i,ta=/^(?:radio|checkbox)$/i;c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan", colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};c.fn.extend({attr:function(a,b){return c.access(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(x){var r=c(this);r.addClass(a.call(this,x,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType=== 1)if(f.className){for(var h=" "+f.className+" ",l=f.className,k=0,o=b.length;k<o;k++)if(h.indexOf(" "+b[k]+" ")<0)l+=" "+b[k];f.className=c.trim(l)}else f.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(o){var x=c(this);x.removeClass(a.call(this,o,x.attr("class")))});if(a&&typeof a==="string"||a===B)for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===1&&f.className)if(a){for(var h=(" "+f.className+" ").replace(sa," "), l=0,k=b.length;l<k;l++)h=h.replace(" "+b[l]+" "," ");f.className=c.trim(h)}else f.className=""}return this},toggleClass:function(a,b){var d=typeof a,e=typeof b==="boolean";if(c.isFunction(a))return this.each(function(f){var h=c(this);h.toggleClass(a.call(this,f,h.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var f,h=0,l=c(this),k=b,o=a.split(ha);f=o[h++];){k=e?k:!l.hasClass(f);l[k?"addClass":"removeClass"](f)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this, "__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(sa," ").indexOf(a)>-1)return true;return false},val:function(a){if(!arguments.length){var b=this[0];if(b){if(c.nodeName(b,"option")){var d=b.attributes.value;return!d||d.specified?b.value:b.text}if(c.nodeName(b,"select")){var e=b.selectedIndex;d=[];var f=b.options;b=b.type==="select-one"; if(e<0)return null;var h=b?e:0;for(e=b?e+1:f.length;h<e;h++){var l=f[h];if(l.selected&&(c.support.optDisabled?!l.disabled:l.getAttribute("disabled")===null)&&(!l.parentNode.disabled||!c.nodeName(l.parentNode,"optgroup"))){a=c(l).val();if(b)return a;d.push(a)}}return d}if(ta.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Sa,"")}return B}var k=c.isFunction(a);return this.each(function(o){var x=c(this),r=a;if(this.nodeType===1){if(k)r= a.call(this,o,x.val());if(r==null)r="";else if(typeof r==="number")r+="";else if(c.isArray(r))r=c.map(r,function(C){return C==null?"":C+""});if(c.isArray(r)&&ta.test(this.type))this.checked=c.inArray(x.val(),r)>=0;else if(c.nodeName(this,"select")){var A=c.makeArray(r);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),A)>=0});if(!A.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true}, attr:function(a,b,d,e){if(!a||a.nodeType===3||a.nodeType===8)return B;if(e&&b in c.attrFn)return c(a)[b](d);e=a.nodeType!==1||!c.isXMLDoc(a);var f=d!==B;b=e&&c.props[b]||b;var h=Ta.test(b);if((b in a||a[b]!==B)&&e&&!h){if(f){b==="type"&&Ua.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");if(d===null)a.nodeType===1&&a.removeAttribute(b);else a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&& b.specified?b.value:Va.test(a.nodeName)||Wa.test(a.nodeName)&&a.href?0:B;return a[b]}if(!c.support.style&&e&&b==="style"){if(f)a.style.cssText=""+d;return a.style.cssText}f&&a.setAttribute(b,""+d);if(!a.attributes[b]&&a.hasAttribute&&!a.hasAttribute(b))return B;a=!c.support.hrefNormalized&&e&&h?a.getAttribute(b,2):a.getAttribute(b);return a===null?B:a}});var X=/\.(.*)$/,ia=/^(?:textarea|input|select)$/i,La=/\./g,Ma=/ /g,Xa=/[^\w\s.|`]/g,Ya=function(a){return a.replace(Xa,"\\$&")},ua={focusin:0,focusout:0}; c.event={add:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(c.isWindow(a)&&a!==E&&!a.frameElement)a=E;if(d===false)d=U;else if(!d)return;var f,h;if(d.handler){f=d;d=f.handler}if(!d.guid)d.guid=c.guid++;if(h=c.data(a)){var l=a.nodeType?"events":"__events__",k=h[l],o=h.handle;if(typeof k==="function"){o=k.handle;k=k.events}else if(!k){a.nodeType||(h[l]=h=function(){});h.events=k={}}if(!o)h.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem, arguments):B};o.elem=a;b=b.split(" ");for(var x=0,r;l=b[x++];){h=f?c.extend({},f):{handler:d,data:e};if(l.indexOf(".")>-1){r=l.split(".");l=r.shift();h.namespace=r.slice(0).sort().join(".")}else{r=[];h.namespace=""}h.type=l;if(!h.guid)h.guid=d.guid;var A=k[l],C=c.event.special[l]||{};if(!A){A=k[l]=[];if(!C.setup||C.setup.call(a,e,r,o)===false)if(a.addEventListener)a.addEventListener(l,o,false);else a.attachEvent&&a.attachEvent("on"+l,o)}if(C.add){C.add.call(a,h);if(!h.handler.guid)h.handler.guid= d.guid}A.push(h);c.event.global[l]=true}a=null}}},global:{},remove:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(d===false)d=U;var f,h,l=0,k,o,x,r,A,C,J=a.nodeType?"events":"__events__",w=c.data(a),I=w&&w[J];if(w&&I){if(typeof I==="function"){w=I;I=I.events}if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(f in I)c.event.remove(a,f+b)}else{for(b=b.split(" ");f=b[l++];){r=f;k=f.indexOf(".")<0;o=[];if(!k){o=f.split(".");f=o.shift();x=RegExp("(^|\\.)"+ c.map(o.slice(0).sort(),Ya).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(A=I[f])if(d){r=c.event.special[f]||{};for(h=e||0;h<A.length;h++){C=A[h];if(d.guid===C.guid){if(k||x.test(C.namespace)){e==null&&A.splice(h--,1);r.remove&&r.remove.call(a,C)}if(e!=null)break}}if(A.length===0||e!=null&&A.length===1){if(!r.teardown||r.teardown.call(a,o)===false)c.removeEvent(a,f,w.handle);delete I[f]}}else for(h=0;h<A.length;h++){C=A[h];if(k||x.test(C.namespace)){c.event.remove(a,r,C.handler,h);A.splice(h--,1)}}}if(c.isEmptyObject(I)){if(b= w.handle)b.elem=null;delete w.events;delete w.handle;if(typeof w==="function")c.removeData(a,J);else c.isEmptyObject(w)&&c.removeData(a)}}}}},trigger:function(a,b,d,e){var f=a.type||a;if(!e){a=typeof a==="object"?a[c.expando]?a:c.extend(c.Event(f),a):c.Event(f);if(f.indexOf("!")>=0){a.type=f=f.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[f]&&c.each(c.cache,function(){this.events&&this.events[f]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType=== 8)return B;a.result=B;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(e=d.nodeType?c.data(d,"handle"):(c.data(d,"__events__")||{}).handle)&&e.apply(d,b);e=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+f]&&d["on"+f].apply(d,b)===false){a.result=false;a.preventDefault()}}catch(h){}if(!a.isPropagationStopped()&&e)c.event.trigger(a,b,e,true);else if(!a.isDefaultPrevented()){var l;e=a.target;var k=f.replace(X,""),o=c.nodeName(e,"a")&&k=== "click",x=c.event.special[k]||{};if((!x._default||x._default.call(d,a)===false)&&!o&&!(e&&e.nodeName&&c.noData[e.nodeName.toLowerCase()])){try{if(e[k]){if(l=e["on"+k])e["on"+k]=null;c.event.triggered=true;e[k]()}}catch(r){}if(l)e["on"+k]=l;c.event.triggered=false}}},handle:function(a){var b,d,e,f;d=[];var h=c.makeArray(arguments);a=h[0]=c.event.fix(a||E.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;if(!b){e=a.type.split(".");a.type=e.shift();d=e.slice(0).sort();e=RegExp("(^|\\.)"+ d.join("\\.(?:.*\\.)?")+"(\\.|$)")}a.namespace=a.namespace||d.join(".");f=c.data(this,this.nodeType?"events":"__events__");if(typeof f==="function")f=f.events;d=(f||{})[a.type];if(f&&d){d=d.slice(0);f=0;for(var l=d.length;f<l;f++){var k=d[f];if(b||e.test(k.namespace)){a.handler=k.handler;a.data=k.data;a.handleObj=k;k=k.handler.apply(this,h);if(k!==B){a.result=k;if(k===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix:function(a){if(a[c.expando])return a;var b=a;a=c.Event(b);for(var d=this.props.length,e;d;){e=this.props[--d];a[e]=b[e]}if(!a.target)a.target=a.srcElement||t;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=t.documentElement;d=t.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop|| d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(a.which==null&&(a.charCode!=null||a.keyCode!=null))a.which=a.charCode!=null?a.charCode:a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==B)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,Y(a.origType,a.selector),c.extend({},a,{handler:Ka,guid:a.handler.guid}))},remove:function(a){c.event.remove(this, Y(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,d){if(c.isWindow(this))this.onbeforeunload=d},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.removeEvent=t.removeEventListener?function(a,b,d){a.removeEventListener&&a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent&&a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp= c.now();this[c.expando]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=ca;var a=this.originalEvent;if(a)if(a.preventDefault)a.preventDefault();else a.returnValue=false},stopPropagation:function(){this.isPropagationStopped=ca;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=ca;this.stopPropagation()},isDefaultPrevented:U,isPropagationStopped:U,isImmediatePropagationStopped:U}; var va=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},wa=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?wa:va,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?wa:va)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(){if(this.nodeName.toLowerCase()!== "form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length){a.liveFired=B;return la("submit",this,arguments)}});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13){a.liveFired=B;return la("submit",this,arguments)}})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};if(!c.support.changeBubbles){var V, xa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(e){return e.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},Z=function(a,b){var d=a.target,e,f;if(!(!ia.test(d.nodeName)||d.readOnly)){e=c.data(d,"_change_data");f=xa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",f);if(!(e===B||f===e))if(e!=null||f){a.type="change";a.liveFired= B;return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:Z,beforedeactivate:Z,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return Z.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return Z.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,"_change_data",xa(a))}},setup:function(){if(this.type=== "file")return false;for(var a in V)c.event.add(this,a+".specialChange",V[a]);return ia.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return ia.test(this.nodeName)}};V=c.event.special.change.filters;V.focus=V.beforeactivate}t.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.trigger(e,null,e.target)}c.event.special[b]={setup:function(){ua[b]++===0&&t.addEventListener(a,d,true)},teardown:function(){--ua[b]=== 0&&t.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,e,f){if(typeof d==="object"){for(var h in d)this[b](h,e,d[h],f);return this}if(c.isFunction(e)||e===false){f=e;e=B}var l=b==="one"?c.proxy(f,function(o){c(this).unbind(o,l);return f.apply(this,arguments)}):f;if(d==="unload"&&b!=="one")this.one(d,e,f);else{h=0;for(var k=this.length;h<k;h++)c.event.add(this[h],d,l,e)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&!a.preventDefault)for(var d in a)this.unbind(d, a[d]);else{d=0;for(var e=this.length;d<e;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,e){return this.live(b,d,e,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var d=c.Event(a);d.preventDefault();d.stopPropagation();c.event.trigger(d,b,this[0]);return d.result}},toggle:function(a){for(var b=arguments,d= 1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(e){var f=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,f+1);e.preventDefault();return b[f].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var ya={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,e,f,h){var l,k=0,o,x,r=h||this.selector;h=h?this:c(this.context);if(typeof d=== "object"&&!d.preventDefault){for(l in d)h[b](l,e,d[l],r);return this}if(c.isFunction(e)){f=e;e=B}for(d=(d||"").split(" ");(l=d[k++])!=null;){o=X.exec(l);x="";if(o){x=o[0];l=l.replace(X,"")}if(l==="hover")d.push("mouseenter"+x,"mouseleave"+x);else{o=l;if(l==="focus"||l==="blur"){d.push(ya[l]+x);l+=x}else l=(ya[l]||l)+x;if(b==="live"){x=0;for(var A=h.length;x<A;x++)c.event.add(h[x],"live."+Y(l,r),{data:e,selector:r,handler:f,origType:l,origHandler:f,preType:o})}else h.unbind("live."+Y(l,r),f)}}return this}}); c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){c.fn[b]=function(d,e){if(e==null){e=d;d=null}return arguments.length>0?this.bind(b,d,e):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});E.attachEvent&&!E.addEventListener&&c(E).bind("unload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}}); (function(){function a(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1&&!q){y.sizcache=n;y.sizset=p}if(y.nodeName.toLowerCase()===i){F=y;break}y=y[g]}m[p]=F}}}function b(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1){if(!q){y.sizcache=n;y.sizset=p}if(typeof i!=="string"){if(y===i){F=true;break}}else if(k.filter(i, [y]).length>0){F=y;break}}y=y[g]}m[p]=F}}}var d=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,h=false,l=true;[0,0].sort(function(){l=false;return 0});var k=function(g,i,n,m){n=n||[];var p=i=i||t;if(i.nodeType!==1&&i.nodeType!==9)return[];if(!g||typeof g!=="string")return n;var q,u,y,F,M,N=true,O=k.isXML(i),D=[],R=g;do{d.exec("");if(q=d.exec(R)){R=q[3];D.push(q[1]);if(q[2]){F=q[3]; break}}}while(q);if(D.length>1&&x.exec(g))if(D.length===2&&o.relative[D[0]])u=L(D[0]+D[1],i);else for(u=o.relative[D[0]]?[i]:k(D.shift(),i);D.length;){g=D.shift();if(o.relative[g])g+=D.shift();u=L(g,u)}else{if(!m&&D.length>1&&i.nodeType===9&&!O&&o.match.ID.test(D[0])&&!o.match.ID.test(D[D.length-1])){q=k.find(D.shift(),i,O);i=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]}if(i){q=m?{expr:D.pop(),set:C(m)}:k.find(D.pop(),D.length===1&&(D[0]==="~"||D[0]==="+")&&i.parentNode?i.parentNode:i,O);u=q.expr?k.filter(q.expr, q.set):q.set;if(D.length>0)y=C(u);else N=false;for(;D.length;){q=M=D.pop();if(o.relative[M])q=D.pop();else M="";if(q==null)q=i;o.relative[M](y,q,O)}}else y=[]}y||(y=u);y||k.error(M||g);if(f.call(y)==="[object Array]")if(N)if(i&&i.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&k.contains(i,y[g])))n.push(u[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&n.push(u[g]);else n.push.apply(n,y);else C(y,n);if(F){k(F,p,n,m);k.uniqueSort(n)}return n};k.uniqueSort=function(g){if(w){h= l;g.sort(w);if(h)for(var i=1;i<g.length;i++)g[i]===g[i-1]&&g.splice(i--,1)}return g};k.matches=function(g,i){return k(g,null,null,i)};k.matchesSelector=function(g,i){return k(i,null,null,[g]).length>0};k.find=function(g,i,n){var m;if(!g)return[];for(var p=0,q=o.order.length;p<q;p++){var u,y=o.order[p];if(u=o.leftMatch[y].exec(g)){var F=u[1];u.splice(1,1);if(F.substr(F.length-1)!=="\\"){u[1]=(u[1]||"").replace(/\\/g,"");m=o.find[y](u,i,n);if(m!=null){g=g.replace(o.match[y],"");break}}}}m||(m=i.getElementsByTagName("*")); return{set:m,expr:g}};k.filter=function(g,i,n,m){for(var p,q,u=g,y=[],F=i,M=i&&i[0]&&k.isXML(i[0]);g&&i.length;){for(var N in o.filter)if((p=o.leftMatch[N].exec(g))!=null&&p[2]){var O,D,R=o.filter[N];D=p[1];q=false;p.splice(1,1);if(D.substr(D.length-1)!=="\\"){if(F===y)y=[];if(o.preFilter[N])if(p=o.preFilter[N](p,F,n,y,m,M)){if(p===true)continue}else q=O=true;if(p)for(var j=0;(D=F[j])!=null;j++)if(D){O=R(D,p,j,F);var s=m^!!O;if(n&&O!=null)if(s)q=true;else F[j]=false;else if(s){y.push(D);q=true}}if(O!== B){n||(F=y);g=g.replace(o.match[N],"");if(!q)return[];break}}}if(g===u)if(q==null)k.error(g);else break;u=g}return F};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var o=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/, POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},relative:{"+":function(g,i){var n=typeof i==="string",m=n&&!/\W/.test(i);n=n&&!m;if(m)i=i.toLowerCase();m=0;for(var p=g.length,q;m<p;m++)if(q=g[m]){for(;(q=q.previousSibling)&&q.nodeType!==1;);g[m]=n||q&&q.nodeName.toLowerCase()=== i?q||false:q===i}n&&k.filter(i,g,true)},">":function(g,i){var n,m=typeof i==="string",p=0,q=g.length;if(m&&!/\W/.test(i))for(i=i.toLowerCase();p<q;p++){if(n=g[p]){n=n.parentNode;g[p]=n.nodeName.toLowerCase()===i?n:false}}else{for(;p<q;p++)if(n=g[p])g[p]=m?n.parentNode:n.parentNode===i;m&&k.filter(i,g,true)}},"":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m=i=i.toLowerCase();q=a}q("parentNode",i,p,g,m,n)},"~":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m= i=i.toLowerCase();q=a}q("previousSibling",i,p,g,m,n)}},find:{ID:function(g,i,n){if(typeof i.getElementById!=="undefined"&&!n)return(g=i.getElementById(g[1]))&&g.parentNode?[g]:[]},NAME:function(g,i){if(typeof i.getElementsByName!=="undefined"){for(var n=[],m=i.getElementsByName(g[1]),p=0,q=m.length;p<q;p++)m[p].getAttribute("name")===g[1]&&n.push(m[p]);return n.length===0?null:n}},TAG:function(g,i){return i.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,i,n,m,p,q){g=" "+g[1].replace(/\\/g, "")+" ";if(q)return g;q=0;for(var u;(u=i[q])!=null;q++)if(u)if(p^(u.className&&(" "+u.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))n||m.push(u);else if(n)i[q]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},CHILD:function(g){if(g[1]==="nth"){var i=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=i[1]+(i[2]||1)-0;g[3]=i[3]-0}g[0]=e++;return g},ATTR:function(g,i,n, m,p,q){i=g[1].replace(/\\/g,"");if(!q&&o.attrMap[i])g[1]=o.attrMap[i];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,i,n,m,p){if(g[1]==="not")if((d.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,i);else{g=k.filter(g[3],i,n,true^p);n||m.push.apply(m,g);return false}else if(o.match.POS.test(g[0])||o.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled=== true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,i,n){return!!k(n[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"=== g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},setFilters:{first:function(g,i){return i===0},last:function(g,i,n,m){return i===m.length-1},even:function(g,i){return i%2===0},odd:function(g,i){return i%2===1},lt:function(g,i,n){return i<n[3]-0},gt:function(g,i,n){return i>n[3]-0},nth:function(g,i,n){return n[3]- 0===i},eq:function(g,i,n){return n[3]-0===i}},filter:{PSEUDO:function(g,i,n,m){var p=i[1],q=o.filters[p];if(q)return q(g,n,i,m);else if(p==="contains")return(g.textContent||g.innerText||k.getText([g])||"").indexOf(i[3])>=0;else if(p==="not"){i=i[3];n=0;for(m=i.length;n<m;n++)if(i[n]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+p)},CHILD:function(g,i){var n=i[1],m=g;switch(n){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(n=== "first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":n=i[2];var p=i[3];if(n===1&&p===0)return true;var q=i[0],u=g.parentNode;if(u&&(u.sizcache!==q||!g.nodeIndex)){var y=0;for(m=u.firstChild;m;m=m.nextSibling)if(m.nodeType===1)m.nodeIndex=++y;u.sizcache=q}m=g.nodeIndex-p;return n===0?m===0:m%n===0&&m/n>=0}},ID:function(g,i){return g.nodeType===1&&g.getAttribute("id")===i},TAG:function(g,i){return i==="*"&&g.nodeType===1||g.nodeName.toLowerCase()=== i},CLASS:function(g,i){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(i)>-1},ATTR:function(g,i){var n=i[1];n=o.attrHandle[n]?o.attrHandle[n](g):g[n]!=null?g[n]:g.getAttribute(n);var m=n+"",p=i[2],q=i[4];return n==null?p==="!=":p==="="?m===q:p==="*="?m.indexOf(q)>=0:p==="~="?(" "+m+" ").indexOf(q)>=0:!q?m&&n!==false:p==="!="?m!==q:p==="^="?m.indexOf(q)===0:p==="$="?m.substr(m.length-q.length)===q:p==="|="?m===q||m.substr(0,q.length+1)===q+"-":false},POS:function(g,i,n,m){var p=o.setFilters[i[2]]; if(p)return p(g,n,i,m)}}},x=o.match.POS,r=function(g,i){return"\\"+(i-0+1)},A;for(A in o.match){o.match[A]=RegExp(o.match[A].source+/(?![^\[]*\])(?![^\(]*\))/.source);o.leftMatch[A]=RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[A].source.replace(/\\(\d+)/g,r))}var C=function(g,i){g=Array.prototype.slice.call(g,0);if(i){i.push.apply(i,g);return i}return g};try{Array.prototype.slice.call(t.documentElement.childNodes,0)}catch(J){C=function(g,i){var n=0,m=i||[];if(f.call(g)==="[object Array]")Array.prototype.push.apply(m, g);else if(typeof g.length==="number")for(var p=g.length;n<p;n++)m.push(g[n]);else for(;g[n];n++)m.push(g[n]);return m}}var w,I;if(t.documentElement.compareDocumentPosition)w=function(g,i){if(g===i){h=true;return 0}if(!g.compareDocumentPosition||!i.compareDocumentPosition)return g.compareDocumentPosition?-1:1;return g.compareDocumentPosition(i)&4?-1:1};else{w=function(g,i){var n,m,p=[],q=[];n=g.parentNode;m=i.parentNode;var u=n;if(g===i){h=true;return 0}else if(n===m)return I(g,i);else if(n){if(!m)return 1}else return-1; for(;u;){p.unshift(u);u=u.parentNode}for(u=m;u;){q.unshift(u);u=u.parentNode}n=p.length;m=q.length;for(u=0;u<n&&u<m;u++)if(p[u]!==q[u])return I(p[u],q[u]);return u===n?I(g,q[u],-1):I(p[u],i,1)};I=function(g,i,n){if(g===i)return n;for(g=g.nextSibling;g;){if(g===i)return-1;g=g.nextSibling}return 1}}k.getText=function(g){for(var i="",n,m=0;g[m];m++){n=g[m];if(n.nodeType===3||n.nodeType===4)i+=n.nodeValue;else if(n.nodeType!==8)i+=k.getText(n.childNodes)}return i};(function(){var g=t.createElement("div"), i="script"+(new Date).getTime(),n=t.documentElement;g.innerHTML="<a name='"+i+"'/>";n.insertBefore(g,n.firstChild);if(t.getElementById(i)){o.find.ID=function(m,p,q){if(typeof p.getElementById!=="undefined"&&!q)return(p=p.getElementById(m[1]))?p.id===m[1]||typeof p.getAttributeNode!=="undefined"&&p.getAttributeNode("id").nodeValue===m[1]?[p]:B:[]};o.filter.ID=function(m,p){var q=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&q&&q.nodeValue===p}}n.removeChild(g); n=g=null})();(function(){var g=t.createElement("div");g.appendChild(t.createComment(""));if(g.getElementsByTagName("*").length>0)o.find.TAG=function(i,n){var m=n.getElementsByTagName(i[1]);if(i[1]==="*"){for(var p=[],q=0;m[q];q++)m[q].nodeType===1&&p.push(m[q]);m=p}return m};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")o.attrHandle.href=function(i){return i.getAttribute("href",2)};g=null})();t.querySelectorAll&& function(){var g=k,i=t.createElement("div");i.innerHTML="<p class='TEST'></p>";if(!(i.querySelectorAll&&i.querySelectorAll(".TEST").length===0)){k=function(m,p,q,u){p=p||t;m=m.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!u&&!k.isXML(p))if(p.nodeType===9)try{return C(p.querySelectorAll(m),q)}catch(y){}else if(p.nodeType===1&&p.nodeName.toLowerCase()!=="object"){var F=p.getAttribute("id"),M=F||"__sizzle__";F||p.setAttribute("id",M);try{return C(p.querySelectorAll("#"+M+" "+m),q)}catch(N){}finally{F|| p.removeAttribute("id")}}return g(m,p,q,u)};for(var n in g)k[n]=g[n];i=null}}();(function(){var g=t.documentElement,i=g.matchesSelector||g.mozMatchesSelector||g.webkitMatchesSelector||g.msMatchesSelector,n=false;try{i.call(t.documentElement,"[test!='']:sizzle")}catch(m){n=true}if(i)k.matchesSelector=function(p,q){q=q.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(p))try{if(n||!o.match.PSEUDO.test(q)&&!/!=/.test(q))return i.call(p,q)}catch(u){}return k(q,null,null,[p]).length>0}})();(function(){var g= t.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){o.order.splice(1,0,"CLASS");o.find.CLASS=function(i,n,m){if(typeof n.getElementsByClassName!=="undefined"&&!m)return n.getElementsByClassName(i[1])};g=null}}})();k.contains=t.documentElement.contains?function(g,i){return g!==i&&(g.contains?g.contains(i):true)}:t.documentElement.compareDocumentPosition? function(g,i){return!!(g.compareDocumentPosition(i)&16)}:function(){return false};k.isXML=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false};var L=function(g,i){for(var n,m=[],p="",q=i.nodeType?[i]:i;n=o.match.PSEUDO.exec(g);){p+=n[0];g=g.replace(o.match.PSEUDO,"")}g=o.relative[g]?g+"*":g;n=0;for(var u=q.length;n<u;n++)k(g,q[n],m);return k.filter(p,m)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=k.getText;c.isXMLDoc=k.isXML; c.contains=k.contains})();var Za=/Until$/,$a=/^(?:parents|prevUntil|prevAll)/,ab=/,/,Na=/^.[^:#\[\.,]*$/,bb=Array.prototype.slice,cb=c.expr.match.POS;c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,e=0,f=this.length;e<f;e++){d=b.length;c.find(a,this[e],b);if(e>0)for(var h=d;h<b.length;h++)for(var l=0;l<d;l++)if(b[l]===b[h]){b.splice(h--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,e=b.length;d<e;d++)if(c.contains(this,b[d]))return true})}, not:function(a){return this.pushStack(ma(this,a,false),"not",a)},filter:function(a){return this.pushStack(ma(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){var d=[],e,f,h=this[0];if(c.isArray(a)){var l,k={},o=1;if(h&&a.length){e=0;for(f=a.length;e<f;e++){l=a[e];k[l]||(k[l]=c.expr.match.POS.test(l)?c(l,b||this.context):l)}for(;h&&h.ownerDocument&&h!==b;){for(l in k){e=k[l];if(e.jquery?e.index(h)>-1:c(h).is(e))d.push({selector:l,elem:h,level:o})}h= h.parentNode;o++}}return d}l=cb.test(a)?c(a,b||this.context):null;e=0;for(f=this.length;e<f;e++)for(h=this[e];h;)if(l?l.index(h)>-1:c.find.matchesSelector(h,a)){d.push(h);break}else{h=h.parentNode;if(!h||!h.ownerDocument||h===b)break}d=d.length>1?c.unique(d):d;return this.pushStack(d,"closest",a)},index:function(a){if(!a||typeof a==="string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var d=typeof a==="string"?c(a,b||this.context): c.makeArray(a),e=c.merge(this.get(),d);return this.pushStack(!d[0]||!d[0].parentNode||d[0].parentNode.nodeType===11||!e[0]||!e[0].parentNode||e[0].parentNode.nodeType===11?e:c.unique(e))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a, 2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a, b){c.fn[a]=function(d,e){var f=c.map(this,b,d);Za.test(a)||(e=d);if(e&&typeof e==="string")f=c.filter(e,f);f=this.length>1?c.unique(f):f;if((this.length>1||ab.test(e))&&$a.test(a))f=f.reverse();return this.pushStack(f,a,bb.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return b.length===1?c.find.matchesSelector(b[0],a)?[b[0]]:[]:c.find.matches(a,b)},dir:function(a,b,d){var e=[];for(a=a[b];a&&a.nodeType!==9&&(d===B||a.nodeType!==1||!c(a).is(d));){a.nodeType===1&& e.push(a);a=a[b]}return e},nth:function(a,b,d){b=b||1;for(var e=0;a;a=a[d])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var za=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,Aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Ba=/<([\w:]+)/,db=/<tbody/i,eb=/<|&#?\w+;/,Ca=/<(?:script|object|embed|option|style)/i,Da=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/\=([^="'>\s]+\/)>/g,P={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,"",""]};P.optgroup=P.option;P.tbody=P.tfoot=P.colgroup=P.caption=P.thead;P.th=P.td;if(!c.support.htmlSerialize)P._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d= c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==B)return this.empty().append((this[0]&&this[0].ownerDocument||t).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})}, prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b, this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,e;(e=this[d])!=null;d++)if(!a||c.filter(a,[e]).length){if(!b&&e.nodeType===1){c.cleanData(e.getElementsByTagName("*"));c.cleanData([e])}e.parentNode&&e.parentNode.removeChild(e)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild); return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,e=this.ownerDocument;if(!d){d=e.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(za,"").replace(fb,'="$1">').replace($,"")],e)[0]}else return this.cloneNode(true)});if(a===true){na(this,b);na(this.find("*"),b.find("*"))}return b},html:function(a){if(a===B)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(za,""):null; else if(typeof a==="string"&&!Ca.test(a)&&(c.support.leadingWhitespace||!$.test(a))&&!P[(Ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Aa,"<$1></$2>");try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(e){this.empty().append(a)}}else c.isFunction(a)?this.each(function(f){var h=c(this);h.html(a.call(this,f,h.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d= c(this),e=d.html();d.replaceWith(a.call(this,b,e))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){var e,f,h,l=a[0],k=[];if(!c.support.checkClone&&arguments.length===3&&typeof l==="string"&&Da.test(l))return this.each(function(){c(this).domManip(a, b,d,true)});if(c.isFunction(l))return this.each(function(x){var r=c(this);a[0]=l.call(this,x,b?r.html():B);r.domManip(a,b,d)});if(this[0]){e=l&&l.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:c.buildFragment(a,this,k);h=e.fragment;if(f=h.childNodes.length===1?h=h.firstChild:h.firstChild){b=b&&c.nodeName(f,"tr");f=0;for(var o=this.length;f<o;f++)d.call(b?c.nodeName(this[f],"table")?this[f].getElementsByTagName("tbody")[0]||this[f].appendChild(this[f].ownerDocument.createElement("tbody")): this[f]:this[f],f>0||e.cacheable||this.length>1?h.cloneNode(true):h)}k.length&&c.each(k,Oa)}return this}});c.buildFragment=function(a,b,d){var e,f,h;b=b&&b[0]?b[0].ownerDocument||b[0]:t;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===t&&!Ca.test(a[0])&&(c.support.checkClone||!Da.test(a[0]))){f=true;if(h=c.fragments[a[0]])if(h!==1)e=h}if(!e){e=b.createDocumentFragment();c.clean(a,b,e,d)}if(f)c.fragments[a[0]]=h?e:1;return{fragment:e,cacheable:f}};c.fragments={};c.each({appendTo:"append", prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var e=[];d=c(d);var f=this.length===1&&this[0].parentNode;if(f&&f.nodeType===11&&f.childNodes.length===1&&d.length===1){d[b](this[0]);return this}else{f=0;for(var h=d.length;f<h;f++){var l=(f>0?this.clone(true):this).get();c(d[f])[b](l);e=e.concat(l)}return this.pushStack(e,a,d.selector)}}});c.extend({clean:function(a,b,d,e){b=b||t;if(typeof b.createElement==="undefined")b=b.ownerDocument|| b[0]&&b[0].ownerDocument||t;for(var f=[],h=0,l;(l=a[h])!=null;h++){if(typeof l==="number")l+="";if(l){if(typeof l==="string"&&!eb.test(l))l=b.createTextNode(l);else if(typeof l==="string"){l=l.replace(Aa,"<$1></$2>");var k=(Ba.exec(l)||["",""])[1].toLowerCase(),o=P[k]||P._default,x=o[0],r=b.createElement("div");for(r.innerHTML=o[1]+l+o[2];x--;)r=r.lastChild;if(!c.support.tbody){x=db.test(l);k=k==="table"&&!x?r.firstChild&&r.firstChild.childNodes:o[1]==="<table>"&&!x?r.childNodes:[];for(o=k.length- 1;o>=0;--o)c.nodeName(k[o],"tbody")&&!k[o].childNodes.length&&k[o].parentNode.removeChild(k[o])}!c.support.leadingWhitespace&&$.test(l)&&r.insertBefore(b.createTextNode($.exec(l)[0]),r.firstChild);l=r.childNodes}if(l.nodeType)f.push(l);else f=c.merge(f,l)}}if(d)for(h=0;f[h];h++)if(e&&c.nodeName(f[h],"script")&&(!f[h].type||f[h].type.toLowerCase()==="text/javascript"))e.push(f[h].parentNode?f[h].parentNode.removeChild(f[h]):f[h]);else{f[h].nodeType===1&&f.splice.apply(f,[h+1,0].concat(c.makeArray(f[h].getElementsByTagName("script")))); d.appendChild(f[h])}return f},cleanData:function(a){for(var b,d,e=c.cache,f=c.event.special,h=c.support.deleteExpando,l=0,k;(k=a[l])!=null;l++)if(!(k.nodeName&&c.noData[k.nodeName.toLowerCase()]))if(d=k[c.expando]){if((b=e[d])&&b.events)for(var o in b.events)f[o]?c.event.remove(k,o):c.removeEvent(k,o,b.handle);if(h)delete k[c.expando];else k.removeAttribute&&k.removeAttribute(c.expando);delete e[d]}}});var Ea=/alpha\([^)]*\)/i,gb=/opacity=([^)]*)/,hb=/-([a-z])/ig,ib=/([A-Z])/g,Fa=/^-?\d+(?:px)?$/i, jb=/^-?\d/,kb={position:"absolute",visibility:"hidden",display:"block"},Pa=["Left","Right"],Qa=["Top","Bottom"],W,Ga,aa,lb=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){if(arguments.length===2&&b===B)return this;return c.access(this,a,b,true,function(d,e,f){return f!==B?c.style(d,e,f):c.css(d,e)})};c.extend({cssHooks:{opacity:{get:function(a,b){if(b){var d=W(a,"opacity","opacity");return d===""?"1":d}else return a.style.opacity}}},cssNumber:{zIndex:true,fontWeight:true,opacity:true, zoom:true,lineHeight:true},cssProps:{"float":c.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,d,e){if(!(!a||a.nodeType===3||a.nodeType===8||!a.style)){var f,h=c.camelCase(b),l=a.style,k=c.cssHooks[h];b=c.cssProps[h]||h;if(d!==B){if(!(typeof d==="number"&&isNaN(d)||d==null)){if(typeof d==="number"&&!c.cssNumber[h])d+="px";if(!k||!("set"in k)||(d=k.set(a,d))!==B)try{l[b]=d}catch(o){}}}else{if(k&&"get"in k&&(f=k.get(a,false,e))!==B)return f;return l[b]}}},css:function(a,b,d){var e,f=c.camelCase(b), h=c.cssHooks[f];b=c.cssProps[f]||f;if(h&&"get"in h&&(e=h.get(a,true,d))!==B)return e;else if(W)return W(a,b,f)},swap:function(a,b,d){var e={},f;for(f in b){e[f]=a.style[f];a.style[f]=b[f]}d.call(a);for(f in b)a.style[f]=e[f]},camelCase:function(a){return a.replace(hb,lb)}});c.curCSS=c.css;c.each(["height","width"],function(a,b){c.cssHooks[b]={get:function(d,e,f){var h;if(e){if(d.offsetWidth!==0)h=oa(d,b,f);else c.swap(d,kb,function(){h=oa(d,b,f)});if(h<=0){h=W(d,b,b);if(h==="0px"&&aa)h=aa(d,b,b); if(h!=null)return h===""||h==="auto"?"0px":h}if(h<0||h==null){h=d.style[b];return h===""||h==="auto"?"0px":h}return typeof h==="string"?h:h+"px"}},set:function(d,e){if(Fa.test(e)){e=parseFloat(e);if(e>=0)return e+"px"}else return e}}});if(!c.support.opacity)c.cssHooks.opacity={get:function(a,b){return gb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var d=a.style;d.zoom=1;var e=c.isNaN(b)?"":"alpha(opacity="+b*100+")",f= d.filter||"";d.filter=Ea.test(f)?f.replace(Ea,e):d.filter+" "+e}};if(t.defaultView&&t.defaultView.getComputedStyle)Ga=function(a,b,d){var e;d=d.replace(ib,"-$1").toLowerCase();if(!(b=a.ownerDocument.defaultView))return B;if(b=b.getComputedStyle(a,null)){e=b.getPropertyValue(d);if(e===""&&!c.contains(a.ownerDocument.documentElement,a))e=c.style(a,d)}return e};if(t.documentElement.currentStyle)aa=function(a,b){var d,e,f=a.currentStyle&&a.currentStyle[b],h=a.style;if(!Fa.test(f)&&jb.test(f)){d=h.left; e=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;h.left=b==="fontSize"?"1em":f||0;f=h.pixelLeft+"px";h.left=d;a.runtimeStyle.left=e}return f===""?"auto":f};W=Ga||aa;if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetHeight;return a.offsetWidth===0&&b===0||!c.support.reliableHiddenOffsets&&(a.style.display||c.css(a,"display"))==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var mb=c.now(),nb=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, ob=/^(?:select|textarea)/i,pb=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,qb=/^(?:GET|HEAD)$/,Ra=/\[\]$/,T=/\=\?(&|$)/,ja=/\?/,rb=/([?&])_=[^&]*/,sb=/^(\w+:)?\/\/([^\/?#]+)/,tb=/%20/g,ub=/#.*$/,Ha=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!=="string"&&Ha)return Ha.apply(this,arguments);else if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var f=a.slice(e,a.length);a=a.slice(0,e)}e="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b=== "object"){b=c.param(b,c.ajaxSettings.traditional);e="POST"}var h=this;c.ajax({url:a,type:e,dataType:"html",data:b,complete:function(l,k){if(k==="success"||k==="notmodified")h.html(f?c("<div>").append(l.responseText.replace(nb,"")).find(f):l.responseText);d&&h.each(d,[l.responseText,k,l])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&& !this.disabled&&(this.checked||ob.test(this.nodeName)||pb.test(this.type))}).map(function(a,b){var d=c(this).val();return d==null?null:c.isArray(d)?c.map(d,function(e){return{name:b.name,value:e}}):{name:b.name,value:d}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:e})}, getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:e})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return new E.XMLHttpRequest},accepts:{xml:"application/xml, text/xml",html:"text/html", script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},ajax:function(a){var b=c.extend(true,{},c.ajaxSettings,a),d,e,f,h=b.type.toUpperCase(),l=qb.test(h);b.url=b.url.replace(ub,"");b.context=a&&a.context!=null?a.context:b;if(b.data&&b.processData&&typeof b.data!=="string")b.data=c.param(b.data,b.traditional);if(b.dataType==="jsonp"){if(h==="GET")T.test(b.url)||(b.url+=(ja.test(b.url)?"&":"?")+(b.jsonp||"callback")+"=?");else if(!b.data|| !T.test(b.data))b.data=(b.data?b.data+"&":"")+(b.jsonp||"callback")+"=?";b.dataType="json"}if(b.dataType==="json"&&(b.data&&T.test(b.data)||T.test(b.url))){d=b.jsonpCallback||"jsonp"+mb++;if(b.data)b.data=(b.data+"").replace(T,"="+d+"$1");b.url=b.url.replace(T,"="+d+"$1");b.dataType="script";var k=E[d];E[d]=function(m){if(c.isFunction(k))k(m);else{E[d]=B;try{delete E[d]}catch(p){}}f=m;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);r&&r.removeChild(A)}}if(b.dataType==="script"&&b.cache===null)b.cache= false;if(b.cache===false&&l){var o=c.now(),x=b.url.replace(rb,"$1_="+o);b.url=x+(x===b.url?(ja.test(b.url)?"&":"?")+"_="+o:"")}if(b.data&&l)b.url+=(ja.test(b.url)?"&":"?")+b.data;b.global&&c.active++===0&&c.event.trigger("ajaxStart");o=(o=sb.exec(b.url))&&(o[1]&&o[1].toLowerCase()!==location.protocol||o[2].toLowerCase()!==location.host);if(b.dataType==="script"&&h==="GET"&&o){var r=t.getElementsByTagName("head")[0]||t.documentElement,A=t.createElement("script");if(b.scriptCharset)A.charset=b.scriptCharset; A.src=b.url;if(!d){var C=false;A.onload=A.onreadystatechange=function(){if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){C=true;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);A.onload=A.onreadystatechange=null;r&&A.parentNode&&r.removeChild(A)}}}r.insertBefore(A,r.firstChild);return B}var J=false,w=b.xhr();if(w){b.username?w.open(h,b.url,b.async,b.username,b.password):w.open(h,b.url,b.async);try{if(b.data!=null&&!l||a&&a.contentType)w.setRequestHeader("Content-Type", b.contentType);if(b.ifModified){c.lastModified[b.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[b.url]);c.etag[b.url]&&w.setRequestHeader("If-None-Match",c.etag[b.url])}o||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept",b.dataType&&b.accepts[b.dataType]?b.accepts[b.dataType]+", */*; q=0.01":b.accepts._default)}catch(I){}if(b.beforeSend&&b.beforeSend.call(b.context,w,b)===false){b.global&&c.active--===1&&c.event.trigger("ajaxStop");w.abort();return false}b.global&& c.triggerGlobal(b,"ajaxSend",[w,b]);var L=w.onreadystatechange=function(m){if(!w||w.readyState===0||m==="abort"){J||c.handleComplete(b,w,e,f);J=true;if(w)w.onreadystatechange=c.noop}else if(!J&&w&&(w.readyState===4||m==="timeout")){J=true;w.onreadystatechange=c.noop;e=m==="timeout"?"timeout":!c.httpSuccess(w)?"error":b.ifModified&&c.httpNotModified(w,b.url)?"notmodified":"success";var p;if(e==="success")try{f=c.httpData(w,b.dataType,b)}catch(q){e="parsererror";p=q}if(e==="success"||e==="notmodified")d|| c.handleSuccess(b,w,e,f);else c.handleError(b,w,e,p);d||c.handleComplete(b,w,e,f);m==="timeout"&&w.abort();if(b.async)w=null}};try{var g=w.abort;w.abort=function(){w&&Function.prototype.call.call(g,w);L("abort")}}catch(i){}b.async&&b.timeout>0&&setTimeout(function(){w&&!J&&L("timeout")},b.timeout);try{w.send(l||b.data==null?null:b.data)}catch(n){c.handleError(b,w,null,n);c.handleComplete(b,w,e,f)}b.async||L();return w}},param:function(a,b){var d=[],e=function(h,l){l=c.isFunction(l)?l():l;d[d.length]= encodeURIComponent(h)+"="+encodeURIComponent(l)};if(b===B)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){e(this.name,this.value)});else for(var f in a)da(f,a[f],b,e);return d.join("&").replace(tb,"+")}});c.extend({active:0,lastModified:{},etag:{},handleError:function(a,b,d,e){a.error&&a.error.call(a.context,b,d,e);a.global&&c.triggerGlobal(a,"ajaxError",[b,a,e])},handleSuccess:function(a,b,d,e){a.success&&a.success.call(a.context,e,d,b);a.global&&c.triggerGlobal(a,"ajaxSuccess", [b,a])},handleComplete:function(a,b,d){a.complete&&a.complete.call(a.context,b,d);a.global&&c.triggerGlobal(a,"ajaxComplete",[b,a]);a.global&&c.active--===1&&c.event.trigger("ajaxStop")},triggerGlobal:function(a,b,d){(a.context&&a.context.url==null?c(a.context):c.event).trigger(b,d)},httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"), e=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(e)c.etag[b]=e;return a.status===304},httpData:function(a,b,d){var e=a.getResponseHeader("content-type")||"",f=b==="xml"||!b&&e.indexOf("xml")>=0;a=f?a.responseXML:a.responseText;f&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&e.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&e.indexOf("javascript")>=0)c.globalEval(a);return a}}); if(E.ActiveXObject)c.ajaxSettings.xhr=function(){if(E.location.protocol!=="file:")try{return new E.XMLHttpRequest}catch(a){}try{return new E.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}};c.support.ajax=!!c.ajaxSettings.xhr();var ea={},vb=/^(?:toggle|show|hide)$/,wb=/^([+\-]=)?([\d+.\-]+)(.*)$/,ba,pa=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b,d){if(a||a===0)return this.animate(S("show", 3),a,b,d);else{d=0;for(var e=this.length;d<e;d++){a=this[d];b=a.style.display;if(!c.data(a,"olddisplay")&&b==="none")b=a.style.display="";b===""&&c.css(a,"display")==="none"&&c.data(a,"olddisplay",qa(a.nodeName))}for(d=0;d<e;d++){a=this[d];b=a.style.display;if(b===""||b==="none")a.style.display=c.data(a,"olddisplay")||""}return this}},hide:function(a,b,d){if(a||a===0)return this.animate(S("hide",3),a,b,d);else{a=0;for(b=this.length;a<b;a++){d=c.css(this[a],"display");d!=="none"&&c.data(this[a],"olddisplay", d)}for(a=0;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b,d){var e=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||e?this.each(function(){var f=e?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(S("toggle",3),a,b,d);return this},fadeTo:function(a,b,d,e){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d,e)},animate:function(a,b,d,e){var f=c.speed(b, d,e);if(c.isEmptyObject(a))return this.each(f.complete);return this[f.queue===false?"each":"queue"](function(){var h=c.extend({},f),l,k=this.nodeType===1,o=k&&c(this).is(":hidden"),x=this;for(l in a){var r=c.camelCase(l);if(l!==r){a[r]=a[l];delete a[l];l=r}if(a[l]==="hide"&&o||a[l]==="show"&&!o)return h.complete.call(this);if(k&&(l==="height"||l==="width")){h.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(c.css(this,"display")==="inline"&&c.css(this,"float")==="none")if(c.support.inlineBlockNeedsLayout)if(qa(this.nodeName)=== "inline")this.style.display="inline-block";else{this.style.display="inline";this.style.zoom=1}else this.style.display="inline-block"}if(c.isArray(a[l])){(h.specialEasing=h.specialEasing||{})[l]=a[l][1];a[l]=a[l][0]}}if(h.overflow!=null)this.style.overflow="hidden";h.curAnim=c.extend({},a);c.each(a,function(A,C){var J=new c.fx(x,h,A);if(vb.test(C))J[C==="toggle"?o?"show":"hide":C](a);else{var w=wb.exec(C),I=J.cur()||0;if(w){var L=parseFloat(w[2]),g=w[3]||"px";if(g!=="px"){c.style(x,A,(L||1)+g);I=(L|| 1)/J.cur()*I;c.style(x,A,I+g)}if(w[1])L=(w[1]==="-="?-1:1)*L+I;J.custom(I,L,g)}else J.custom(I,C,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var e=d.length-1;e>=0;e--)if(d[e].elem===this){b&&d[e](true);d.splice(e,1)}});b||this.dequeue();return this}});c.each({slideDown:S("show",1),slideUp:S("hide",1),slideToggle:S("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){c.fn[a]=function(d,e,f){return this.animate(b, d,e,f)}});c.extend({speed:function(a,b,d){var e=a&&typeof a==="object"?c.extend({},a):{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};e.duration=c.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in c.fx.speeds?c.fx.speeds[e.duration]:c.fx.speeds._default;e.old=e.complete;e.complete=function(){e.queue!==false&&c(this).dequeue();c.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,d,e){return d+e*a},swing:function(a,b,d,e){return(-Math.cos(a* Math.PI)/2+0.5)*e+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a=parseFloat(c.css(this.elem,this.prop));return a&&a>-1E4?a:0},custom:function(a,b,d){function e(l){return f.step(l)} var f=this,h=c.fx;this.startTime=c.now();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;e.elem=this.elem;if(e()&&c.timers.push(e)&&!ba)ba=setInterval(h.tick,h.interval)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true; this.custom(this.cur(),0)},step:function(a){var b=c.now(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var e in this.options.curAnim)if(this.options.curAnim[e]!==true)d=false;if(d){if(this.options.overflow!=null&&!c.support.shrinkWrapBlocks){var f=this.elem,h=this.options;c.each(["","X","Y"],function(k,o){f.style["overflow"+o]=h.overflow[k]})}this.options.hide&&c(this.elem).hide();if(this.options.hide|| this.options.show)for(var l in this.options.curAnim)c.style(this.elem,l,this.options.orig[l]);this.options.complete.call(this.elem)}return false}else{a=b-this.startTime;this.state=a/this.options.duration;b=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||b](this.state,a,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a= c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},interval:13,stop:function(){clearInterval(ba);ba=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a=== b.elem}).length};var xb=/^t(?:able|d|h)$/i,Ia=/^(?:body|html)$/i;c.fn.offset="getBoundingClientRect"in t.documentElement?function(a){var b=this[0],d;if(a)return this.each(function(l){c.offset.setOffset(this,a,l)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);try{d=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,h=f.documentElement;if(!d||!c.contains(h,b))return d||{top:0,left:0};b=f.body;f=fa(f);return{top:d.top+(f.pageYOffset||c.support.boxModel&& h.scrollTop||b.scrollTop)-(h.clientTop||b.clientTop||0),left:d.left+(f.pageXOffset||c.support.boxModel&&h.scrollLeft||b.scrollLeft)-(h.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(a)return this.each(function(x){c.offset.setOffset(this,a,x)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d,e=b.offsetParent,f=b.ownerDocument,h=f.documentElement,l=f.body;d=(f=f.defaultView)?f.getComputedStyle(b,null):b.currentStyle; for(var k=b.offsetTop,o=b.offsetLeft;(b=b.parentNode)&&b!==l&&b!==h;){if(c.offset.supportsFixedPosition&&d.position==="fixed")break;d=f?f.getComputedStyle(b,null):b.currentStyle;k-=b.scrollTop;o-=b.scrollLeft;if(b===e){k+=b.offsetTop;o+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&xb.test(b.nodeName))){k+=parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}e=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"){k+= parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}d=d}if(d.position==="relative"||d.position==="static"){k+=l.offsetTop;o+=l.offsetLeft}if(c.offset.supportsFixedPosition&&d.position==="fixed"){k+=Math.max(h.scrollTop,l.scrollTop);o+=Math.max(h.scrollLeft,l.scrollLeft)}return{top:k,left:o}};c.offset={initialize:function(){var a=t.body,b=t.createElement("div"),d,e,f,h=parseFloat(c.css(a,"marginTop"))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px", height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.insertBefore(b,a.firstChild);d=b.firstChild;e=d.firstChild;f=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=e.offsetTop!==5;this.doesAddBorderForTableAndCells= f.offsetTop===5;e.style.position="fixed";e.style.top="20px";this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15;e.style.position=e.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==h;a.removeChild(b);c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.css(a, "marginTop"))||0;d+=parseFloat(c.css(a,"marginLeft"))||0}return{top:b,left:d}},setOffset:function(a,b,d){var e=c.css(a,"position");if(e==="static")a.style.position="relative";var f=c(a),h=f.offset(),l=c.css(a,"top"),k=c.css(a,"left"),o=e==="absolute"&&c.inArray("auto",[l,k])>-1;e={};var x={};if(o)x=f.position();l=o?x.top:parseInt(l,10)||0;k=o?x.left:parseInt(k,10)||0;if(c.isFunction(b))b=b.call(a,d,h);if(b.top!=null)e.top=b.top-h.top+l;if(b.left!=null)e.left=b.left-h.left+k;"using"in b?b.using.call(a, e):f.css(e)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),e=Ia.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.css(a,"marginTop"))||0;d.left-=parseFloat(c.css(a,"marginLeft"))||0;e.top+=parseFloat(c.css(b[0],"borderTopWidth"))||0;e.left+=parseFloat(c.css(b[0],"borderLeftWidth"))||0;return{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||t.body;a&&!Ia.test(a.nodeName)&& c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(e){var f=this[0],h;if(!f)return null;if(e!==B)return this.each(function(){if(h=fa(this))h.scrollTo(!a?e:c(h).scrollLeft(),a?e:c(h).scrollTop());else this[d]=e});else return(h=fa(f))?"pageXOffset"in h?h[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&h.document.documentElement[d]||h.document.body[d]:f[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase(); c.fn["inner"+b]=function(){return this[0]?parseFloat(c.css(this[0],d,"padding")):null};c.fn["outer"+b]=function(e){return this[0]?parseFloat(c.css(this[0],d,e?"margin":"border")):null};c.fn[d]=function(e){var f=this[0];if(!f)return e==null?null:this;if(c.isFunction(e))return this.each(function(l){var k=c(this);k[d](e.call(this,l,k[d]()))});if(c.isWindow(f))return f.document.compatMode==="CSS1Compat"&&f.document.documentElement["client"+b]||f.document.body["client"+b];else if(f.nodeType===9)return Math.max(f.documentElement["client"+ b],f.body["scroll"+b],f.documentElement["scroll"+b],f.body["offset"+b],f.documentElement["offset"+b]);else if(e===B){f=c.css(f,d);var h=parseFloat(f);return c.isNaN(h)?f:h}else return this.css(d,typeof e==="string"?e:e+"px")}})})(window);
src/client/routes.js
youprofit/este
// import Examples from './examples/page.react'; import App from './app/app.react'; import Home from './home/index.react'; import Login from './auth/index.react'; import Me from './me/index.react'; import NotFound from './components/notfound.react'; import React from 'react'; import Todos from './todos/index.react'; import {DefaultRoute, NotFoundRoute, Route} from 'react-router'; export default ( <Route handler={App} path="/"> <DefaultRoute handler={Home} name="home" /> <NotFoundRoute handler={NotFound} name="not-found" /> {/*<Route handler={Examples} name="examples" />*/} <Route handler={Login} name="login" /> <Route handler={Me} name="me" /> <Route handler={Todos} name="todos" /> </Route> );
example/src/test_rollinput.js
flywingdevelopers/rn-naive
/** * <TextInput> * Kevin Lee 3 Sept 2017 **/ import React from 'react' import { Screen, Bar, Block, DataBar, DataBlock, Text, CheckBox, Input, Roll, } from 'rn-naive' export default class App extends React.Component { constructor(props) { super(props) this.state = { disabled: false, d1: '', d2: '', d3: '', d4: '', d5: '', } } logos = [ {icon:'logo-android', text:'Android'}, {icon:'logo-apple', text:'Apple'}, {icon:'logo-dropbox', text:'Dropbox'}, {icon:'logo-facebook', text:'Facebook'}, {icon:'logo-playstation', text:'PlayStation'}, {icon:'logo-xbox', text:'X-Box'}, ] genders = [ {icon:'md-man', text:'Man', iconColor:'green', textStyle:{color:'green'}}, {icon:'md-woman', text:'Woman', iconColor:'red', textStyle:{color:'red'}}, ] render() { k = 1 return ( <Screen lines={16} title='<Roll Input> Control Test' left={<CheckBox iconOnly style={{alignItems:'flex-start'}} iconSize={20} iconColor='#ddd' icons={['md-eye-off', 'md-eye']} value={this.state.DisableAll} onValueChange={(disabled)=>this.setState({disabled})} />} > <Bar lines={2} text={<Text D3>Roll Input change value upon user clicks. It is styled to align with other input elements.</Text>} /> <Block lines={7} style={{borderWidth:1, margin:2}}> <DataBar text={(k++) + '. Basic Input'} input={<Input disabled={this.state.disabled}/>} /> <DataBar text={(k++) + '. Basic Roll Input'} input={<Roll input items={this.logos} disabled={this.state.disabled} value={this.state.d1} onValueChange={(d1)=>this.setState({d1})} />} /> <DataBar text={(k++) + '. Underlined Input'} input={<Input underline disabled={this.state.disabled}/>} /> <DataBar text={(k++) + '. Underlined Roll Input'} input={<Roll input items={this.logos} underline disabled={this.state.disabled} value={this.state.d2} onValueChange={(d2)=>this.setState({d2})} />} /> <DataBar text={(k++) + '. Underlined IconOnly Roll'} input={<Roll input items={this.logos} iconOnly underline disabled={this.state.disabled} value={this.state.d5} onValueChange={(d5)=>this.setState({d5})} />} /> <DataBar lines={1.5} text={(k++) + '. Underlined IconOnly Roll'} input={<Roll input items={this.logos} iconTop underline disabled={this.state.disabled} value={this.state.d5} onValueChange={(d5)=>this.setState({d5})} />} /> </Block> <Bar lines={2}> <DataBlock style={{borderWidth:1}} text={(k++) + '. Basic Input'} input={<Input disabled={this.state.disabled}/>} /> <DataBlock style={{borderWidth:1}} text={(k++) + '. Basic Roll Input'} input={<Roll input items={this.genders} iconRight disabled={this.state.disabled} value={this.state.d3} onValueChange={(d3)=>this.setState({d3})} />} /> </Bar> <Bar lines={2}> <DataBlock style={{borderWidth:1}} text={(k++) + '. Underlined Input'} input={<Input underline disabled={this.state.disabled}/>} /> <DataBlock style={{borderWidth:1}} text={(k++) + '. Underlined Roll Input'} input={<Roll input items={this.genders} iconRight underline disabled={this.state.disabled} value={this.state.d4} onValueChange={(d4)=>this.setState({d4})} />} /> </Bar> </Screen> ) } }
drools-guvnor/src/main/webapp/org.drools.guvnor.Guvnor/js/ext/ext-all-debug.js
bobmcwhirter/drools
/* * Ext JS Library 2.0.2 * Copyright(c) 2006-2008, Ext JS, LLC. * licensing@extjs.com * * http://extjs.com/license */ Ext.DomHelper = function(){ var tempTableEl = null; var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i; var tableRe = /^table|tbody|tr|td$/i; var createHtml = function(o){ if(typeof o == 'string'){ return o; } var b = ""; if (Ext.isArray(o)) { for (var i = 0, l = o.length; i < l; i++) { b += createHtml(o[i]); } return b; } if(!o.tag){ o.tag = "div"; } b += "<" + o.tag; for(var attr in o){ if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") continue; if(attr == "style"){ var s = o["style"]; if(typeof s == "function"){ s = s.call(); } if(typeof s == "string"){ b += ' style="' + s + '"'; }else if(typeof s == "object"){ b += ' style="'; for(var key in s){ if(typeof s[key] != "function"){ b += key + ":" + s[key] + ";"; } } b += '"'; } }else{ if(attr == "cls"){ b += ' class="' + o["cls"] + '"'; }else if(attr == "htmlFor"){ b += ' for="' + o["htmlFor"] + '"'; }else{ b += " " + attr + '="' + o[attr] + '"'; } } } if(emptyTags.test(o.tag)){ b += "/>"; }else{ b += ">"; var cn = o.children || o.cn; if(cn){ b += createHtml(cn); } else if(o.html){ b += o.html; } b += "</" + o.tag + ">"; } return b; }; var createDom = function(o, parentNode){ var el; if (Ext.isArray(o)) { el = document.createDocumentFragment(); for(var i = 0, l = o.length; i < l; i++) { createDom(o[i], el); } } else if (typeof o == "string)") { el = document.createTextNode(o); } else { el = document.createElement(o.tag||'div'); var useSet = !!el.setAttribute; for(var attr in o){ if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || attr == "style" || typeof o[attr] == "function") continue; if(attr=="cls"){ el.className = o["cls"]; }else{ if(useSet) el.setAttribute(attr, o[attr]); else el[attr] = o[attr]; } } Ext.DomHelper.applyStyles(el, o.style); var cn = o.children || o.cn; if(cn){ createDom(cn, el); } else if(o.html){ el.innerHTML = o.html; } } if(parentNode){ parentNode.appendChild(el); } return el; }; var ieTable = function(depth, s, h, e){ tempTableEl.innerHTML = [s, h, e].join(''); var i = -1, el = tempTableEl; while(++i < depth){ el = el.firstChild; } return el; }; var ts = '<table>', te = '</table>', tbs = ts+'<tbody>', tbe = '</tbody>'+te, trs = tbs + '<tr>', tre = '</tr>'+tbe; var insertIntoTable = function(tag, where, el, html){ if(!tempTableEl){ tempTableEl = document.createElement('div'); } var node; var before = null; if(tag == 'td'){ if(where == 'afterbegin' || where == 'beforeend'){ return; } if(where == 'beforebegin'){ before = el; el = el.parentNode; } else{ before = el.nextSibling; el = el.parentNode; } node = ieTable(4, trs, html, tre); } else if(tag == 'tr'){ if(where == 'beforebegin'){ before = el; el = el.parentNode; node = ieTable(3, tbs, html, tbe); } else if(where == 'afterend'){ before = el.nextSibling; el = el.parentNode; node = ieTable(3, tbs, html, tbe); } else{ if(where == 'afterbegin'){ before = el.firstChild; } node = ieTable(4, trs, html, tre); } } else if(tag == 'tbody'){ if(where == 'beforebegin'){ before = el; el = el.parentNode; node = ieTable(2, ts, html, te); } else if(where == 'afterend'){ before = el.nextSibling; el = el.parentNode; node = ieTable(2, ts, html, te); } else{ if(where == 'afterbegin'){ before = el.firstChild; } node = ieTable(3, tbs, html, tbe); } } else{ if(where == 'beforebegin' || where == 'afterend'){ return; } if(where == 'afterbegin'){ before = el.firstChild; } node = ieTable(2, ts, html, te); } el.insertBefore(node, before); return node; }; return { useDom : false, markup : function(o){ return createHtml(o); }, applyStyles : function(el, styles){ if(styles){ el = Ext.fly(el); if(typeof styles == "string"){ var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi; var matches; while ((matches = re.exec(styles)) != null){ el.setStyle(matches[1], matches[2]); } }else if (typeof styles == "object"){ for (var style in styles){ el.setStyle(style, styles[style]); } }else if (typeof styles == "function"){ Ext.DomHelper.applyStyles(el, styles.call()); } } }, insertHtml : function(where, el, html){ where = where.toLowerCase(); if(el.insertAdjacentHTML){ if(tableRe.test(el.tagName)){ var rs; if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){ return rs; } } switch(where){ case "beforebegin": el.insertAdjacentHTML('BeforeBegin', html); return el.previousSibling; case "afterbegin": el.insertAdjacentHTML('AfterBegin', html); return el.firstChild; case "beforeend": el.insertAdjacentHTML('BeforeEnd', html); return el.lastChild; case "afterend": el.insertAdjacentHTML('AfterEnd', html); return el.nextSibling; } throw 'Illegal insertion point -> "' + where + '"'; } var range = el.ownerDocument.createRange(); var frag; switch(where){ case "beforebegin": range.setStartBefore(el); frag = range.createContextualFragment(html); el.parentNode.insertBefore(frag, el); return el.previousSibling; case "afterbegin": if(el.firstChild){ range.setStartBefore(el.firstChild); frag = range.createContextualFragment(html); el.insertBefore(frag, el.firstChild); return el.firstChild; }else{ el.innerHTML = html; return el.firstChild; } case "beforeend": if(el.lastChild){ range.setStartAfter(el.lastChild); frag = range.createContextualFragment(html); el.appendChild(frag); return el.lastChild; }else{ el.innerHTML = html; return el.lastChild; } case "afterend": range.setStartAfter(el); frag = range.createContextualFragment(html); el.parentNode.insertBefore(frag, el.nextSibling); return el.nextSibling; } throw 'Illegal insertion point -> "' + where + '"'; }, insertBefore : function(el, o, returnElement){ return this.doInsert(el, o, returnElement, "beforeBegin"); }, insertAfter : function(el, o, returnElement){ return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling"); }, insertFirst : function(el, o, returnElement){ return this.doInsert(el, o, returnElement, "afterBegin", "firstChild"); }, doInsert : function(el, o, returnElement, pos, sibling){ el = Ext.getDom(el); var newNode; if(this.useDom){ newNode = createDom(o, null); (sibling === "firstChild" ? el : el.parentNode).insertBefore(newNode, sibling ? el[sibling] : el); }else{ var html = createHtml(o); newNode = this.insertHtml(pos, el, html); } return returnElement ? Ext.get(newNode, true) : newNode; }, append : function(el, o, returnElement){ el = Ext.getDom(el); var newNode; if(this.useDom){ newNode = createDom(o, null); el.appendChild(newNode); }else{ var html = createHtml(o); newNode = this.insertHtml("beforeEnd", el, html); } return returnElement ? Ext.get(newNode, true) : newNode; }, overwrite : function(el, o, returnElement){ el = Ext.getDom(el); el.innerHTML = createHtml(o); return returnElement ? Ext.get(el.firstChild, true) : el.firstChild; }, createTemplate : function(o){ var html = createHtml(o); return new Ext.Template(html); } }; }(); Ext.Template = function(html){ var a = arguments; if(Ext.isArray(html)){ html = html.join(""); }else if(a.length > 1){ var buf = []; for(var i = 0, len = a.length; i < len; i++){ if(typeof a[i] == 'object'){ Ext.apply(this, a[i]); }else{ buf[buf.length] = a[i]; } } html = buf.join(''); } this.html = html; if(this.compiled){ this.compile(); } }; Ext.Template.prototype = { applyTemplate : function(values){ if(this.compiled){ return this.compiled(values); } var useF = this.disableFormats !== true; var fm = Ext.util.Format, tpl = this; var fn = function(m, name, format, args){ if(format && useF){ if(format.substr(0, 5) == "this."){ return tpl.call(format.substr(5), values[name], values); }else{ if(args){ var re = /^\s*['"](.*)["']\s*$/; args = args.split(','); for(var i = 0, len = args.length; i < len; i++){ args[i] = args[i].replace(re, "$1"); } args = [values[name]].concat(args); }else{ args = [values[name]]; } return fm[format].apply(fm, args); } }else{ return values[name] !== undefined ? values[name] : ""; } }; return this.html.replace(this.re, fn); }, set : function(html, compile){ this.html = html; this.compiled = null; if(compile){ this.compile(); } return this; }, disableFormats : false, re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g, compile : function(){ var fm = Ext.util.Format; var useF = this.disableFormats !== true; var sep = Ext.isGecko ? "+" : ","; var fn = function(m, name, format, args){ if(format && useF){ args = args ? ',' + args : ""; if(format.substr(0, 5) != "this."){ format = "fm." + format + '('; }else{ format = 'this.call("'+ format.substr(5) + '", '; args = ", values"; } }else{ args= ''; format = "(values['" + name + "'] == undefined ? '' : "; } return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'"; }; var body; if(Ext.isGecko){ body = "this.compiled = function(values){ return '" + this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) + "';};"; }else{ body = ["this.compiled = function(values){ return ['"]; body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn)); body.push("'].join('');};"); body = body.join(''); } eval(body); return this; }, call : function(fnName, value, allValues){ return this[fnName](value, allValues); }, insertFirst: function(el, values, returnElement){ return this.doInsert('afterBegin', el, values, returnElement); }, insertBefore: function(el, values, returnElement){ return this.doInsert('beforeBegin', el, values, returnElement); }, insertAfter : function(el, values, returnElement){ return this.doInsert('afterEnd', el, values, returnElement); }, append : function(el, values, returnElement){ return this.doInsert('beforeEnd', el, values, returnElement); }, doInsert : function(where, el, values, returnEl){ el = Ext.getDom(el); var newNode = Ext.DomHelper.insertHtml(where, el, this.applyTemplate(values)); return returnEl ? Ext.get(newNode, true) : newNode; }, overwrite : function(el, values, returnElement){ el = Ext.getDom(el); el.innerHTML = this.applyTemplate(values); return returnElement ? Ext.get(el.firstChild, true) : el.firstChild; } }; Ext.Template.prototype.apply = Ext.Template.prototype.applyTemplate; Ext.DomHelper.Template = Ext.Template; Ext.Template.from = function(el, config){ el = Ext.getDom(el); return new Ext.Template(el.value || el.innerHTML, config || ''); }; Ext.DomQuery = function(){ var cache = {}, simpleCache = {}, valueCache = {}; var nonSpace = /\S/; var trimRe = /^\s+|\s+$/g; var tplRe = /\{(\d+)\}/g; var modeRe = /^(\s?[\/>+~]\s?|\s|$)/; var tagTokenRe = /^(#)?([\w-\*]+)/; var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/; function child(p, index){ var i = 0; var n = p.firstChild; while(n){ if(n.nodeType == 1){ if(++i == index){ return n; } } n = n.nextSibling; } return null; }; function next(n){ while((n = n.nextSibling) && n.nodeType != 1); return n; }; function prev(n){ while((n = n.previousSibling) && n.nodeType != 1); return n; }; function children(d){ var n = d.firstChild, ni = -1; while(n){ var nx = n.nextSibling; if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){ d.removeChild(n); }else{ n.nodeIndex = ++ni; } n = nx; } return this; }; function byClassName(c, a, v){ if(!v){ return c; } var r = [], ri = -1, cn; for(var i = 0, ci; ci = c[i]; i++){ if((' '+ci.className+' ').indexOf(v) != -1){ r[++ri] = ci; } } return r; }; function attrValue(n, attr){ if(!n.tagName && typeof n.length != "undefined"){ n = n[0]; } if(!n){ return null; } if(attr == "for"){ return n.htmlFor; } if(attr == "class" || attr == "className"){ return n.className; } return n.getAttribute(attr) || n[attr]; }; function getNodes(ns, mode, tagName){ var result = [], ri = -1, cs; if(!ns){ return result; } tagName = tagName || "*"; if(typeof ns.getElementsByTagName != "undefined"){ ns = [ns]; } if(!mode){ for(var i = 0, ni; ni = ns[i]; i++){ cs = ni.getElementsByTagName(tagName); for(var j = 0, ci; ci = cs[j]; j++){ result[++ri] = ci; } } }else if(mode == "/" || mode == ">"){ var utag = tagName.toUpperCase(); for(var i = 0, ni, cn; ni = ns[i]; i++){ cn = ni.children || ni.childNodes; for(var j = 0, cj; cj = cn[j]; j++){ if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){ result[++ri] = cj; } } } }else if(mode == "+"){ var utag = tagName.toUpperCase(); for(var i = 0, n; n = ns[i]; i++){ while((n = n.nextSibling) && n.nodeType != 1); if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){ result[++ri] = n; } } }else if(mode == "~"){ for(var i = 0, n; n = ns[i]; i++){ while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName))); if(n){ result[++ri] = n; } } } return result; }; function concat(a, b){ if(b.slice){ return a.concat(b); } for(var i = 0, l = b.length; i < l; i++){ a[a.length] = b[i]; } return a; } function byTag(cs, tagName){ if(cs.tagName || cs == document){ cs = [cs]; } if(!tagName){ return cs; } var r = [], ri = -1; tagName = tagName.toLowerCase(); for(var i = 0, ci; ci = cs[i]; i++){ if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){ r[++ri] = ci; } } return r; }; function byId(cs, attr, id){ if(cs.tagName || cs == document){ cs = [cs]; } if(!id){ return cs; } var r = [], ri = -1; for(var i = 0,ci; ci = cs[i]; i++){ if(ci && ci.id == id){ r[++ri] = ci; return r; } } return r; }; function byAttribute(cs, attr, value, op, custom){ var r = [], ri = -1, st = custom=="{"; var f = Ext.DomQuery.operators[op]; for(var i = 0, ci; ci = cs[i]; i++){ var a; if(st){ a = Ext.DomQuery.getStyle(ci, attr); } else if(attr == "class" || attr == "className"){ a = ci.className; }else if(attr == "for"){ a = ci.htmlFor; }else if(attr == "href"){ a = ci.getAttribute("href", 2); }else{ a = ci.getAttribute(attr); } if((f && f(a, value)) || (!f && a)){ r[++ri] = ci; } } return r; }; function byPseudo(cs, name, value){ return Ext.DomQuery.pseudos[name](cs, value); }; var isIE = window.ActiveXObject ? true : false; eval("var batch = 30803;"); var key = 30803; function nodupIEXml(cs){ var d = ++key; cs[0].setAttribute("_nodup", d); var r = [cs[0]]; for(var i = 1, len = cs.length; i < len; i++){ var c = cs[i]; if(!c.getAttribute("_nodup") != d){ c.setAttribute("_nodup", d); r[r.length] = c; } } for(var i = 0, len = cs.length; i < len; i++){ cs[i].removeAttribute("_nodup"); } return r; } function nodup(cs){ if(!cs){ return []; } var len = cs.length, c, i, r = cs, cj, ri = -1; if(!len || typeof cs.nodeType != "undefined" || len == 1){ return cs; } if(isIE && typeof cs[0].selectSingleNode != "undefined"){ return nodupIEXml(cs); } var d = ++key; cs[0]._nodup = d; for(i = 1; c = cs[i]; i++){ if(c._nodup != d){ c._nodup = d; }else{ r = []; for(var j = 0; j < i; j++){ r[++ri] = cs[j]; } for(j = i+1; cj = cs[j]; j++){ if(cj._nodup != d){ cj._nodup = d; r[++ri] = cj; } } return r; } } return r; } function quickDiffIEXml(c1, c2){ var d = ++key; for(var i = 0, len = c1.length; i < len; i++){ c1[i].setAttribute("_qdiff", d); } var r = []; for(var i = 0, len = c2.length; i < len; i++){ if(c2[i].getAttribute("_qdiff") != d){ r[r.length] = c2[i]; } } for(var i = 0, len = c1.length; i < len; i++){ c1[i].removeAttribute("_qdiff"); } return r; } function quickDiff(c1, c2){ var len1 = c1.length; if(!len1){ return c2; } if(isIE && c1[0].selectSingleNode){ return quickDiffIEXml(c1, c2); } var d = ++key; for(var i = 0; i < len1; i++){ c1[i]._qdiff = d; } var r = []; for(var i = 0, len = c2.length; i < len; i++){ if(c2[i]._qdiff != d){ r[r.length] = c2[i]; } } return r; } function quickId(ns, mode, root, id){ if(ns == root){ var d = root.ownerDocument || root; return d.getElementById(id); } ns = getNodes(ns, mode, "*"); return byId(ns, null, id); } return { getStyle : function(el, name){ return Ext.fly(el).getStyle(name); }, compile : function(path, type){ type = type || "select"; var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"]; var q = path, mode, lq; var tk = Ext.DomQuery.matchers; var tklen = tk.length; var mm; var lmode = q.match(modeRe); if(lmode && lmode[1]){ fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";'; q = q.replace(lmode[1], ""); } while(path.substr(0, 1)=="/"){ path = path.substr(1); } while(q && lq != q){ lq = q; var tm = q.match(tagTokenRe); if(type == "select"){ if(tm){ if(tm[1] == "#"){ fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");'; }else{ fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");'; } q = q.replace(tm[0], ""); }else if(q.substr(0, 1) != '@'){ fn[fn.length] = 'n = getNodes(n, mode, "*");'; } }else{ if(tm){ if(tm[1] == "#"){ fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");'; }else{ fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");'; } q = q.replace(tm[0], ""); } } while(!(mm = q.match(modeRe))){ var matched = false; for(var j = 0; j < tklen; j++){ var t = tk[j]; var m = q.match(t.re); if(m){ fn[fn.length] = t.select.replace(tplRe, function(x, i){ return m[i]; }); q = q.replace(m[0], ""); matched = true; break; } } if(!matched){ throw 'Error parsing selector, parsing failed at "' + q + '"'; } } if(mm[1]){ fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";'; q = q.replace(mm[1], ""); } } fn[fn.length] = "return nodup(n);\n}"; eval(fn.join("")); return f; }, select : function(path, root, type){ if(!root || root == document){ root = document; } if(typeof root == "string"){ root = document.getElementById(root); } var paths = path.split(","); var results = []; for(var i = 0, len = paths.length; i < len; i++){ var p = paths[i].replace(trimRe, ""); if(!cache[p]){ cache[p] = Ext.DomQuery.compile(p); if(!cache[p]){ throw p + " is not a valid selector"; } } var result = cache[p](root); if(result && result != document){ results = results.concat(result); } } if(paths.length > 1){ return nodup(results); } return results; }, selectNode : function(path, root){ return Ext.DomQuery.select(path, root)[0]; }, selectValue : function(path, root, defaultValue){ path = path.replace(trimRe, ""); if(!valueCache[path]){ valueCache[path] = Ext.DomQuery.compile(path, "select"); } var n = valueCache[path](root); n = n[0] ? n[0] : n; var v = (n && n.firstChild ? n.firstChild.nodeValue : null); return ((v === null||v === undefined||v==='') ? defaultValue : v); }, selectNumber : function(path, root, defaultValue){ var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0); return parseFloat(v); }, is : function(el, ss){ if(typeof el == "string"){ el = document.getElementById(el); } var isArray = Ext.isArray(el); var result = Ext.DomQuery.filter(isArray ? el : [el], ss); return isArray ? (result.length == el.length) : (result.length > 0); }, filter : function(els, ss, nonMatches){ ss = ss.replace(trimRe, ""); if(!simpleCache[ss]){ simpleCache[ss] = Ext.DomQuery.compile(ss, "simple"); } var result = simpleCache[ss](els); return nonMatches ? quickDiff(result, els) : result; }, matchers : [{ re: /^\.([\w-]+)/, select: 'n = byClassName(n, null, " {1} ");' }, { re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/, select: 'n = byPseudo(n, "{1}", "{2}");' },{ re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/, select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");' }, { re: /^#([\w-]+)/, select: 'n = byId(n, null, "{1}");' },{ re: /^@([\w-]+)/, select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};' } ], operators : { "=" : function(a, v){ return a == v; }, "!=" : function(a, v){ return a != v; }, "^=" : function(a, v){ return a && a.substr(0, v.length) == v; }, "$=" : function(a, v){ return a && a.substr(a.length-v.length) == v; }, "*=" : function(a, v){ return a && a.indexOf(v) !== -1; }, "%=" : function(a, v){ return (a % v) == 0; }, "|=" : function(a, v){ return a && (a == v || a.substr(0, v.length+1) == v+'-'); }, "~=" : function(a, v){ return a && (' '+a+' ').indexOf(' '+v+' ') != -1; } }, pseudos : { "first-child" : function(c){ var r = [], ri = -1, n; for(var i = 0, ci; ci = n = c[i]; i++){ while((n = n.previousSibling) && n.nodeType != 1); if(!n){ r[++ri] = ci; } } return r; }, "last-child" : function(c){ var r = [], ri = -1, n; for(var i = 0, ci; ci = n = c[i]; i++){ while((n = n.nextSibling) && n.nodeType != 1); if(!n){ r[++ri] = ci; } } return r; }, "nth-child" : function(c, a) { var r = [], ri = -1; var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a); var f = (m[1] || 1) - 0, l = m[2] - 0; for(var i = 0, n; n = c[i]; i++){ var pn = n.parentNode; if (batch != pn._batch) { var j = 0; for(var cn = pn.firstChild; cn; cn = cn.nextSibling){ if(cn.nodeType == 1){ cn.nodeIndex = ++j; } } pn._batch = batch; } if (f == 1) { if (l == 0 || n.nodeIndex == l){ r[++ri] = n; } } else if ((n.nodeIndex + l) % f == 0){ r[++ri] = n; } } return r; }, "only-child" : function(c){ var r = [], ri = -1;; for(var i = 0, ci; ci = c[i]; i++){ if(!prev(ci) && !next(ci)){ r[++ri] = ci; } } return r; }, "empty" : function(c){ var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ var cns = ci.childNodes, j = 0, cn, empty = true; while(cn = cns[j]){ ++j; if(cn.nodeType == 1 || cn.nodeType == 3){ empty = false; break; } } if(empty){ r[++ri] = ci; } } return r; }, "contains" : function(c, v){ var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ if((ci.textContent||ci.innerText||'').indexOf(v) != -1){ r[++ri] = ci; } } return r; }, "nodeValue" : function(c, v){ var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ if(ci.firstChild && ci.firstChild.nodeValue == v){ r[++ri] = ci; } } return r; }, "checked" : function(c){ var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ if(ci.checked == true){ r[++ri] = ci; } } return r; }, "not" : function(c, ss){ return Ext.DomQuery.filter(c, ss, true); }, "any" : function(c, selectors){ var ss = selectors.split('|'); var r = [], ri = -1, s; for(var i = 0, ci; ci = c[i]; i++){ for(var j = 0; s = ss[j]; j++){ if(Ext.DomQuery.is(ci, s)){ r[++ri] = ci; break; } } } return r; }, "odd" : function(c){ return this["nth-child"](c, "odd"); }, "even" : function(c){ return this["nth-child"](c, "even"); }, "nth" : function(c, a){ return c[a-1] || []; }, "first" : function(c){ return c[0] || []; }, "last" : function(c){ return c[c.length-1] || []; }, "has" : function(c, ss){ var s = Ext.DomQuery.select; var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ if(s(ss, ci).length > 0){ r[++ri] = ci; } } return r; }, "next" : function(c, ss){ var is = Ext.DomQuery.is; var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ var n = next(ci); if(n && is(n, ss)){ r[++ri] = ci; } } return r; }, "prev" : function(c, ss){ var is = Ext.DomQuery.is; var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ var n = prev(ci); if(n && is(n, ss)){ r[++ri] = ci; } } return r; } } }; }(); Ext.query = Ext.DomQuery.select; Ext.util.Observable = function(){ if(this.listeners){ this.on(this.listeners); delete this.listeners; } }; Ext.util.Observable.prototype = { fireEvent : function(){ if(this.eventsSuspended !== true){ var ce = this.events[arguments[0].toLowerCase()]; if(typeof ce == "object"){ return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1)); } } return true; }, filterOptRe : /^(?:scope|delay|buffer|single)$/, addListener : function(eventName, fn, scope, o){ if(typeof eventName == "object"){ o = eventName; for(var e in o){ if(this.filterOptRe.test(e)){ continue; } if(typeof o[e] == "function"){ this.addListener(e, o[e], o.scope, o); }else{ this.addListener(e, o[e].fn, o[e].scope, o[e]); } } return; } o = (!o || typeof o == "boolean") ? {} : o; eventName = eventName.toLowerCase(); var ce = this.events[eventName] || true; if(typeof ce == "boolean"){ ce = new Ext.util.Event(this, eventName); this.events[eventName] = ce; } ce.addListener(fn, scope, o); }, removeListener : function(eventName, fn, scope){ var ce = this.events[eventName.toLowerCase()]; if(typeof ce == "object"){ ce.removeListener(fn, scope); } }, purgeListeners : function(){ for(var evt in this.events){ if(typeof this.events[evt] == "object"){ this.events[evt].clearListeners(); } } }, relayEvents : function(o, events){ var createHandler = function(ename){ return function(){ return this.fireEvent.apply(this, Ext.combine(ename, Array.prototype.slice.call(arguments, 0))); }; }; for(var i = 0, len = events.length; i < len; i++){ var ename = events[i]; if(!this.events[ename]){ this.events[ename] = true; }; o.on(ename, createHandler(ename), this); } }, addEvents : function(o){ if(!this.events){ this.events = {}; } if(typeof o == 'string'){ for(var i = 0, a = arguments, v; v = a[i]; i++){ if(!this.events[a[i]]){ o[a[i]] = true; } } }else{ Ext.applyIf(this.events, o); } }, hasListener : function(eventName){ var e = this.events[eventName]; return typeof e == "object" && e.listeners.length > 0; }, suspendEvents : function(){ this.eventsSuspended = true; }, resumeEvents : function(){ this.eventsSuspended = false; }, getMethodEvent : function(method){ if(!this.methodEvents){ this.methodEvents = {}; } var e = this.methodEvents[method]; if(!e){ e = {}; this.methodEvents[method] = e; e.originalFn = this[method]; e.methodName = method; e.before = []; e.after = []; var returnValue, v, cancel; var obj = this; var makeCall = function(fn, scope, args){ if((v = fn.apply(scope || obj, args)) !== undefined){ if(typeof v === 'object'){ if(v.returnValue !== undefined){ returnValue = v.returnValue; }else{ returnValue = v; } if(v.cancel === true){ cancel = true; } }else if(v === false){ cancel = true; }else { returnValue = v; } } } this[method] = function(){ returnValue = v = undefined; cancel = false; var args = Array.prototype.slice.call(arguments, 0); for(var i = 0, len = e.before.length; i < len; i++){ makeCall(e.before[i].fn, e.before[i].scope, args); if(cancel){ return returnValue; } } if((v = e.originalFn.apply(obj, args)) !== undefined){ returnValue = v; } for(var i = 0, len = e.after.length; i < len; i++){ makeCall(e.after[i].fn, e.after[i].scope, args); if(cancel){ return returnValue; } } return returnValue; }; } return e; }, beforeMethod : function(method, fn, scope){ var e = this.getMethodEvent(method); e.before.push({fn: fn, scope: scope}); }, afterMethod : function(method, fn, scope){ var e = this.getMethodEvent(method); e.after.push({fn: fn, scope: scope}); }, removeMethodListener : function(method, fn, scope){ var e = this.getMethodEvent(method); for(var i = 0, len = e.before.length; i < len; i++){ if(e.before[i].fn == fn && e.before[i].scope == scope){ e.before.splice(i, 1); return; } } for(var i = 0, len = e.after.length; i < len; i++){ if(e.after[i].fn == fn && e.after[i].scope == scope){ e.after.splice(i, 1); return; } } } }; Ext.util.Observable.prototype.on = Ext.util.Observable.prototype.addListener; Ext.util.Observable.prototype.un = Ext.util.Observable.prototype.removeListener; Ext.util.Observable.capture = function(o, fn, scope){ o.fireEvent = o.fireEvent.createInterceptor(fn, scope); }; Ext.util.Observable.releaseCapture = function(o){ o.fireEvent = Ext.util.Observable.prototype.fireEvent; }; (function(){ var createBuffered = function(h, o, scope){ var task = new Ext.util.DelayedTask(); return function(){ task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0)); }; }; var createSingle = function(h, e, fn, scope){ return function(){ e.removeListener(fn, scope); return h.apply(scope, arguments); }; }; var createDelayed = function(h, o, scope){ return function(){ var args = Array.prototype.slice.call(arguments, 0); setTimeout(function(){ h.apply(scope, args); }, o.delay || 10); }; }; Ext.util.Event = function(obj, name){ this.name = name; this.obj = obj; this.listeners = []; }; Ext.util.Event.prototype = { addListener : function(fn, scope, options){ scope = scope || this.obj; if(!this.isListening(fn, scope)){ var l = this.createListener(fn, scope, options); if(!this.firing){ this.listeners.push(l); }else{ this.listeners = this.listeners.slice(0); this.listeners.push(l); } } }, createListener : function(fn, scope, o){ o = o || {}; scope = scope || this.obj; var l = {fn: fn, scope: scope, options: o}; var h = fn; if(o.delay){ h = createDelayed(h, o, scope); } if(o.single){ h = createSingle(h, this, fn, scope); } if(o.buffer){ h = createBuffered(h, o, scope); } l.fireFn = h; return l; }, findListener : function(fn, scope){ scope = scope || this.obj; var ls = this.listeners; for(var i = 0, len = ls.length; i < len; i++){ var l = ls[i]; if(l.fn == fn && l.scope == scope){ return i; } } return -1; }, isListening : function(fn, scope){ return this.findListener(fn, scope) != -1; }, removeListener : function(fn, scope){ var index; if((index = this.findListener(fn, scope)) != -1){ if(!this.firing){ this.listeners.splice(index, 1); }else{ this.listeners = this.listeners.slice(0); this.listeners.splice(index, 1); } return true; } return false; }, clearListeners : function(){ this.listeners = []; }, fire : function(){ var ls = this.listeners, scope, len = ls.length; if(len > 0){ this.firing = true; var args = Array.prototype.slice.call(arguments, 0); for(var i = 0; i < len; i++){ var l = ls[i]; if(l.fireFn.apply(l.scope||this.obj||window, arguments) === false){ this.firing = false; return false; } } this.firing = false; } return true; } }; })(); Ext.EventManager = function(){ var docReadyEvent, docReadyProcId, docReadyState = false; var resizeEvent, resizeTask, textEvent, textSize; var E = Ext.lib.Event; var D = Ext.lib.Dom; var fireDocReady = function(){ if(!docReadyState){ docReadyState = true; Ext.isReady = true; if(docReadyProcId){ clearInterval(docReadyProcId); } if(Ext.isGecko || Ext.isOpera) { document.removeEventListener("DOMContentLoaded", fireDocReady, false); } if(Ext.isIE){ var defer = document.getElementById("ie-deferred-loader"); if(defer){ defer.onreadystatechange = null; defer.parentNode.removeChild(defer); } } if(docReadyEvent){ docReadyEvent.fire(); docReadyEvent.clearListeners(); } } }; var initDocReady = function(){ docReadyEvent = new Ext.util.Event(); if(Ext.isGecko || Ext.isOpera) { document.addEventListener("DOMContentLoaded", fireDocReady, false); }else if(Ext.isIE){ document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>"); var defer = document.getElementById("ie-deferred-loader"); defer.onreadystatechange = function(){ if(this.readyState == "complete"){ fireDocReady(); } }; }else if(Ext.isSafari){ docReadyProcId = setInterval(function(){ var rs = document.readyState; if(rs == "complete") { fireDocReady(); } }, 10); } E.on(window, "load", fireDocReady); }; var createBuffered = function(h, o){ var task = new Ext.util.DelayedTask(h); return function(e){ e = new Ext.EventObjectImpl(e); task.delay(o.buffer, h, null, [e]); }; }; var createSingle = function(h, el, ename, fn){ return function(e){ Ext.EventManager.removeListener(el, ename, fn); h(e); }; }; var createDelayed = function(h, o){ return function(e){ e = new Ext.EventObjectImpl(e); setTimeout(function(){ h(e); }, o.delay || 10); }; }; var listen = function(element, ename, opt, fn, scope){ var o = (!opt || typeof opt == "boolean") ? {} : opt; fn = fn || o.fn; scope = scope || o.scope; var el = Ext.getDom(element); if(!el){ throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.'; } var h = function(e){ e = Ext.EventObject.setEvent(e); var t; if(o.delegate){ t = e.getTarget(o.delegate, el); if(!t){ return; } }else{ t = e.target; } if(o.stopEvent === true){ e.stopEvent(); } if(o.preventDefault === true){ e.preventDefault(); } if(o.stopPropagation === true){ e.stopPropagation(); } if(o.normalized === false){ e = e.browserEvent; } fn.call(scope || el, e, t, o); }; if(o.delay){ h = createDelayed(h, o); } if(o.single){ h = createSingle(h, el, ename, fn); } if(o.buffer){ h = createBuffered(h, o); } fn._handlers = fn._handlers || []; fn._handlers.push([Ext.id(el), ename, h]); E.on(el, ename, h); if(ename == "mousewheel" && el.addEventListener){ el.addEventListener("DOMMouseScroll", h, false); E.on(window, 'unload', function(){ el.removeEventListener("DOMMouseScroll", h, false); }); } if(ename == "mousedown" && el == document){ Ext.EventManager.stoppedMouseDownEvent.addListener(h); } return h; }; var stopListening = function(el, ename, fn){ var id = Ext.id(el), hds = fn._handlers, hd = fn; if(hds){ for(var i = 0, len = hds.length; i < len; i++){ var h = hds[i]; if(h[0] == id && h[1] == ename){ hd = h[2]; hds.splice(i, 1); break; } } } E.un(el, ename, hd); el = Ext.getDom(el); if(ename == "mousewheel" && el.addEventListener){ el.removeEventListener("DOMMouseScroll", hd, false); } if(ename == "mousedown" && el == document){ Ext.EventManager.stoppedMouseDownEvent.removeListener(hd); } }; var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/; var pub = { addListener : function(element, eventName, fn, scope, options){ if(typeof eventName == "object"){ var o = eventName; for(var e in o){ if(propRe.test(e)){ continue; } if(typeof o[e] == "function"){ listen(element, e, o, o[e], o.scope); }else{ listen(element, e, o[e]); } } return; } return listen(element, eventName, options, fn, scope); }, removeListener : function(element, eventName, fn){ return stopListening(element, eventName, fn); }, onDocumentReady : function(fn, scope, options){ if(docReadyState){ docReadyEvent.addListener(fn, scope, options); docReadyEvent.fire(); docReadyEvent.clearListeners(); return; } if(!docReadyEvent){ initDocReady(); } docReadyEvent.addListener(fn, scope, options); }, onWindowResize : function(fn, scope, options){ if(!resizeEvent){ resizeEvent = new Ext.util.Event(); resizeTask = new Ext.util.DelayedTask(function(){ resizeEvent.fire(D.getViewWidth(), D.getViewHeight()); }); E.on(window, "resize", this.fireWindowResize, this); } resizeEvent.addListener(fn, scope, options); }, fireWindowResize : function(){ if(resizeEvent){ if((Ext.isIE||Ext.isAir) && resizeTask){ resizeTask.delay(50); }else{ resizeEvent.fire(D.getViewWidth(), D.getViewHeight()); } } }, onTextResize : function(fn, scope, options){ if(!textEvent){ textEvent = new Ext.util.Event(); var textEl = new Ext.Element(document.createElement('div')); textEl.dom.className = 'x-text-resize'; textEl.dom.innerHTML = 'X'; textEl.appendTo(document.body); textSize = textEl.dom.offsetHeight; setInterval(function(){ if(textEl.dom.offsetHeight != textSize){ textEvent.fire(textSize, textSize = textEl.dom.offsetHeight); } }, this.textResizeInterval); } textEvent.addListener(fn, scope, options); }, removeResizeListener : function(fn, scope){ if(resizeEvent){ resizeEvent.removeListener(fn, scope); } }, fireResize : function(){ if(resizeEvent){ resizeEvent.fire(D.getViewWidth(), D.getViewHeight()); } }, ieDeferSrc : false, textResizeInterval : 50 }; pub.on = pub.addListener; pub.un = pub.removeListener; pub.stoppedMouseDownEvent = new Ext.util.Event(); return pub; }(); Ext.onReady = Ext.EventManager.onDocumentReady; Ext.onReady(function(){ var bd = Ext.getBody(); if(!bd){ return; } var cls = [ Ext.isIE ? "ext-ie " + (Ext.isIE6 ? 'ext-ie6' : 'ext-ie7') : Ext.isGecko ? "ext-gecko" : Ext.isOpera ? "ext-opera" : Ext.isSafari ? "ext-safari" : ""]; if(Ext.isMac){ cls.push("ext-mac"); } if(Ext.isLinux){ cls.push("ext-linux"); } if(Ext.isBorderBox){ cls.push('ext-border-box'); } if(Ext.isStrict){ var p = bd.dom.parentNode; if(p){ p.className += ' ext-strict'; } } bd.addClass(cls.join(' ')); }); Ext.EventObject = function(){ var E = Ext.lib.Event; var safariKeys = { 63234 : 37, 63235 : 39, 63232 : 38, 63233 : 40, 63276 : 33, 63277 : 34, 63272 : 46, 63273 : 36, 63275 : 35 }; var btnMap = Ext.isIE ? {1:0,4:1,2:2} : (Ext.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2}); Ext.EventObjectImpl = function(e){ if(e){ this.setEvent(e.browserEvent || e); } }; Ext.EventObjectImpl.prototype = { browserEvent : null, button : -1, shiftKey : false, ctrlKey : false, altKey : false, BACKSPACE : 8, TAB : 9, RETURN : 13, ENTER : 13, SHIFT : 16, CONTROL : 17, ESC : 27, SPACE : 32, PAGEUP : 33, PAGEDOWN : 34, END : 35, HOME : 36, LEFT : 37, UP : 38, RIGHT : 39, DOWN : 40, DELETE : 46, F5 : 116, setEvent : function(e){ if(e == this || (e && e.browserEvent)){ return e; } this.browserEvent = e; if(e){ this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1); if(e.type == 'click' && this.button == -1){ this.button = 0; } this.type = e.type; this.shiftKey = e.shiftKey; this.ctrlKey = e.ctrlKey || e.metaKey; this.altKey = e.altKey; this.keyCode = e.keyCode; this.charCode = e.charCode; this.target = E.getTarget(e); this.xy = E.getXY(e); }else{ this.button = -1; this.shiftKey = false; this.ctrlKey = false; this.altKey = false; this.keyCode = 0; this.charCode =0; this.target = null; this.xy = [0, 0]; } return this; }, stopEvent : function(){ if(this.browserEvent){ if(this.browserEvent.type == 'mousedown'){ Ext.EventManager.stoppedMouseDownEvent.fire(this); } E.stopEvent(this.browserEvent); } }, preventDefault : function(){ if(this.browserEvent){ E.preventDefault(this.browserEvent); } }, isNavKeyPress : function(){ var k = this.keyCode; k = Ext.isSafari ? (safariKeys[k] || k) : k; return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC; }, isSpecialKey : function(){ var k = this.keyCode; return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 || (k == 16) || (k == 17) || (k >= 18 && k <= 20) || (k >= 33 && k <= 35) || (k >= 36 && k <= 39) || (k >= 44 && k <= 45); }, stopPropagation : function(){ if(this.browserEvent){ if(this.browserEvent.type == 'mousedown'){ Ext.EventManager.stoppedMouseDownEvent.fire(this); } E.stopPropagation(this.browserEvent); } }, getCharCode : function(){ return this.charCode || this.keyCode; }, getKey : function(){ var k = this.keyCode || this.charCode; return Ext.isSafari ? (safariKeys[k] || k) : k; }, getPageX : function(){ return this.xy[0]; }, getPageY : function(){ return this.xy[1]; }, getTime : function(){ if(this.browserEvent){ return E.getTime(this.browserEvent); } return null; }, getXY : function(){ return this.xy; }, getTarget : function(selector, maxDepth, returnEl){ var t = Ext.get(this.target); return selector ? t.findParent(selector, maxDepth, returnEl) : (returnEl ? t : this.target); }, getRelatedTarget : function(){ if(this.browserEvent){ return E.getRelatedTarget(this.browserEvent); } return null; }, getWheelDelta : function(){ var e = this.browserEvent; var delta = 0; if(e.wheelDelta){ delta = e.wheelDelta/120; }else if(e.detail){ delta = -e.detail/3; } return delta; }, hasModifier : function(){ return ((this.ctrlKey || this.altKey) || this.shiftKey) ? true : false; }, within : function(el, related){ var t = this[related ? "getRelatedTarget" : "getTarget"](); return t && Ext.fly(el).contains(t); }, getPoint : function(){ return new Ext.lib.Point(this.xy[0], this.xy[1]); } }; return new Ext.EventObjectImpl(); }(); (function(){ var D = Ext.lib.Dom; var E = Ext.lib.Event; var A = Ext.lib.Anim; var propCache = {}; var camelRe = /(-[a-z])/gi; var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); }; var view = document.defaultView; Ext.Element = function(element, forceNew){ var dom = typeof element == "string" ? document.getElementById(element) : element; if(!dom){ return null; } var id = dom.id; if(forceNew !== true && id && Ext.Element.cache[id]){ return Ext.Element.cache[id]; } this.dom = dom; this.id = id || Ext.id(dom); }; var El = Ext.Element; El.prototype = { originalDisplay : "", visibilityMode : 1, defaultUnit : "px", setVisibilityMode : function(visMode){ this.visibilityMode = visMode; return this; }, enableDisplayMode : function(display){ this.setVisibilityMode(El.DISPLAY); if(typeof display != "undefined") this.originalDisplay = display; return this; }, findParent : function(simpleSelector, maxDepth, returnEl){ var p = this.dom, b = document.body, depth = 0, dq = Ext.DomQuery, stopEl; maxDepth = maxDepth || 50; if(typeof maxDepth != "number"){ stopEl = Ext.getDom(maxDepth); maxDepth = 10; } while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){ if(dq.is(p, simpleSelector)){ return returnEl ? Ext.get(p) : p; } depth++; p = p.parentNode; } return null; }, findParentNode : function(simpleSelector, maxDepth, returnEl){ var p = Ext.fly(this.dom.parentNode, '_internal'); return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null; }, up : function(simpleSelector, maxDepth){ return this.findParentNode(simpleSelector, maxDepth, true); }, is : function(simpleSelector){ return Ext.DomQuery.is(this.dom, simpleSelector); }, animate : function(args, duration, onComplete, easing, animType){ this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType); return this; }, anim : function(args, opt, animType, defaultDur, defaultEase, cb){ animType = animType || 'run'; opt = opt || {}; var anim = Ext.lib.Anim[animType]( this.dom, args, (opt.duration || defaultDur) || .35, (opt.easing || defaultEase) || 'easeOut', function(){ Ext.callback(cb, this); Ext.callback(opt.callback, opt.scope || this, [this, opt]); }, this ); opt.anim = anim; return anim; }, preanim : function(a, i){ return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]}); }, clean : function(forceReclean){ if(this.isCleaned && forceReclean !== true){ return this; } var ns = /\S/; var d = this.dom, n = d.firstChild, ni = -1; while(n){ var nx = n.nextSibling; if(n.nodeType == 3 && !ns.test(n.nodeValue)){ d.removeChild(n); }else{ n.nodeIndex = ++ni; } n = nx; } this.isCleaned = true; return this; }, scrollIntoView : function(container, hscroll){ var c = Ext.getDom(container) || Ext.getBody().dom; var el = this.dom; var o = this.getOffsetsTo(c), l = o[0] + c.scrollLeft, t = o[1] + c.scrollTop, b = t+el.offsetHeight, r = l+el.offsetWidth; var ch = c.clientHeight; var ct = parseInt(c.scrollTop, 10); var cl = parseInt(c.scrollLeft, 10); var cb = ct + ch; var cr = cl + c.clientWidth; if(el.offsetHeight > ch || t < ct){ c.scrollTop = t; }else if(b > cb){ c.scrollTop = b-ch; } c.scrollTop = c.scrollTop; if(hscroll !== false){ if(el.offsetWidth > c.clientWidth || l < cl){ c.scrollLeft = l; }else if(r > cr){ c.scrollLeft = r-c.clientWidth; } c.scrollLeft = c.scrollLeft; } return this; }, scrollChildIntoView : function(child, hscroll){ Ext.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll); }, autoHeight : function(animate, duration, onComplete, easing){ var oldHeight = this.getHeight(); this.clip(); this.setHeight(1); setTimeout(function(){ var height = parseInt(this.dom.scrollHeight, 10); if(!animate){ this.setHeight(height); this.unclip(); if(typeof onComplete == "function"){ onComplete(); } }else{ this.setHeight(oldHeight); this.setHeight(height, animate, duration, function(){ this.unclip(); if(typeof onComplete == "function") onComplete(); }.createDelegate(this), easing); } }.createDelegate(this), 0); return this; }, contains : function(el){ if(!el){return false;} return D.isAncestor(this.dom, el.dom ? el.dom : el); }, isVisible : function(deep) { var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none"); if(deep !== true || !vis){ return vis; } var p = this.dom.parentNode; while(p && p.tagName.toLowerCase() != "body"){ if(!Ext.fly(p, '_isVisible').isVisible()){ return false; } p = p.parentNode; } return true; }, select : function(selector, unique){ return El.select(selector, unique, this.dom); }, query : function(selector, unique){ return Ext.DomQuery.select(selector, this.dom); }, child : function(selector, returnDom){ var n = Ext.DomQuery.selectNode(selector, this.dom); return returnDom ? n : Ext.get(n); }, down : function(selector, returnDom){ var n = Ext.DomQuery.selectNode(" > " + selector, this.dom); return returnDom ? n : Ext.get(n); }, initDD : function(group, config, overrides){ var dd = new Ext.dd.DD(Ext.id(this.dom), group, config); return Ext.apply(dd, overrides); }, initDDProxy : function(group, config, overrides){ var dd = new Ext.dd.DDProxy(Ext.id(this.dom), group, config); return Ext.apply(dd, overrides); }, initDDTarget : function(group, config, overrides){ var dd = new Ext.dd.DDTarget(Ext.id(this.dom), group, config); return Ext.apply(dd, overrides); }, setVisible : function(visible, animate){ if(!animate || !A){ if(this.visibilityMode == El.DISPLAY){ this.setDisplayed(visible); }else{ this.fixDisplay(); this.dom.style.visibility = visible ? "visible" : "hidden"; } }else{ var dom = this.dom; var visMode = this.visibilityMode; if(visible){ this.setOpacity(.01); this.setVisible(true); } this.anim({opacity: { to: (visible?1:0) }}, this.preanim(arguments, 1), null, .35, 'easeIn', function(){ if(!visible){ if(visMode == El.DISPLAY){ dom.style.display = "none"; }else{ dom.style.visibility = "hidden"; } Ext.get(dom).setOpacity(1); } }); } return this; }, isDisplayed : function() { return this.getStyle("display") != "none"; }, toggle : function(animate){ this.setVisible(!this.isVisible(), this.preanim(arguments, 0)); return this; }, setDisplayed : function(value) { if(typeof value == "boolean"){ value = value ? this.originalDisplay : "none"; } this.setStyle("display", value); return this; }, focus : function() { try{ this.dom.focus(); }catch(e){} return this; }, blur : function() { try{ this.dom.blur(); }catch(e){} return this; }, addClass : function(className){ if(Ext.isArray(className)){ for(var i = 0, len = className.length; i < len; i++) { this.addClass(className[i]); } }else{ if(className && !this.hasClass(className)){ this.dom.className = this.dom.className + " " + className; } } return this; }, radioClass : function(className){ var siblings = this.dom.parentNode.childNodes; for(var i = 0; i < siblings.length; i++) { var s = siblings[i]; if(s.nodeType == 1){ Ext.get(s).removeClass(className); } } this.addClass(className); return this; }, removeClass : function(className){ if(!className || !this.dom.className){ return this; } if(Ext.isArray(className)){ for(var i = 0, len = className.length; i < len; i++) { this.removeClass(className[i]); } }else{ if(this.hasClass(className)){ var re = this.classReCache[className]; if (!re) { re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g"); this.classReCache[className] = re; } this.dom.className = this.dom.className.replace(re, " "); } } return this; }, classReCache: {}, toggleClass : function(className){ if(this.hasClass(className)){ this.removeClass(className); }else{ this.addClass(className); } return this; }, hasClass : function(className){ return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1; }, replaceClass : function(oldClassName, newClassName){ this.removeClass(oldClassName); this.addClass(newClassName); return this; }, getStyles : function(){ var a = arguments, len = a.length, r = {}; for(var i = 0; i < len; i++){ r[a[i]] = this.getStyle(a[i]); } return r; }, getStyle : function(){ return view && view.getComputedStyle ? function(prop){ var el = this.dom, v, cs, camel; if(prop == 'float'){ prop = "cssFloat"; } if(v = el.style[prop]){ return v; } if(cs = view.getComputedStyle(el, "")){ if(!(camel = propCache[prop])){ camel = propCache[prop] = prop.replace(camelRe, camelFn); } return cs[camel]; } return null; } : function(prop){ var el = this.dom, v, cs, camel; if(prop == 'opacity'){ if(typeof el.style.filter == 'string'){ var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i); if(m){ var fv = parseFloat(m[1]); if(!isNaN(fv)){ return fv ? fv / 100 : 0; } } } return 1; }else if(prop == 'float'){ prop = "styleFloat"; } if(!(camel = propCache[prop])){ camel = propCache[prop] = prop.replace(camelRe, camelFn); } if(v = el.style[camel]){ return v; } if(cs = el.currentStyle){ return cs[camel]; } return null; }; }(), setStyle : function(prop, value){ if(typeof prop == "string"){ var camel; if(!(camel = propCache[prop])){ camel = propCache[prop] = prop.replace(camelRe, camelFn); } if(camel == 'opacity') { this.setOpacity(value); }else{ this.dom.style[camel] = value; } }else{ for(var style in prop){ if(typeof prop[style] != "function"){ this.setStyle(style, prop[style]); } } } return this; }, applyStyles : function(style){ Ext.DomHelper.applyStyles(this.dom, style); return this; }, getX : function(){ return D.getX(this.dom); }, getY : function(){ return D.getY(this.dom); }, getXY : function(){ return D.getXY(this.dom); }, getOffsetsTo : function(el){ var o = this.getXY(); var e = Ext.fly(el, '_internal').getXY(); return [o[0]-e[0],o[1]-e[1]]; }, setX : function(x, animate){ if(!animate || !A){ D.setX(this.dom, x); }else{ this.setXY([x, this.getY()], this.preanim(arguments, 1)); } return this; }, setY : function(y, animate){ if(!animate || !A){ D.setY(this.dom, y); }else{ this.setXY([this.getX(), y], this.preanim(arguments, 1)); } return this; }, setLeft : function(left){ this.setStyle("left", this.addUnits(left)); return this; }, setTop : function(top){ this.setStyle("top", this.addUnits(top)); return this; }, setRight : function(right){ this.setStyle("right", this.addUnits(right)); return this; }, setBottom : function(bottom){ this.setStyle("bottom", this.addUnits(bottom)); return this; }, setXY : function(pos, animate){ if(!animate || !A){ D.setXY(this.dom, pos); }else{ this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion'); } return this; }, setLocation : function(x, y, animate){ this.setXY([x, y], this.preanim(arguments, 2)); return this; }, moveTo : function(x, y, animate){ this.setXY([x, y], this.preanim(arguments, 2)); return this; }, getRegion : function(){ return D.getRegion(this.dom); }, getHeight : function(contentHeight){ var h = this.dom.offsetHeight || 0; h = contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb"); return h < 0 ? 0 : h; }, getWidth : function(contentWidth){ var w = this.dom.offsetWidth || 0; w = contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr"); return w < 0 ? 0 : w; }, getComputedHeight : function(){ var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight); if(!h){ h = parseInt(this.getStyle('height'), 10) || 0; if(!this.isBorderBox()){ h += this.getFrameWidth('tb'); } } return h; }, getComputedWidth : function(){ var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth); if(!w){ w = parseInt(this.getStyle('width'), 10) || 0; if(!this.isBorderBox()){ w += this.getFrameWidth('lr'); } } return w; }, getSize : function(contentSize){ return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)}; }, getStyleSize : function(){ var w, h, d = this.dom, s = d.style; if(s.width && s.width != 'auto'){ w = parseInt(s.width, 10); if(Ext.isBorderBox){ w -= this.getFrameWidth('lr'); } } if(s.height && s.height != 'auto'){ h = parseInt(s.height, 10); if(Ext.isBorderBox){ h -= this.getFrameWidth('tb'); } } return {width: w || this.getWidth(true), height: h || this.getHeight(true)}; }, getViewSize : function(){ var d = this.dom, doc = document, aw = 0, ah = 0; if(d == doc || d == doc.body){ return {width : D.getViewWidth(), height: D.getViewHeight()}; }else{ return { width : d.clientWidth, height: d.clientHeight }; } }, getValue : function(asNumber){ return asNumber ? parseInt(this.dom.value, 10) : this.dom.value; }, adjustWidth : function(width){ if(typeof width == "number"){ if(this.autoBoxAdjust && !this.isBorderBox()){ width -= (this.getBorderWidth("lr") + this.getPadding("lr")); } if(width < 0){ width = 0; } } return width; }, adjustHeight : function(height){ if(typeof height == "number"){ if(this.autoBoxAdjust && !this.isBorderBox()){ height -= (this.getBorderWidth("tb") + this.getPadding("tb")); } if(height < 0){ height = 0; } } return height; }, setWidth : function(width, animate){ width = this.adjustWidth(width); if(!animate || !A){ this.dom.style.width = this.addUnits(width); }else{ this.anim({width: {to: width}}, this.preanim(arguments, 1)); } return this; }, setHeight : function(height, animate){ height = this.adjustHeight(height); if(!animate || !A){ this.dom.style.height = this.addUnits(height); }else{ this.anim({height: {to: height}}, this.preanim(arguments, 1)); } return this; }, setSize : function(width, height, animate){ if(typeof width == "object"){ height = width.height; width = width.width; } width = this.adjustWidth(width); height = this.adjustHeight(height); if(!animate || !A){ this.dom.style.width = this.addUnits(width); this.dom.style.height = this.addUnits(height); }else{ this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2)); } return this; }, setBounds : function(x, y, width, height, animate){ if(!animate || !A){ this.setSize(width, height); this.setLocation(x, y); }else{ width = this.adjustWidth(width); height = this.adjustHeight(height); this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}}, this.preanim(arguments, 4), 'motion'); } return this; }, setRegion : function(region, animate){ this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1)); return this; }, addListener : function(eventName, fn, scope, options){ Ext.EventManager.on(this.dom, eventName, fn, scope || this, options); }, removeListener : function(eventName, fn){ Ext.EventManager.removeListener(this.dom, eventName, fn); return this; }, removeAllListeners : function(){ E.purgeElement(this.dom); return this; }, relayEvent : function(eventName, observable){ this.on(eventName, function(e){ observable.fireEvent(eventName, e); }); }, setOpacity : function(opacity, animate){ if(!animate || !A){ var s = this.dom.style; if(Ext.isIE){ s.zoom = 1; s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") + (opacity == 1 ? "" : " alpha(opacity=" + opacity * 100 + ")"); }else{ s.opacity = opacity; } }else{ this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn'); } return this; }, getLeft : function(local){ if(!local){ return this.getX(); }else{ return parseInt(this.getStyle("left"), 10) || 0; } }, getRight : function(local){ if(!local){ return this.getX() + this.getWidth(); }else{ return (this.getLeft(true) + this.getWidth()) || 0; } }, getTop : function(local) { if(!local){ return this.getY(); }else{ return parseInt(this.getStyle("top"), 10) || 0; } }, getBottom : function(local){ if(!local){ return this.getY() + this.getHeight(); }else{ return (this.getTop(true) + this.getHeight()) || 0; } }, position : function(pos, zIndex, x, y){ if(!pos){ if(this.getStyle('position') == 'static'){ this.setStyle('position', 'relative'); } }else{ this.setStyle("position", pos); } if(zIndex){ this.setStyle("z-index", zIndex); } if(x !== undefined && y !== undefined){ this.setXY([x, y]); }else if(x !== undefined){ this.setX(x); }else if(y !== undefined){ this.setY(y); } }, clearPositioning : function(value){ value = value ||''; this.setStyle({ "left": value, "right": value, "top": value, "bottom": value, "z-index": "", "position" : "static" }); return this; }, getPositioning : function(){ var l = this.getStyle("left"); var t = this.getStyle("top"); return { "position" : this.getStyle("position"), "left" : l, "right" : l ? "" : this.getStyle("right"), "top" : t, "bottom" : t ? "" : this.getStyle("bottom"), "z-index" : this.getStyle("z-index") }; }, getBorderWidth : function(side){ return this.addStyles(side, El.borders); }, getPadding : function(side){ return this.addStyles(side, El.paddings); }, setPositioning : function(pc){ this.applyStyles(pc); if(pc.right == "auto"){ this.dom.style.right = ""; } if(pc.bottom == "auto"){ this.dom.style.bottom = ""; } return this; }, fixDisplay : function(){ if(this.getStyle("display") == "none"){ this.setStyle("visibility", "hidden"); this.setStyle("display", this.originalDisplay); if(this.getStyle("display") == "none"){ this.setStyle("display", "block"); } } }, setOverflow : function(v){ if(v=='auto' && Ext.isMac && Ext.isGecko){ this.dom.style.overflow = 'hidden'; (function(){this.dom.style.overflow = 'auto';}).defer(1, this); }else{ this.dom.style.overflow = v; } }, setLeftTop : function(left, top){ this.dom.style.left = this.addUnits(left); this.dom.style.top = this.addUnits(top); return this; }, move : function(direction, distance, animate){ var xy = this.getXY(); direction = direction.toLowerCase(); switch(direction){ case "l": case "left": this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2)); break; case "r": case "right": this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2)); break; case "t": case "top": case "up": this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2)); break; case "b": case "bottom": case "down": this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2)); break; } return this; }, clip : function(){ if(!this.isClipped){ this.isClipped = true; this.originalClip = { "o": this.getStyle("overflow"), "x": this.getStyle("overflow-x"), "y": this.getStyle("overflow-y") }; this.setStyle("overflow", "hidden"); this.setStyle("overflow-x", "hidden"); this.setStyle("overflow-y", "hidden"); } return this; }, unclip : function(){ if(this.isClipped){ this.isClipped = false; var o = this.originalClip; if(o.o){this.setStyle("overflow", o.o);} if(o.x){this.setStyle("overflow-x", o.x);} if(o.y){this.setStyle("overflow-y", o.y);} } return this; }, getAnchorXY : function(anchor, local, s){ var w, h, vp = false; if(!s){ var d = this.dom; if(d == document.body || d == document){ vp = true; w = D.getViewWidth(); h = D.getViewHeight(); }else{ w = this.getWidth(); h = this.getHeight(); } }else{ w = s.width; h = s.height; } var x = 0, y = 0, r = Math.round; switch((anchor || "tl").toLowerCase()){ case "c": x = r(w*.5); y = r(h*.5); break; case "t": x = r(w*.5); y = 0; break; case "l": x = 0; y = r(h*.5); break; case "r": x = w; y = r(h*.5); break; case "b": x = r(w*.5); y = h; break; case "tl": x = 0; y = 0; break; case "bl": x = 0; y = h; break; case "br": x = w; y = h; break; case "tr": x = w; y = 0; break; } if(local === true){ return [x, y]; } if(vp){ var sc = this.getScroll(); return [x + sc.left, y + sc.top]; } var o = this.getXY(); return [x+o[0], y+o[1]]; }, getAlignToXY : function(el, p, o){ el = Ext.get(el); if(!el || !el.dom){ throw "Element.alignToXY with an element that doesn't exist"; } var d = this.dom; var c = false; var p1 = "", p2 = ""; o = o || [0,0]; if(!p){ p = "tl-bl"; }else if(p == "?"){ p = "tl-bl?"; }else if(p.indexOf("-") == -1){ p = "tl-" + p; } p = p.toLowerCase(); var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/); if(!m){ throw "Element.alignTo with an invalid alignment " + p; } p1 = m[1]; p2 = m[2]; c = !!m[3]; var a1 = this.getAnchorXY(p1, true); var a2 = el.getAnchorXY(p2, false); var x = a2[0] - a1[0] + o[0]; var y = a2[1] - a1[1] + o[1]; if(c){ var w = this.getWidth(), h = this.getHeight(), r = el.getRegion(); var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5; var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1); var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1); var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t")); var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r")); var doc = document; var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5; var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5; if((x+w) > dw + scrollX){ x = swapX ? r.left-w : dw+scrollX-w; } if(x < scrollX){ x = swapX ? r.right : scrollX; } if((y+h) > dh + scrollY){ y = swapY ? r.top-h : dh+scrollY-h; } if (y < scrollY){ y = swapY ? r.bottom : scrollY; } } return [x,y]; }, getConstrainToXY : function(){ var os = {top:0, left:0, bottom:0, right: 0}; return function(el, local, offsets, proposedXY){ el = Ext.get(el); offsets = offsets ? Ext.applyIf(offsets, os) : os; var vw, vh, vx = 0, vy = 0; if(el.dom == document.body || el.dom == document){ vw = Ext.lib.Dom.getViewWidth(); vh = Ext.lib.Dom.getViewHeight(); }else{ vw = el.dom.clientWidth; vh = el.dom.clientHeight; if(!local){ var vxy = el.getXY(); vx = vxy[0]; vy = vxy[1]; } } var s = el.getScroll(); vx += offsets.left + s.left; vy += offsets.top + s.top; vw -= offsets.right; vh -= offsets.bottom; var vr = vx+vw; var vb = vy+vh; var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]); var x = xy[0], y = xy[1]; var w = this.dom.offsetWidth, h = this.dom.offsetHeight; var moved = false; if((x + w) > vr){ x = vr - w; moved = true; } if((y + h) > vb){ y = vb - h; moved = true; } if(x < vx){ x = vx; moved = true; } if(y < vy){ y = vy; moved = true; } return moved ? [x, y] : false; }; }(), adjustForConstraints : function(xy, parent, offsets){ return this.getConstrainToXY(parent || document, false, offsets, xy) || xy; }, alignTo : function(element, position, offsets, animate){ var xy = this.getAlignToXY(element, position, offsets); this.setXY(xy, this.preanim(arguments, 3)); return this; }, anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){ var action = function(){ this.alignTo(el, alignment, offsets, animate); Ext.callback(callback, this); }; Ext.EventManager.onWindowResize(action, this); var tm = typeof monitorScroll; if(tm != 'undefined'){ Ext.EventManager.on(window, 'scroll', action, this, {buffer: tm == 'number' ? monitorScroll : 50}); } action.call(this); return this; }, clearOpacity : function(){ if (window.ActiveXObject) { if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){ this.dom.style.filter = ""; } } else { this.dom.style.opacity = ""; this.dom.style["-moz-opacity"] = ""; this.dom.style["-khtml-opacity"] = ""; } return this; }, hide : function(animate){ this.setVisible(false, this.preanim(arguments, 0)); return this; }, show : function(animate){ this.setVisible(true, this.preanim(arguments, 0)); return this; }, addUnits : function(size){ return Ext.Element.addUnits(size, this.defaultUnit); }, update : function(html, loadScripts, callback){ if(typeof html == "undefined"){ html = ""; } if(loadScripts !== true){ this.dom.innerHTML = html; if(typeof callback == "function"){ callback(); } return this; } var id = Ext.id(); var dom = this.dom; html += '<span id="' + id + '"></span>'; E.onAvailable(id, function(){ var hd = document.getElementsByTagName("head")[0]; var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig; var srcRe = /\ssrc=([\'\"])(.*?)\1/i; var typeRe = /\stype=([\'\"])(.*?)\1/i; var match; while(match = re.exec(html)){ var attrs = match[1]; var srcMatch = attrs ? attrs.match(srcRe) : false; if(srcMatch && srcMatch[2]){ var s = document.createElement("script"); s.src = srcMatch[2]; var typeMatch = attrs.match(typeRe); if(typeMatch && typeMatch[2]){ s.type = typeMatch[2]; } hd.appendChild(s); }else if(match[2] && match[2].length > 0){ if(window.execScript) { window.execScript(match[2]); } else { window.eval(match[2]); } } } var el = document.getElementById(id); if(el){Ext.removeNode(el);} if(typeof callback == "function"){ callback(); } }); dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, ""); return this; }, load : function(){ var um = this.getUpdater(); um.update.apply(um, arguments); return this; }, getUpdater : function(){ if(!this.updateManager){ this.updateManager = new Ext.Updater(this); } return this.updateManager; }, unselectable : function(){ this.dom.unselectable = "on"; this.swallowEvent("selectstart", true); this.applyStyles("-moz-user-select:none;-khtml-user-select:none;"); this.addClass("x-unselectable"); return this; }, getCenterXY : function(){ return this.getAlignToXY(document, 'c-c'); }, center : function(centerIn){ this.alignTo(centerIn || document, 'c-c'); return this; }, isBorderBox : function(){ return noBoxAdjust[this.dom.tagName.toLowerCase()] || Ext.isBorderBox; }, getBox : function(contentBox, local){ var xy; if(!local){ xy = this.getXY(); }else{ var left = parseInt(this.getStyle("left"), 10) || 0; var top = parseInt(this.getStyle("top"), 10) || 0; xy = [left, top]; } var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx; if(!contentBox){ bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h}; }else{ var l = this.getBorderWidth("l")+this.getPadding("l"); var r = this.getBorderWidth("r")+this.getPadding("r"); var t = this.getBorderWidth("t")+this.getPadding("t"); var b = this.getBorderWidth("b")+this.getPadding("b"); bx = {x: xy[0]+l, y: xy[1]+t, 0: xy[0]+l, 1: xy[1]+t, width: w-(l+r), height: h-(t+b)}; } bx.right = bx.x + bx.width; bx.bottom = bx.y + bx.height; return bx; }, getFrameWidth : function(sides, onlyContentBox){ return onlyContentBox && Ext.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides)); }, setBox : function(box, adjust, animate){ var w = box.width, h = box.height; if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){ w -= (this.getBorderWidth("lr") + this.getPadding("lr")); h -= (this.getBorderWidth("tb") + this.getPadding("tb")); } this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2)); return this; }, repaint : function(){ var dom = this.dom; this.addClass("x-repaint"); setTimeout(function(){ Ext.get(dom).removeClass("x-repaint"); }, 1); return this; }, getMargins : function(side){ if(!side){ return { top: parseInt(this.getStyle("margin-top"), 10) || 0, left: parseInt(this.getStyle("margin-left"), 10) || 0, bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0, right: parseInt(this.getStyle("margin-right"), 10) || 0 }; }else{ return this.addStyles(side, El.margins); } }, addStyles : function(sides, styles){ var val = 0, v, w; for(var i = 0, len = sides.length; i < len; i++){ v = this.getStyle(styles[sides.charAt(i)]); if(v){ w = parseInt(v, 10); if(w){ val += (w >= 0 ? w : -1 * w); } } } return val; }, createProxy : function(config, renderTo, matchBox){ config = typeof config == "object" ? config : {tag : "div", cls: config}; var proxy; if(renderTo){ proxy = Ext.DomHelper.append(renderTo, config, true); }else { proxy = Ext.DomHelper.insertBefore(this.dom, config, true); } if(matchBox){ proxy.setBox(this.getBox()); } return proxy; }, mask : function(msg, msgCls){ if(this.getStyle("position") == "static"){ this.setStyle("position", "relative"); } if(this._maskMsg){ this._maskMsg.remove(); } if(this._mask){ this._mask.remove(); } this._mask = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask"}, true); this.addClass("x-masked"); this._mask.setDisplayed(true); if(typeof msg == 'string'){ this._maskMsg = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask-msg", cn:{tag:'div'}}, true); var mm = this._maskMsg; mm.dom.className = msgCls ? "ext-el-mask-msg " + msgCls : "ext-el-mask-msg"; mm.dom.firstChild.innerHTML = msg; mm.setDisplayed(true); mm.center(this); } if(Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && this.getStyle('height') == 'auto'){ this._mask.setSize(this.dom.clientWidth, this.getHeight()); } return this._mask; }, unmask : function(){ if(this._mask){ if(this._maskMsg){ this._maskMsg.remove(); delete this._maskMsg; } this._mask.remove(); delete this._mask; } this.removeClass("x-masked"); }, isMasked : function(){ return this._mask && this._mask.isVisible(); }, createShim : function(){ var el = document.createElement('iframe'); el.frameBorder = 'no'; el.className = 'ext-shim'; if(Ext.isIE && Ext.isSecure){ el.src = Ext.SSL_SECURE_URL; } var shim = Ext.get(this.dom.parentNode.insertBefore(el, this.dom)); shim.autoBoxAdjust = false; return shim; }, remove : function(){ Ext.removeNode(this.dom); delete El.cache[this.dom.id]; }, hover : function(overFn, outFn, scope){ var preOverFn = function(e){ if(!e.within(this, true)){ overFn.apply(scope || this, arguments); } }; var preOutFn = function(e){ if(!e.within(this, true)){ outFn.apply(scope || this, arguments); } }; this.on("mouseover", preOverFn, this.dom); this.on("mouseout", preOutFn, this.dom); return this; }, addClassOnOver : function(className, preventFlicker){ this.hover( function(){ Ext.fly(this, '_internal').addClass(className); }, function(){ Ext.fly(this, '_internal').removeClass(className); } ); return this; }, addClassOnFocus : function(className){ this.on("focus", function(){ Ext.fly(this, '_internal').addClass(className); }, this.dom); this.on("blur", function(){ Ext.fly(this, '_internal').removeClass(className); }, this.dom); return this; }, addClassOnClick : function(className){ var dom = this.dom; this.on("mousedown", function(){ Ext.fly(dom, '_internal').addClass(className); var d = Ext.getDoc(); var fn = function(){ Ext.fly(dom, '_internal').removeClass(className); d.removeListener("mouseup", fn); }; d.on("mouseup", fn); }); return this; }, swallowEvent : function(eventName, preventDefault){ var fn = function(e){ e.stopPropagation(); if(preventDefault){ e.preventDefault(); } }; if(Ext.isArray(eventName)){ for(var i = 0, len = eventName.length; i < len; i++){ this.on(eventName[i], fn); } return this; } this.on(eventName, fn); return this; }, parent : function(selector, returnDom){ return this.matchNode('parentNode', 'parentNode', selector, returnDom); }, next : function(selector, returnDom){ return this.matchNode('nextSibling', 'nextSibling', selector, returnDom); }, prev : function(selector, returnDom){ return this.matchNode('previousSibling', 'previousSibling', selector, returnDom); }, first : function(selector, returnDom){ return this.matchNode('nextSibling', 'firstChild', selector, returnDom); }, last : function(selector, returnDom){ return this.matchNode('previousSibling', 'lastChild', selector, returnDom); }, matchNode : function(dir, start, selector, returnDom){ var n = this.dom[start]; while(n){ if(n.nodeType == 1 && (!selector || Ext.DomQuery.is(n, selector))){ return !returnDom ? Ext.get(n) : n; } n = n[dir]; } return null; }, appendChild: function(el){ el = Ext.get(el); el.appendTo(this); return this; }, createChild: function(config, insertBefore, returnDom){ config = config || {tag:'div'}; if(insertBefore){ return Ext.DomHelper.insertBefore(insertBefore, config, returnDom !== true); } return Ext.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true); }, appendTo: function(el){ el = Ext.getDom(el); el.appendChild(this.dom); return this; }, insertBefore: function(el){ el = Ext.getDom(el); el.parentNode.insertBefore(this.dom, el); return this; }, insertAfter: function(el){ el = Ext.getDom(el); el.parentNode.insertBefore(this.dom, el.nextSibling); return this; }, insertFirst: function(el, returnDom){ el = el || {}; if(typeof el == 'object' && !el.nodeType && !el.dom){ return this.createChild(el, this.dom.firstChild, returnDom); }else{ el = Ext.getDom(el); this.dom.insertBefore(el, this.dom.firstChild); return !returnDom ? Ext.get(el) : el; } }, insertSibling: function(el, where, returnDom){ var rt; if(Ext.isArray(el)){ for(var i = 0, len = el.length; i < len; i++){ rt = this.insertSibling(el[i], where, returnDom); } return rt; } where = where ? where.toLowerCase() : 'before'; el = el || {}; var refNode = where == 'before' ? this.dom : this.dom.nextSibling; if(typeof el == 'object' && !el.nodeType && !el.dom){ if(where == 'after' && !this.dom.nextSibling){ rt = Ext.DomHelper.append(this.dom.parentNode, el, !returnDom); }else{ rt = Ext.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom); } }else{ rt = this.dom.parentNode.insertBefore(Ext.getDom(el), refNode); if(!returnDom){ rt = Ext.get(rt); } } return rt; }, wrap: function(config, returnDom){ if(!config){ config = {tag: "div"}; } var newEl = Ext.DomHelper.insertBefore(this.dom, config, !returnDom); newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom); return newEl; }, replace: function(el){ el = Ext.get(el); this.insertBefore(el); el.remove(); return this; }, replaceWith: function(el){ if(typeof el == 'object' && !el.nodeType && !el.dom){ el = this.insertSibling(el, 'before'); }else{ el = Ext.getDom(el); this.dom.parentNode.insertBefore(el, this.dom); } El.uncache(this.id); this.dom.parentNode.removeChild(this.dom); this.dom = el; this.id = Ext.id(el); El.cache[this.id] = this; return this; }, insertHtml : function(where, html, returnEl){ var el = Ext.DomHelper.insertHtml(where, this.dom, html); return returnEl ? Ext.get(el) : el; }, set : function(o, useSet){ var el = this.dom; useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet; for(var attr in o){ if(attr == "style" || typeof o[attr] == "function") continue; if(attr=="cls"){ el.className = o["cls"]; }else if(o.hasOwnProperty(attr)){ if(useSet) el.setAttribute(attr, o[attr]); else el[attr] = o[attr]; } } if(o.style){ Ext.DomHelper.applyStyles(el, o.style); } return this; }, addKeyListener : function(key, fn, scope){ var config; if(typeof key != "object" || Ext.isArray(key)){ config = { key: key, fn: fn, scope: scope }; }else{ config = { key : key.key, shift : key.shift, ctrl : key.ctrl, alt : key.alt, fn: fn, scope: scope }; } return new Ext.KeyMap(this, config); }, addKeyMap : function(config){ return new Ext.KeyMap(this, config); }, isScrollable : function(){ var dom = this.dom; return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth; }, scrollTo : function(side, value, animate){ var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop"; if(!animate || !A){ this.dom[prop] = value; }else{ var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value]; this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll'); } return this; }, scroll : function(direction, distance, animate){ if(!this.isScrollable()){ return; } var el = this.dom; var l = el.scrollLeft, t = el.scrollTop; var w = el.scrollWidth, h = el.scrollHeight; var cw = el.clientWidth, ch = el.clientHeight; direction = direction.toLowerCase(); var scrolled = false; var a = this.preanim(arguments, 2); switch(direction){ case "l": case "left": if(w - l > cw){ var v = Math.min(l + distance, w-cw); this.scrollTo("left", v, a); scrolled = true; } break; case "r": case "right": if(l > 0){ var v = Math.max(l - distance, 0); this.scrollTo("left", v, a); scrolled = true; } break; case "t": case "top": case "up": if(t > 0){ var v = Math.max(t - distance, 0); this.scrollTo("top", v, a); scrolled = true; } break; case "b": case "bottom": case "down": if(h - t > ch){ var v = Math.min(t + distance, h-ch); this.scrollTo("top", v, a); scrolled = true; } break; } return scrolled; }, translatePoints : function(x, y){ if(typeof x == 'object' || Ext.isArray(x)){ y = x[1]; x = x[0]; } var p = this.getStyle('position'); var o = this.getXY(); var l = parseInt(this.getStyle('left'), 10); var t = parseInt(this.getStyle('top'), 10); if(isNaN(l)){ l = (p == "relative") ? 0 : this.dom.offsetLeft; } if(isNaN(t)){ t = (p == "relative") ? 0 : this.dom.offsetTop; } return {left: (x - o[0] + l), top: (y - o[1] + t)}; }, getScroll : function(){ var d = this.dom, doc = document; if(d == doc || d == doc.body){ var l, t; if(Ext.isIE && Ext.isStrict){ l = doc.documentElement.scrollLeft || (doc.body.scrollLeft || 0); t = doc.documentElement.scrollTop || (doc.body.scrollTop || 0); }else{ l = window.pageXOffset || (doc.body.scrollLeft || 0); t = window.pageYOffset || (doc.body.scrollTop || 0); } return {left: l, top: t}; }else{ return {left: d.scrollLeft, top: d.scrollTop}; } }, getColor : function(attr, defaultValue, prefix){ var v = this.getStyle(attr); if(!v || v == "transparent" || v == "inherit") { return defaultValue; } var color = typeof prefix == "undefined" ? "#" : prefix; if(v.substr(0, 4) == "rgb("){ var rvs = v.slice(4, v.length -1).split(","); for(var i = 0; i < 3; i++){ var h = parseInt(rvs[i]); var s = h.toString(16); if(h < 16){ s = "0" + s; } color += s; } } else { if(v.substr(0, 1) == "#"){ if(v.length == 4) { for(var i = 1; i < 4; i++){ var c = v.charAt(i); color += c + c; } }else if(v.length == 7){ color += v.substr(1); } } } return(color.length > 5 ? color.toLowerCase() : defaultValue); }, boxWrap : function(cls){ cls = cls || 'x-box'; var el = Ext.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls))); el.child('.'+cls+'-mc').dom.appendChild(this.dom); return el; }, getAttributeNS : Ext.isIE ? function(ns, name){ var d = this.dom; var type = typeof d[ns+":"+name]; if(type != 'undefined' && type != 'unknown'){ return d[ns+":"+name]; } return d[name]; } : function(ns, name){ var d = this.dom; return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name]; }, getTextWidth : function(text, min, max){ return (Ext.util.TextMetrics.measure(this.dom, Ext.value(text, this.dom.innerHTML, true)).width).constrain(min || 0, max || 1000000); } }; var ep = El.prototype; ep.on = ep.addListener; ep.mon = ep.addListener; ep.getUpdateManager = ep.getUpdater; ep.un = ep.removeListener; ep.autoBoxAdjust = true; El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i; El.addUnits = function(v, defaultUnit){ if(v === "" || v == "auto"){ return v; } if(v === undefined){ return ''; } if(typeof v == "number" || !El.unitPattern.test(v)){ return v + (defaultUnit || 'px'); } return v; }; El.boxMarkup = '<div class="{0}-tl"><div class="{0}-tr"><div class="{0}-tc"></div></div></div><div class="{0}-ml"><div class="{0}-mr"><div class="{0}-mc"></div></div></div><div class="{0}-bl"><div class="{0}-br"><div class="{0}-bc"></div></div></div>'; El.VISIBILITY = 1; El.DISPLAY = 2; El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"}; El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"}; El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"}; El.cache = {}; var docEl; El.get = function(el){ var ex, elm, id; if(!el){ return null; } if(typeof el == "string"){ if(!(elm = document.getElementById(el))){ return null; } if(ex = El.cache[el]){ ex.dom = elm; }else{ ex = El.cache[el] = new El(elm); } return ex; }else if(el.tagName){ if(!(id = el.id)){ id = Ext.id(el); } if(ex = El.cache[id]){ ex.dom = el; }else{ ex = El.cache[id] = new El(el); } return ex; }else if(el instanceof El){ if(el != docEl){ el.dom = document.getElementById(el.id) || el.dom; El.cache[el.id] = el; } return el; }else if(el.isComposite){ return el; }else if(Ext.isArray(el)){ return El.select(el); }else if(el == document){ if(!docEl){ var f = function(){}; f.prototype = El.prototype; docEl = new f(); docEl.dom = document; } return docEl; } return null; }; El.uncache = function(el){ for(var i = 0, a = arguments, len = a.length; i < len; i++) { if(a[i]){ delete El.cache[a[i].id || a[i]]; } } }; El.garbageCollect = function(){ if(!Ext.enableGarbageCollector){ clearInterval(El.collectorThread); return; } for(var eid in El.cache){ var el = El.cache[eid], d = el.dom; if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){ delete El.cache[eid]; if(d && Ext.enableListenerCollection){ E.purgeElement(d); } } } } El.collectorThreadId = setInterval(El.garbageCollect, 30000); var flyFn = function(){}; flyFn.prototype = El.prototype; var _cls = new flyFn(); El.Flyweight = function(dom){ this.dom = dom; }; El.Flyweight.prototype = _cls; El.Flyweight.prototype.isFlyweight = true; El._flyweights = {}; El.fly = function(el, named){ named = named || '_global'; el = Ext.getDom(el); if(!el){ return null; } if(!El._flyweights[named]){ El._flyweights[named] = new El.Flyweight(); } El._flyweights[named].dom = el; return El._flyweights[named]; }; Ext.get = El.get; Ext.fly = El.fly; var noBoxAdjust = Ext.isStrict ? { select:1 } : { input:1, select:1, textarea:1 }; if(Ext.isIE || Ext.isGecko){ noBoxAdjust['button'] = 1; } Ext.EventManager.on(window, 'unload', function(){ delete El.cache; delete El._flyweights; }); })(); Ext.enableFx = true; Ext.Fx = { slideIn : function(anchor, o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ anchor = anchor || "t"; this.fixDisplay(); var r = this.getFxRestore(); var b = this.getBox(); this.setSize(b); var wrap = this.fxWrap(r.pos, o, "hidden"); var st = this.dom.style; st.visibility = "visible"; st.position = "absolute"; var after = function(){ el.fxUnwrap(wrap, r.pos, o); st.width = r.width; st.height = r.height; el.afterFx(o); }; var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height}; switch(anchor.toLowerCase()){ case "t": wrap.setSize(b.width, 0); st.left = st.bottom = "0"; a = {height: bh}; break; case "l": wrap.setSize(0, b.height); st.right = st.top = "0"; a = {width: bw}; break; case "r": wrap.setSize(0, b.height); wrap.setX(b.right); st.left = st.top = "0"; a = {width: bw, points: pt}; break; case "b": wrap.setSize(b.width, 0); wrap.setY(b.bottom); st.left = st.top = "0"; a = {height: bh, points: pt}; break; case "tl": wrap.setSize(0, 0); st.right = st.bottom = "0"; a = {width: bw, height: bh}; break; case "bl": wrap.setSize(0, 0); wrap.setY(b.y+b.height); st.right = st.top = "0"; a = {width: bw, height: bh, points: pt}; break; case "br": wrap.setSize(0, 0); wrap.setXY([b.right, b.bottom]); st.left = st.top = "0"; a = {width: bw, height: bh, points: pt}; break; case "tr": wrap.setSize(0, 0); wrap.setX(b.x+b.width); st.left = st.bottom = "0"; a = {width: bw, height: bh, points: pt}; break; } this.dom.style.visibility = "visible"; wrap.show(); arguments.callee.anim = wrap.fxanim(a, o, 'motion', .5, 'easeOut', after); }); return this; }, slideOut : function(anchor, o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ anchor = anchor || "t"; var r = this.getFxRestore(); var b = this.getBox(); this.setSize(b); var wrap = this.fxWrap(r.pos, o, "visible"); var st = this.dom.style; st.visibility = "visible"; st.position = "absolute"; wrap.setSize(b); var after = function(){ if(o.useDisplay){ el.setDisplayed(false); }else{ el.hide(); } el.fxUnwrap(wrap, r.pos, o); st.width = r.width; st.height = r.height; el.afterFx(o); }; var a, zero = {to: 0}; switch(anchor.toLowerCase()){ case "t": st.left = st.bottom = "0"; a = {height: zero}; break; case "l": st.right = st.top = "0"; a = {width: zero}; break; case "r": st.left = st.top = "0"; a = {width: zero, points: {to:[b.right, b.y]}}; break; case "b": st.left = st.top = "0"; a = {height: zero, points: {to:[b.x, b.bottom]}}; break; case "tl": st.right = st.bottom = "0"; a = {width: zero, height: zero}; break; case "bl": st.right = st.top = "0"; a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}}; break; case "br": st.left = st.top = "0"; a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}}; break; case "tr": st.left = st.bottom = "0"; a = {width: zero, height: zero, points: {to:[b.right, b.y]}}; break; } arguments.callee.anim = wrap.fxanim(a, o, 'motion', .5, "easeOut", after); }); return this; }, puff : function(o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ this.clearOpacity(); this.show(); var r = this.getFxRestore(); var st = this.dom.style; var after = function(){ if(o.useDisplay){ el.setDisplayed(false); }else{ el.hide(); } el.clearOpacity(); el.setPositioning(r.pos); st.width = r.width; st.height = r.height; st.fontSize = ''; el.afterFx(o); }; var width = this.getWidth(); var height = this.getHeight(); arguments.callee.anim = this.fxanim({ width : {to: this.adjustWidth(width * 2)}, height : {to: this.adjustHeight(height * 2)}, points : {by: [-(width * .5), -(height * .5)]}, opacity : {to: 0}, fontSize: {to:200, unit: "%"} }, o, 'motion', .5, "easeOut", after); }); return this; }, switchOff : function(o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ this.clearOpacity(); this.clip(); var r = this.getFxRestore(); var st = this.dom.style; var after = function(){ if(o.useDisplay){ el.setDisplayed(false); }else{ el.hide(); } el.clearOpacity(); el.setPositioning(r.pos); st.width = r.width; st.height = r.height; el.afterFx(o); }; this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){ this.clearOpacity(); (function(){ this.fxanim({ height:{to:1}, points:{by:[0, this.getHeight() * .5]} }, o, 'motion', 0.3, 'easeIn', after); }).defer(100, this); }); }); return this; }, highlight : function(color, o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ color = color || "ffff9c"; var attr = o.attr || "backgroundColor"; this.clearOpacity(); this.show(); var origColor = this.getColor(attr); var restoreColor = this.dom.style[attr]; var endColor = (o.endColor || origColor) || "ffffff"; var after = function(){ el.dom.style[attr] = restoreColor; el.afterFx(o); }; var a = {}; a[attr] = {from: color, to: endColor}; arguments.callee.anim = this.fxanim(a, o, 'color', 1, 'easeIn', after); }); return this; }, frame : function(color, count, o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ color = color || "#C3DAF9"; if(color.length == 6){ color = "#" + color; } count = count || 1; var duration = o.duration || 1; this.show(); var b = this.getBox(); var animFn = function(){ var proxy = Ext.getBody().createChild({ style:{ visbility:"hidden", position:"absolute", "z-index":"35000", border:"0px solid " + color } }); var scale = Ext.isBorderBox ? 2 : 1; proxy.animate({ top:{from:b.y, to:b.y - 20}, left:{from:b.x, to:b.x - 20}, borderWidth:{from:0, to:10}, opacity:{from:1, to:0}, height:{from:b.height, to:(b.height + (20*scale))}, width:{from:b.width, to:(b.width + (20*scale))} }, duration, function(){ proxy.remove(); if(--count > 0){ animFn(); }else{ el.afterFx(o); } }); }; animFn.call(this); }); return this; }, pause : function(seconds){ var el = this.getFxEl(); var o = {}; el.queueFx(o, function(){ setTimeout(function(){ el.afterFx(o); }, seconds * 1000); }); return this; }, fadeIn : function(o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ this.setOpacity(0); this.fixDisplay(); this.dom.style.visibility = 'visible'; var to = o.endOpacity || 1; arguments.callee.anim = this.fxanim({opacity:{to:to}}, o, null, .5, "easeOut", function(){ if(to == 1){ this.clearOpacity(); } el.afterFx(o); }); }); return this; }, fadeOut : function(o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}}, o, null, .5, "easeOut", function(){ if(this.visibilityMode == Ext.Element.DISPLAY || o.useDisplay){ this.dom.style.display = "none"; }else{ this.dom.style.visibility = "hidden"; } this.clearOpacity(); el.afterFx(o); }); }); return this; }, scale : function(w, h, o){ this.shift(Ext.apply({}, o, { width: w, height: h })); return this; }, shift : function(o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity; if(w !== undefined){ a.width = {to: this.adjustWidth(w)}; } if(h !== undefined){ a.height = {to: this.adjustHeight(h)}; } if(x !== undefined || y !== undefined){ a.points = {to: [ x !== undefined ? x : this.getX(), y !== undefined ? y : this.getY() ]}; } if(op !== undefined){ a.opacity = {to: op}; } if(o.xy !== undefined){ a.points = {to: o.xy}; } arguments.callee.anim = this.fxanim(a, o, 'motion', .35, "easeOut", function(){ el.afterFx(o); }); }); return this; }, ghost : function(anchor, o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ anchor = anchor || "b"; var r = this.getFxRestore(); var w = this.getWidth(), h = this.getHeight(); var st = this.dom.style; var after = function(){ if(o.useDisplay){ el.setDisplayed(false); }else{ el.hide(); } el.clearOpacity(); el.setPositioning(r.pos); st.width = r.width; st.height = r.height; el.afterFx(o); }; var a = {opacity: {to: 0}, points: {}}, pt = a.points; switch(anchor.toLowerCase()){ case "t": pt.by = [0, -h]; break; case "l": pt.by = [-w, 0]; break; case "r": pt.by = [w, 0]; break; case "b": pt.by = [0, h]; break; case "tl": pt.by = [-w, -h]; break; case "bl": pt.by = [-w, h]; break; case "br": pt.by = [w, h]; break; case "tr": pt.by = [w, -h]; break; } arguments.callee.anim = this.fxanim(a, o, 'motion', .5, "easeOut", after); }); return this; }, syncFx : function(){ this.fxDefaults = Ext.apply(this.fxDefaults || {}, { block : false, concurrent : true, stopFx : false }); return this; }, sequenceFx : function(){ this.fxDefaults = Ext.apply(this.fxDefaults || {}, { block : false, concurrent : false, stopFx : false }); return this; }, nextFx : function(){ var ef = this.fxQueue[0]; if(ef){ ef.call(this); } }, hasActiveFx : function(){ return this.fxQueue && this.fxQueue[0]; }, stopFx : function(){ if(this.hasActiveFx()){ var cur = this.fxQueue[0]; if(cur && cur.anim && cur.anim.isAnimated()){ this.fxQueue = [cur]; cur.anim.stop(true); } } return this; }, beforeFx : function(o){ if(this.hasActiveFx() && !o.concurrent){ if(o.stopFx){ this.stopFx(); return true; } return false; } return true; }, hasFxBlock : function(){ var q = this.fxQueue; return q && q[0] && q[0].block; }, queueFx : function(o, fn){ if(!this.fxQueue){ this.fxQueue = []; } if(!this.hasFxBlock()){ Ext.applyIf(o, this.fxDefaults); if(!o.concurrent){ var run = this.beforeFx(o); fn.block = o.block; this.fxQueue.push(fn); if(run){ this.nextFx(); } }else{ fn.call(this); } } return this; }, fxWrap : function(pos, o, vis){ var wrap; if(!o.wrap || !(wrap = Ext.get(o.wrap))){ var wrapXY; if(o.fixPosition){ wrapXY = this.getXY(); } var div = document.createElement("div"); div.style.visibility = vis; wrap = Ext.get(this.dom.parentNode.insertBefore(div, this.dom)); wrap.setPositioning(pos); if(wrap.getStyle("position") == "static"){ wrap.position("relative"); } this.clearPositioning('auto'); wrap.clip(); wrap.dom.appendChild(this.dom); if(wrapXY){ wrap.setXY(wrapXY); } } return wrap; }, fxUnwrap : function(wrap, pos, o){ this.clearPositioning(); this.setPositioning(pos); if(!o.wrap){ wrap.dom.parentNode.insertBefore(this.dom, wrap.dom); wrap.remove(); } }, getFxRestore : function(){ var st = this.dom.style; return {pos: this.getPositioning(), width: st.width, height : st.height}; }, afterFx : function(o){ if(o.afterStyle){ this.applyStyles(o.afterStyle); } if(o.afterCls){ this.addClass(o.afterCls); } if(o.remove === true){ this.remove(); } Ext.callback(o.callback, o.scope, [this]); if(!o.concurrent){ this.fxQueue.shift(); this.nextFx(); } }, getFxEl : function(){ return Ext.get(this.dom); }, fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){ animType = animType || 'run'; opt = opt || {}; var anim = Ext.lib.Anim[animType]( this.dom, args, (opt.duration || defaultDur) || .35, (opt.easing || defaultEase) || 'easeOut', function(){ Ext.callback(cb, this); }, this ); opt.anim = anim; return anim; } }; Ext.Fx.resize = Ext.Fx.scale; Ext.apply(Ext.Element.prototype, Ext.Fx); Ext.CompositeElement = function(els){ this.elements = []; this.addElements(els); }; Ext.CompositeElement.prototype = { isComposite: true, addElements : function(els){ if(!els) return this; if(typeof els == "string"){ els = Ext.Element.selectorFunction(els); } var yels = this.elements; var index = yels.length-1; for(var i = 0, len = els.length; i < len; i++) { yels[++index] = Ext.get(els[i]); } return this; }, fill : function(els){ this.elements = []; this.add(els); return this; }, filter : function(selector){ var els = []; this.each(function(el){ if(el.is(selector)){ els[els.length] = el.dom; } }); this.fill(els); return this; }, invoke : function(fn, args){ var els = this.elements; for(var i = 0, len = els.length; i < len; i++) { Ext.Element.prototype[fn].apply(els[i], args); } return this; }, add : function(els){ if(typeof els == "string"){ this.addElements(Ext.Element.selectorFunction(els)); }else if(els.length !== undefined){ this.addElements(els); }else{ this.addElements([els]); } return this; }, each : function(fn, scope){ var els = this.elements; for(var i = 0, len = els.length; i < len; i++){ if(fn.call(scope || els[i], els[i], this, i) === false) { break; } } return this; }, item : function(index){ return this.elements[index] || null; }, first : function(){ return this.item(0); }, last : function(){ return this.item(this.elements.length-1); }, getCount : function(){ return this.elements.length; }, contains : function(el){ return this.indexOf(el) !== -1; }, indexOf : function(el){ return this.elements.indexOf(Ext.get(el)); }, removeElement : function(el, removeDom){ if(Ext.isArray(el)){ for(var i = 0, len = el.length; i < len; i++){ this.removeElement(el[i]); } return this; } var index = typeof el == 'number' ? el : this.indexOf(el); if(index !== -1 && this.elements[index]){ if(removeDom){ var d = this.elements[index]; if(d.dom){ d.remove(); }else{ Ext.removeNode(d); } } this.elements.splice(index, 1); } return this; }, replaceElement : function(el, replacement, domReplace){ var index = typeof el == 'number' ? el : this.indexOf(el); if(index !== -1){ if(domReplace){ this.elements[index].replaceWith(replacement); }else{ this.elements.splice(index, 1, Ext.get(replacement)) } } return this; }, clear : function(){ this.elements = []; } }; (function(){ Ext.CompositeElement.createCall = function(proto, fnName){ if(!proto[fnName]){ proto[fnName] = function(){ return this.invoke(fnName, arguments); }; } }; for(var fnName in Ext.Element.prototype){ if(typeof Ext.Element.prototype[fnName] == "function"){ Ext.CompositeElement.createCall(Ext.CompositeElement.prototype, fnName); } }; })(); Ext.CompositeElementLite = function(els){ Ext.CompositeElementLite.superclass.constructor.call(this, els); this.el = new Ext.Element.Flyweight(); }; Ext.extend(Ext.CompositeElementLite, Ext.CompositeElement, { addElements : function(els){ if(els){ if(Ext.isArray(els)){ this.elements = this.elements.concat(els); }else{ var yels = this.elements; var index = yels.length-1; for(var i = 0, len = els.length; i < len; i++) { yels[++index] = els[i]; } } } return this; }, invoke : function(fn, args){ var els = this.elements; var el = this.el; for(var i = 0, len = els.length; i < len; i++) { el.dom = els[i]; Ext.Element.prototype[fn].apply(el, args); } return this; }, item : function(index){ if(!this.elements[index]){ return null; } this.el.dom = this.elements[index]; return this.el; }, addListener : function(eventName, handler, scope, opt){ var els = this.elements; for(var i = 0, len = els.length; i < len; i++) { Ext.EventManager.on(els[i], eventName, handler, scope || els[i], opt); } return this; }, each : function(fn, scope){ var els = this.elements; var el = this.el; for(var i = 0, len = els.length; i < len; i++){ el.dom = els[i]; if(fn.call(scope || el, el, this, i) === false){ break; } } return this; }, indexOf : function(el){ return this.elements.indexOf(Ext.getDom(el)); }, replaceElement : function(el, replacement, domReplace){ var index = typeof el == 'number' ? el : this.indexOf(el); if(index !== -1){ replacement = Ext.getDom(replacement); if(domReplace){ var d = this.elements[index]; d.parentNode.insertBefore(replacement, d); Ext.removeNode(d); } this.elements.splice(index, 1, replacement); } return this; } }); Ext.CompositeElementLite.prototype.on = Ext.CompositeElementLite.prototype.addListener; if(Ext.DomQuery){ Ext.Element.selectorFunction = Ext.DomQuery.select; } Ext.Element.select = function(selector, unique, root){ var els; if(typeof selector == "string"){ els = Ext.Element.selectorFunction(selector, root); }else if(selector.length !== undefined){ els = selector; }else{ throw "Invalid selector"; } if(unique === true){ return new Ext.CompositeElement(els); }else{ return new Ext.CompositeElementLite(els); } }; Ext.select = Ext.Element.select; Ext.data.Connection = function(config){ Ext.apply(this, config); this.addEvents( "beforerequest", "requestcomplete", "requestexception" ); Ext.data.Connection.superclass.constructor.call(this); }; Ext.extend(Ext.data.Connection, Ext.util.Observable, { timeout : 30000, autoAbort:false, disableCaching: true, request : function(o){ if(this.fireEvent("beforerequest", this, o) !== false){ var p = o.params; if(typeof p == "function"){ p = p.call(o.scope||window, o); } if(typeof p == "object"){ p = Ext.urlEncode(p); } if(this.extraParams){ var extras = Ext.urlEncode(this.extraParams); p = p ? (p + '&' + extras) : extras; } var url = o.url || this.url; if(typeof url == 'function'){ url = url.call(o.scope||window, o); } if(o.form){ var form = Ext.getDom(o.form); url = url || form.action; var enctype = form.getAttribute("enctype"); if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){ return this.doFormUpload(o, p, url); } var f = Ext.lib.Ajax.serializeForm(form); p = p ? (p + '&' + f) : f; } var hs = o.headers; if(this.defaultHeaders){ hs = Ext.apply(hs || {}, this.defaultHeaders); if(!o.headers){ o.headers = hs; } } var cb = { success: this.handleResponse, failure: this.handleFailure, scope: this, argument: {options: o}, timeout : o.timeout || this.timeout }; var method = o.method||this.method||(p ? "POST" : "GET"); if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){ url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime()); } if(typeof o.autoAbort == 'boolean'){ if(o.autoAbort){ this.abort(); } }else if(this.autoAbort !== false){ this.abort(); } if((method == 'GET' && p) || o.xmlData || o.jsonData){ url += (url.indexOf('?') != -1 ? '&' : '?') + p; p = ''; } this.transId = Ext.lib.Ajax.request(method, url, cb, p, o); return this.transId; }else{ Ext.callback(o.callback, o.scope, [o, null, null]); return null; } }, isLoading : function(transId){ if(transId){ return Ext.lib.Ajax.isCallInProgress(transId); }else{ return this.transId ? true : false; } }, abort : function(transId){ if(transId || this.isLoading()){ Ext.lib.Ajax.abort(transId || this.transId); } }, handleResponse : function(response){ this.transId = false; var options = response.argument.options; response.argument = options ? options.argument : null; this.fireEvent("requestcomplete", this, response, options); Ext.callback(options.success, options.scope, [response, options]); Ext.callback(options.callback, options.scope, [options, true, response]); }, handleFailure : function(response, e){ this.transId = false; var options = response.argument.options; response.argument = options ? options.argument : null; this.fireEvent("requestexception", this, response, options, e); Ext.callback(options.failure, options.scope, [response, options]); Ext.callback(options.callback, options.scope, [options, false, response]); }, doFormUpload : function(o, ps, url){ var id = Ext.id(); var frame = document.createElement('iframe'); frame.id = id; frame.name = id; frame.className = 'x-hidden'; if(Ext.isIE){ frame.src = Ext.SSL_SECURE_URL; } document.body.appendChild(frame); if(Ext.isIE){ document.frames[id].name = id; } var form = Ext.getDom(o.form); form.target = id; form.method = 'POST'; form.enctype = form.encoding = 'multipart/form-data'; if(url){ form.action = url; } var hiddens, hd; if(ps){ hiddens = []; ps = Ext.urlDecode(ps, false); for(var k in ps){ if(ps.hasOwnProperty(k)){ hd = document.createElement('input'); hd.type = 'hidden'; hd.name = k; hd.value = ps[k]; form.appendChild(hd); hiddens.push(hd); } } } function cb(){ var r = { responseText : '', responseXML : null }; r.argument = o ? o.argument : null; try { var doc; if(Ext.isIE){ doc = frame.contentWindow.document; }else { doc = (frame.contentDocument || window.frames[id].document); } if(doc && doc.body){ r.responseText = doc.body.innerHTML; } if(doc && doc.XMLDocument){ r.responseXML = doc.XMLDocument; }else { r.responseXML = doc; } } catch(e) { } Ext.EventManager.removeListener(frame, 'load', cb, this); this.fireEvent("requestcomplete", this, r, o); Ext.callback(o.success, o.scope, [r, o]); Ext.callback(o.callback, o.scope, [o, true, r]); setTimeout(function(){Ext.removeNode(frame);}, 100); } Ext.EventManager.on(frame, 'load', cb, this); form.submit(); if(hiddens){ for(var i = 0, len = hiddens.length; i < len; i++){ Ext.removeNode(hiddens[i]); } } } }); Ext.Ajax = new Ext.data.Connection({ autoAbort : false, serializeForm : function(form){ return Ext.lib.Ajax.serializeForm(form); } }); Ext.Updater = function(el, forceNew){ el = Ext.get(el); if(!forceNew && el.updateManager){ return el.updateManager; } this.el = el; this.defaultUrl = null; this.addEvents( "beforeupdate", "update", "failure" ); var d = Ext.Updater.defaults; this.sslBlankUrl = d.sslBlankUrl; this.disableCaching = d.disableCaching; this.indicatorText = d.indicatorText; this.showLoadIndicator = d.showLoadIndicator; this.timeout = d.timeout; this.loadScripts = d.loadScripts; this.transaction = null; this.autoRefreshProcId = null; this.refreshDelegate = this.refresh.createDelegate(this); this.updateDelegate = this.update.createDelegate(this); this.formUpdateDelegate = this.formUpdate.createDelegate(this); if(!this.renderer){ this.renderer = new Ext.Updater.BasicRenderer(); } Ext.Updater.superclass.constructor.call(this); }; Ext.extend(Ext.Updater, Ext.util.Observable, { getEl : function(){ return this.el; }, update : function(url, params, callback, discardUrl){ if(this.fireEvent("beforeupdate", this.el, url, params) !== false){ var method = this.method, cfg, callerScope; if(typeof url == "object"){ cfg = url; url = cfg.url; params = params || cfg.params; callback = callback || cfg.callback; discardUrl = discardUrl || cfg.discardUrl; callerScope = cfg.scope; if(typeof cfg.method != "undefined"){method = cfg.method;}; if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;}; if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";}; if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;}; if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;}; } this.showLoading(); if(!discardUrl){ this.defaultUrl = url; } if(typeof url == "function"){ url = url.call(this); } method = method || (params ? "POST" : "GET"); if(method == "GET"){ url = this.prepareUrl(url); } var o = Ext.apply(cfg ||{}, { url : url, params: (typeof params == "function" && callerScope) ? params.createDelegate(callerScope) : params, success: this.processSuccess, failure: this.processFailure, scope: this, callback: undefined, timeout: (this.timeout*1000), argument: { "options": cfg, "url": url, "form": null, "callback": callback, "scope": callerScope || window, "params": params } }); this.transaction = Ext.Ajax.request(o); } }, formUpdate : function(form, url, reset, callback){ if(this.fireEvent("beforeupdate", this.el, form, url) !== false){ if(typeof url == "function"){ url = url.call(this); } form = Ext.getDom(form) this.transaction = Ext.Ajax.request({ form: form, url:url, success: this.processSuccess, failure: this.processFailure, scope: this, timeout: (this.timeout*1000), argument: { "url": url, "form": form, "callback": callback, "reset": reset } }); this.showLoading.defer(1, this); } }, refresh : function(callback){ if(this.defaultUrl == null){ return; } this.update(this.defaultUrl, null, callback, true); }, startAutoRefresh : function(interval, url, params, callback, refreshNow){ if(refreshNow){ this.update(url || this.defaultUrl, params, callback, true); } if(this.autoRefreshProcId){ clearInterval(this.autoRefreshProcId); } this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000); }, stopAutoRefresh : function(){ if(this.autoRefreshProcId){ clearInterval(this.autoRefreshProcId); delete this.autoRefreshProcId; } }, isAutoRefreshing : function(){ return this.autoRefreshProcId ? true : false; }, showLoading : function(){ if(this.showLoadIndicator){ this.el.update(this.indicatorText); } }, prepareUrl : function(url){ if(this.disableCaching){ var append = "_dc=" + (new Date().getTime()); if(url.indexOf("?") !== -1){ url += "&" + append; }else{ url += "?" + append; } } return url; }, processSuccess : function(response){ this.transaction = null; if(response.argument.form && response.argument.reset){ try{ response.argument.form.reset(); }catch(e){} } if(this.loadScripts){ this.renderer.render(this.el, response, this, this.updateComplete.createDelegate(this, [response])); }else{ this.renderer.render(this.el, response, this); this.updateComplete(response); } }, updateComplete : function(response){ this.fireEvent("update", this.el, response); if(typeof response.argument.callback == "function"){ response.argument.callback.call(response.argument.scope, this.el, true, response, response.argument.options); } }, processFailure : function(response){ this.transaction = null; this.fireEvent("failure", this.el, response); if(typeof response.argument.callback == "function"){ response.argument.callback.call(response.argument.scope, this.el, false, response, response.argument.options); } }, setRenderer : function(renderer){ this.renderer = renderer; }, getRenderer : function(){ return this.renderer; }, setDefaultUrl : function(defaultUrl){ this.defaultUrl = defaultUrl; }, abort : function(){ if(this.transaction){ Ext.Ajax.abort(this.transaction); } }, isUpdating : function(){ if(this.transaction){ return Ext.Ajax.isLoading(this.transaction); } return false; } }); Ext.Updater.defaults = { timeout : 30, loadScripts : false, sslBlankUrl : (Ext.SSL_SECURE_URL || "javascript:false"), disableCaching : false, showLoadIndicator : true, indicatorText : '<div class="loading-indicator">Loading...</div>' }; Ext.Updater.updateElement = function(el, url, params, options){ var um = Ext.get(el).getUpdater(); Ext.apply(um, options); um.update(url, params, options ? options.callback : null); }; Ext.Updater.update = Ext.Updater.updateElement; Ext.Updater.BasicRenderer = function(){}; Ext.Updater.BasicRenderer.prototype = { render : function(el, response, updateManager, callback){ el.update(response.responseText, updateManager.loadScripts, callback); } }; Ext.UpdateManager = Ext.Updater; Date.parseFunctions = {count:0}; Date.parseRegexes = []; Date.formatFunctions = {count:0}; Date.prototype.dateFormat = function(format) { if (Date.formatFunctions[format] == null) { Date.createNewFormat(format); } var func = Date.formatFunctions[format]; return this[func](); }; Date.prototype.format = Date.prototype.dateFormat; Date.createNewFormat = function(format) { var funcName = "format" + Date.formatFunctions.count++; Date.formatFunctions[format] = funcName; var code = "Date.prototype." + funcName + " = function(){return "; var special = false; var ch = ''; for (var i = 0; i < format.length; ++i) { ch = format.charAt(i); if (!special && ch == "\\") { special = true; } else if (special) { special = false; code += "'" + String.escape(ch) + "' + "; } else { code += Date.getFormatCode(ch); } } eval(code.substring(0, code.length - 3) + ";}"); }; Date.getFormatCode = function(character) { switch (character) { case "d": return "String.leftPad(this.getDate(), 2, '0') + "; case "D": return "Date.getShortDayName(this.getDay()) + "; case "j": return "this.getDate() + "; case "l": return "Date.dayNames[this.getDay()] + "; case "N": return "(this.getDay() ? this.getDay() : 7) + "; case "S": return "this.getSuffix() + "; case "w": return "this.getDay() + "; case "z": return "this.getDayOfYear() + "; case "W": return "String.leftPad(this.getWeekOfYear(), 2, '0') + "; case "F": return "Date.monthNames[this.getMonth()] + "; case "m": return "String.leftPad(this.getMonth() + 1, 2, '0') + "; case "M": return "Date.getShortMonthName(this.getMonth()) + "; case "n": return "(this.getMonth() + 1) + "; case "t": return "this.getDaysInMonth() + "; case "L": return "(this.isLeapYear() ? 1 : 0) + "; case "o": return "(this.getFullYear() + (this.getWeekOfYear() == 1 && this.getMonth() > 0 ? +1 : (this.getWeekOfYear() >= 52 && this.getMonth() < 11 ? -1 : 0))) + "; case "Y": return "this.getFullYear() + "; case "y": return "('' + this.getFullYear()).substring(2, 4) + "; case "a": return "(this.getHours() < 12 ? 'am' : 'pm') + "; case "A": return "(this.getHours() < 12 ? 'AM' : 'PM') + "; case "g": return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + "; case "G": return "this.getHours() + "; case "h": return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + "; case "H": return "String.leftPad(this.getHours(), 2, '0') + "; case "i": return "String.leftPad(this.getMinutes(), 2, '0') + "; case "s": return "String.leftPad(this.getSeconds(), 2, '0') + "; case "u": return "String.leftPad(this.getMilliseconds(), 3, '0') + "; case "O": return "this.getGMTOffset() + "; case "P": return "this.getGMTOffset(true) + "; case "T": return "this.getTimezone() + "; case "Z": return "(this.getTimezoneOffset() * -60) + "; case "c": for (var df = Date.getFormatCode, c = "Y-m-dTH:i:sP", code = "", i = 0, l = c.length; i < l; ++i) { var e = c.charAt(i); code += e == "T" ? "'T' + " : df(e); } return code; case "U": return "Math.round(this.getTime() / 1000) + "; default: return "'" + String.escape(character) + "' + "; } }; Date.parseDate = function(input, format) { if (Date.parseFunctions[format] == null) { Date.createParser(format); } var func = Date.parseFunctions[format]; return Date[func](input); }; Date.createParser = function(format) { var funcName = "parse" + Date.parseFunctions.count++; var regexNum = Date.parseRegexes.length; var currentGroup = 1; Date.parseFunctions[format] = funcName; var code = "Date." + funcName + " = function(input){\n" + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, ms = -1, o, z, u, v;\n" + "input = String(input);var d = new Date();\n" + "y = d.getFullYear();\n" + "m = d.getMonth();\n" + "d = d.getDate();\n" + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n" + "if (results && results.length > 0) {"; var regex = ""; var special = false; var ch = ''; for (var i = 0; i < format.length; ++i) { ch = format.charAt(i); if (!special && ch == "\\") { special = true; } else if (special) { special = false; regex += String.escape(ch); } else { var obj = Date.formatCodeToRegex(ch, currentGroup); currentGroup += obj.g; regex += obj.s; if (obj.g && obj.c) { code += obj.c; } } } code += "if (u)\n" + "{v = new Date(u * 1000);}" + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0 && ms >= 0)\n" + "{v = new Date(y, m, d, h, i, s, ms);}\n" + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n" + "{v = new Date(y, m, d, h, i, s);}\n" + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n" + "{v = new Date(y, m, d, h, i);}\n" + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n" + "{v = new Date(y, m, d, h);}\n" + "else if (y >= 0 && m >= 0 && d > 0)\n" + "{v = new Date(y, m, d);}\n" + "else if (y >= 0 && m >= 0)\n" + "{v = new Date(y, m);}\n" + "else if (y >= 0)\n" + "{v = new Date(y);}\n" + "}return (v && (z || o))?\n" + " (z ? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" + ";}"; Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$", "i"); eval(code); }; Date.formatCodeToRegex = function(character, currentGroup) { switch (character) { case "d": return {g:1, c:"d = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{2})"}; case "D": for (var a = [], i = 0; i < 7; a.push(Date.getShortDayName(i)), ++i); return {g:0, c:null, s:"(?:" + a.join("|") +")"}; case "j": return {g:1, c:"d = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{1,2})"}; case "l": return {g:0, c:null, s:"(?:" + Date.dayNames.join("|") + ")"}; case "N": return {g:0, c:null, s:"[1-7]"}; case "S": return {g:0, c:null, s:"(?:st|nd|rd|th)"}; case "w": return {g:0, c:null, s:"[0-6]"}; case "z": return {g:0, c:null, s:"(?:\\d{1,3}"}; case "W": return {g:0, c:null, s:"(?:\\d{2})"}; case "F": return {g:1, c:"m = parseInt(Date.getMonthNumber(results[" + currentGroup + "]), 10);\n", s:"(" + Date.monthNames.join("|") + ")"}; case "m": return {g:1, c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n", s:"(\\d{2})"}; case "M": for (var a = [], i = 0; i < 12; a.push(Date.getShortMonthName(i)), ++i); return {g:1, c:"m = parseInt(Date.getMonthNumber(results[" + currentGroup + "]), 10);\n", s:"(" + a.join("|") + ")"}; case "n": return {g:1, c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n", s:"(\\d{1,2})"}; case "t": return {g:0, c:null, s:"(?:\\d{2})"}; case "L": return {g:0, c:null, s:"(?:1|0)"}; case "o": case "Y": return {g:1, c:"y = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{4})"}; case "y": return {g:1, c:"var ty = parseInt(results[" + currentGroup + "], 10);\n" + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n", s:"(\\d{1,2})"}; case "a": return {g:1, c:"if (results[" + currentGroup + "] == 'am') {\n" + "if (h == 12) { h = 0; }\n" + "} else { if (h < 12) { h += 12; }}", s:"(am|pm)"}; case "A": return {g:1, c:"if (results[" + currentGroup + "] == 'AM') {\n" + "if (h == 12) { h = 0; }\n" + "} else { if (h < 12) { h += 12; }}", s:"(AM|PM)"}; case "g": case "G": return {g:1, c:"h = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{1,2})"}; case "h": case "H": return {g:1, c:"h = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{2})"}; case "i": return {g:1, c:"i = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{2})"}; case "s": return {g:1, c:"s = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{2})"}; case "u": return {g:1, c:"ms = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{3})"}; case "O": return {g:1, c:[ "o = results[", currentGroup, "];\n", "var sn = o.substring(0,1);\n", "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", "var mn = o.substring(3,5) % 60;\n", "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", " (sn + String.leftPad(hr, 2, '0') + String.leftPad(mn, 2, '0')) : null;\n" ].join(""), s: "([+\-]\\d{4})"}; case "P": return {g:1, c:[ "o = results[", currentGroup, "];\n", "var sn = o.substring(0,1);\n", "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n", "var mn = o.substring(4,6) % 60;\n", "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", " (sn + String.leftPad(hr, 2, '0') + String.leftPad(mn, 2, '0')) : null;\n" ].join(""), s: "([+\-]\\d{2}:\\d{2})"}; case "T": return {g:0, c:null, s:"[A-Z]{1,4}"}; case "Z": return {g:1, c:"z = results[" + currentGroup + "] * 1;\n" + "z = (-43200 <= z && z <= 50400)? z : null;\n", s:"([+\-]?\\d{1,5})"}; case "c": var df = Date.formatCodeToRegex, calc = []; var arr = [df("Y", 1), df("m", 2), df("d", 3), df("h", 4), df("i", 5), df("s", 6), df("P", 7)]; for (var i = 0, l = arr.length; i < l; ++i) { calc.push(arr[i].c); } return {g:1, c:calc.join(""), s:arr[0].s + "-" + arr[1].s + "-" + arr[2].s + "T" + arr[3].s + ":" + arr[4].s + ":" + arr[5].s + arr[6].s}; case "U": return {g:1, c:"u = parseInt(results[" + currentGroup + "], 10);\n", s:"(-?\\d+)"}; default: return {g:0, c:null, s:Ext.escapeRe(character)}; } }; Date.prototype.getTimezone = function() { return this.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, ""); }; Date.prototype.getGMTOffset = function(colon) { return (this.getTimezoneOffset() > 0 ? "-" : "+") + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0") + (colon ? ":" : "") + String.leftPad(this.getTimezoneOffset() % 60, 2, "0"); }; Date.prototype.getDayOfYear = function() { var num = 0; Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28; for (var i = 0; i < this.getMonth(); ++i) { num += Date.daysInMonth[i]; } return num + this.getDate() - 1; }; Date.prototype.getWeekOfYear = function() { var ms1d = 864e5; var ms7d = 7 * ms1d; var DC3 = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate() + 3) / ms1d; var AWN = Math.floor(DC3 / 7); var Wyr = new Date(AWN * ms7d).getUTCFullYear(); return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1; }; Date.prototype.isLeapYear = function() { var year = this.getFullYear(); return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year))); }; Date.prototype.getFirstDayOfMonth = function() { var day = (this.getDay() - (this.getDate() - 1)) % 7; return (day < 0) ? (day + 7) : day; }; Date.prototype.getLastDayOfMonth = function() { var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7; return (day < 0) ? (day + 7) : day; }; Date.prototype.getFirstDateOfMonth = function() { return new Date(this.getFullYear(), this.getMonth(), 1); }; Date.prototype.getLastDateOfMonth = function() { return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth()); }; Date.prototype.getDaysInMonth = function() { Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28; return Date.daysInMonth[this.getMonth()]; }; Date.prototype.getSuffix = function() { switch (this.getDate()) { case 1: case 21: case 31: return "st"; case 2: case 22: return "nd"; case 3: case 23: return "rd"; default: return "th"; } }; Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31]; Date.monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; Date.getShortMonthName = function(month) { return Date.monthNames[month].substring(0, 3); } Date.dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; Date.getShortDayName = function(day) { return Date.dayNames[day].substring(0, 3); } Date.y2kYear = 50; Date.monthNumbers = { Jan:0, Feb:1, Mar:2, Apr:3, May:4, Jun:5, Jul:6, Aug:7, Sep:8, Oct:9, Nov:10, Dec:11}; Date.getMonthNumber = function(name) { return Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()]; } Date.prototype.clone = function() { return new Date(this.getTime()); }; Date.prototype.clearTime = function(clone){ if(clone){ return this.clone().clearTime(); } this.setHours(0); this.setMinutes(0); this.setSeconds(0); this.setMilliseconds(0); return this; }; if(Ext.isSafari){ Date.brokenSetMonth = Date.prototype.setMonth; Date.prototype.setMonth = function(num){ if(num <= -1){ var n = Math.ceil(-num); var back_year = Math.ceil(n/12); var month = (n % 12) ? 12 - n % 12 : 0 ; this.setFullYear(this.getFullYear() - back_year); return Date.brokenSetMonth.call(this, month); } else { return Date.brokenSetMonth.apply(this, arguments); } }; } Date.MILLI = "ms"; Date.SECOND = "s"; Date.MINUTE = "mi"; Date.HOUR = "h"; Date.DAY = "d"; Date.MONTH = "mo"; Date.YEAR = "y"; Date.prototype.add = function(interval, value){ var d = this.clone(); if (!interval || value === 0) return d; switch(interval.toLowerCase()){ case Date.MILLI: d.setMilliseconds(this.getMilliseconds() + value); break; case Date.SECOND: d.setSeconds(this.getSeconds() + value); break; case Date.MINUTE: d.setMinutes(this.getMinutes() + value); break; case Date.HOUR: d.setHours(this.getHours() + value); break; case Date.DAY: d.setDate(this.getDate() + value); break; case Date.MONTH: var day = this.getDate(); if(day > 28){ day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate()); } d.setDate(day); d.setMonth(this.getMonth() + value); break; case Date.YEAR: d.setFullYear(this.getFullYear() + value); break; } return d; }; Date.prototype.between = function(start, end){ var t = this.getTime(); return start.getTime() <= t && t <= end.getTime(); } Ext.util.DelayedTask = function(fn, scope, args){ var id = null, d, t; var call = function(){ var now = new Date().getTime(); if(now - t >= d){ clearInterval(id); id = null; fn.apply(scope, args || []); } }; this.delay = function(delay, newFn, newScope, newArgs){ if(id && delay != d){ this.cancel(); } d = delay; t = new Date().getTime(); fn = newFn || fn; scope = newScope || scope; args = newArgs || args; if(!id){ id = setInterval(call, d); } }; this.cancel = function(){ if(id){ clearInterval(id); id = null; } }; }; Ext.util.TaskRunner = function(interval){ interval = interval || 10; var tasks = [], removeQueue = []; var id = 0; var running = false; var stopThread = function(){ running = false; clearInterval(id); id = 0; }; var startThread = function(){ if(!running){ running = true; id = setInterval(runTasks, interval); } }; var removeTask = function(t){ removeQueue.push(t); if(t.onStop){ t.onStop.apply(t.scope || t); } }; var runTasks = function(){ if(removeQueue.length > 0){ for(var i = 0, len = removeQueue.length; i < len; i++){ tasks.remove(removeQueue[i]); } removeQueue = []; if(tasks.length < 1){ stopThread(); return; } } var now = new Date().getTime(); for(var i = 0, len = tasks.length; i < len; ++i){ var t = tasks[i]; var itime = now - t.taskRunTime; if(t.interval <= itime){ var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]); t.taskRunTime = now; if(rt === false || t.taskRunCount === t.repeat){ removeTask(t); return; } } if(t.duration && t.duration <= (now - t.taskStartTime)){ removeTask(t); } } }; this.start = function(task){ tasks.push(task); task.taskStartTime = new Date().getTime(); task.taskRunTime = 0; task.taskRunCount = 0; startThread(); return task; }; this.stop = function(task){ removeTask(task); return task; }; this.stopAll = function(){ stopThread(); for(var i = 0, len = tasks.length; i < len; i++){ if(tasks[i].onStop){ tasks[i].onStop(); } } tasks = []; removeQueue = []; }; }; Ext.TaskMgr = new Ext.util.TaskRunner(); Ext.util.MixedCollection = function(allowFunctions, keyFn){ this.items = []; this.map = {}; this.keys = []; this.length = 0; this.addEvents( "clear", "add", "replace", "remove", "sort" ); this.allowFunctions = allowFunctions === true; if(keyFn){ this.getKey = keyFn; } Ext.util.MixedCollection.superclass.constructor.call(this); }; Ext.extend(Ext.util.MixedCollection, Ext.util.Observable, { allowFunctions : false, add : function(key, o){ if(arguments.length == 1){ o = arguments[0]; key = this.getKey(o); } if(typeof key == "undefined" || key === null){ this.length++; this.items.push(o); this.keys.push(null); }else{ var old = this.map[key]; if(old){ return this.replace(key, o); } this.length++; this.items.push(o); this.map[key] = o; this.keys.push(key); } this.fireEvent("add", this.length-1, o, key); return o; }, getKey : function(o){ return o.id; }, replace : function(key, o){ if(arguments.length == 1){ o = arguments[0]; key = this.getKey(o); } var old = this.item(key); if(typeof key == "undefined" || key === null || typeof old == "undefined"){ return this.add(key, o); } var index = this.indexOfKey(key); this.items[index] = o; this.map[key] = o; this.fireEvent("replace", key, old, o); return o; }, addAll : function(objs){ if(arguments.length > 1 || Ext.isArray(objs)){ var args = arguments.length > 1 ? arguments : objs; for(var i = 0, len = args.length; i < len; i++){ this.add(args[i]); } }else{ for(var key in objs){ if(this.allowFunctions || typeof objs[key] != "function"){ this.add(key, objs[key]); } } } }, each : function(fn, scope){ var items = [].concat(this.items); for(var i = 0, len = items.length; i < len; i++){ if(fn.call(scope || items[i], items[i], i, len) === false){ break; } } }, eachKey : function(fn, scope){ for(var i = 0, len = this.keys.length; i < len; i++){ fn.call(scope || window, this.keys[i], this.items[i], i, len); } }, find : function(fn, scope){ for(var i = 0, len = this.items.length; i < len; i++){ if(fn.call(scope || window, this.items[i], this.keys[i])){ return this.items[i]; } } return null; }, insert : function(index, key, o){ if(arguments.length == 2){ o = arguments[1]; key = this.getKey(o); } if(index >= this.length){ return this.add(key, o); } this.length++; this.items.splice(index, 0, o); if(typeof key != "undefined" && key != null){ this.map[key] = o; } this.keys.splice(index, 0, key); this.fireEvent("add", index, o, key); return o; }, remove : function(o){ return this.removeAt(this.indexOf(o)); }, removeAt : function(index){ if(index < this.length && index >= 0){ this.length--; var o = this.items[index]; this.items.splice(index, 1); var key = this.keys[index]; if(typeof key != "undefined"){ delete this.map[key]; } this.keys.splice(index, 1); this.fireEvent("remove", o, key); return o; } return false; }, removeKey : function(key){ return this.removeAt(this.indexOfKey(key)); }, getCount : function(){ return this.length; }, indexOf : function(o){ return this.items.indexOf(o); }, indexOfKey : function(key){ return this.keys.indexOf(key); }, item : function(key){ var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key]; return typeof item != 'function' || this.allowFunctions ? item : null; }, itemAt : function(index){ return this.items[index]; }, key : function(key){ return this.map[key]; }, contains : function(o){ return this.indexOf(o) != -1; }, containsKey : function(key){ return typeof this.map[key] != "undefined"; }, clear : function(){ this.length = 0; this.items = []; this.keys = []; this.map = {}; this.fireEvent("clear"); }, first : function(){ return this.items[0]; }, last : function(){ return this.items[this.length-1]; }, _sort : function(property, dir, fn){ var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1; fn = fn || function(a, b){ return a-b; }; var c = [], k = this.keys, items = this.items; for(var i = 0, len = items.length; i < len; i++){ c[c.length] = {key: k[i], value: items[i], index: i}; } c.sort(function(a, b){ var v = fn(a[property], b[property]) * dsc; if(v == 0){ v = (a.index < b.index ? -1 : 1); } return v; }); for(var i = 0, len = c.length; i < len; i++){ items[i] = c[i].value; k[i] = c[i].key; } this.fireEvent("sort", this); }, sort : function(dir, fn){ this._sort("value", dir, fn); }, keySort : function(dir, fn){ this._sort("key", dir, fn || function(a, b){ return String(a).toUpperCase()-String(b).toUpperCase(); }); }, getRange : function(start, end){ var items = this.items; if(items.length < 1){ return []; } start = start || 0; end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1); var r = []; if(start <= end){ for(var i = start; i <= end; i++) { r[r.length] = items[i]; } }else{ for(var i = start; i >= end; i--) { r[r.length] = items[i]; } } return r; }, filter : function(property, value, anyMatch, caseSensitive){ if(Ext.isEmpty(value, false)){ return this.clone(); } value = this.createValueMatcher(value, anyMatch, caseSensitive); return this.filterBy(function(o){ return o && value.test(o[property]); }); }, filterBy : function(fn, scope){ var r = new Ext.util.MixedCollection(); r.getKey = this.getKey; var k = this.keys, it = this.items; for(var i = 0, len = it.length; i < len; i++){ if(fn.call(scope||this, it[i], k[i])){ r.add(k[i], it[i]); } } return r; }, findIndex : function(property, value, start, anyMatch, caseSensitive){ if(Ext.isEmpty(value, false)){ return -1; } value = this.createValueMatcher(value, anyMatch, caseSensitive); return this.findIndexBy(function(o){ return o && value.test(o[property]); }, null, start); }, findIndexBy : function(fn, scope, start){ var k = this.keys, it = this.items; for(var i = (start||0), len = it.length; i < len; i++){ if(fn.call(scope||this, it[i], k[i])){ return i; } } if(typeof start == 'number' && start > 0){ for(var i = 0; i < start; i++){ if(fn.call(scope||this, it[i], k[i])){ return i; } } } return -1; }, createValueMatcher : function(value, anyMatch, caseSensitive){ if(!value.exec){ value = String(value); value = new RegExp((anyMatch === true ? '' : '^') + Ext.escapeRe(value), caseSensitive ? '' : 'i'); } return value; }, clone : function(){ var r = new Ext.util.MixedCollection(); var k = this.keys, it = this.items; for(var i = 0, len = it.length; i < len; i++){ r.add(k[i], it[i]); } r.getKey = this.getKey; return r; } }); Ext.util.MixedCollection.prototype.get = Ext.util.MixedCollection.prototype.item; Ext.util.JSON = new (function(){ var useHasOwn = {}.hasOwnProperty ? true : false; var pad = function(n) { return n < 10 ? "0" + n : n; }; var m = { "\b": '\\b', "\t": '\\t', "\n": '\\n', "\f": '\\f', "\r": '\\r', '"' : '\\"', "\\": '\\\\' }; var encodeString = function(s){ if (/["\\\x00-\x1f]/.test(s)) { return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) { var c = m[b]; if(c){ return c; } c = b.charCodeAt(); return "\\u00" + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }) + '"'; } return '"' + s + '"'; }; var encodeArray = function(o){ var a = ["["], b, i, l = o.length, v; for (i = 0; i < l; i += 1) { v = o[i]; switch (typeof v) { case "undefined": case "function": case "unknown": break; default: if (b) { a.push(','); } a.push(v === null ? "null" : Ext.util.JSON.encode(v)); b = true; } } a.push("]"); return a.join(""); }; var encodeDate = function(o){ return '"' + o.getFullYear() + "-" + pad(o.getMonth() + 1) + "-" + pad(o.getDate()) + "T" + pad(o.getHours()) + ":" + pad(o.getMinutes()) + ":" + pad(o.getSeconds()) + '"'; }; this.encode = function(o){ if(typeof o == "undefined" || o === null){ return "null"; }else if(Ext.isArray(o)){ return encodeArray(o); }else if(Ext.isDate(o)){ return encodeDate(o); }else if(typeof o == "string"){ return encodeString(o); }else if(typeof o == "number"){ return isFinite(o) ? String(o) : "null"; }else if(typeof o == "boolean"){ return String(o); }else { var a = ["{"], b, i, v; for (i in o) { if(!useHasOwn || o.hasOwnProperty(i)) { v = o[i]; switch (typeof v) { case "undefined": case "function": case "unknown": break; default: if(b){ a.push(','); } a.push(this.encode(i), ":", v === null ? "null" : this.encode(v)); b = true; } } } a.push("}"); return a.join(""); } }; this.decode = function(json){ return eval("(" + json + ')'); }; })(); Ext.encode = Ext.util.JSON.encode; Ext.decode = Ext.util.JSON.decode; Ext.util.Format = function(){ var trimRe = /^\s+|\s+$/g; return { ellipsis : function(value, len){ if(value && value.length > len){ return value.substr(0, len-3)+"..."; } return value; }, undef : function(value){ return value !== undefined ? value : ""; }, defaultValue : function(value, defaultValue){ return value !== undefined && value !== '' ? value : defaultValue; }, htmlEncode : function(value){ return !value ? value : String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;"); }, htmlDecode : function(value){ return !value ? value : String(value).replace(/&amp;/g, "&").replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"'); }, trim : function(value){ return String(value).replace(trimRe, ""); }, substr : function(value, start, length){ return String(value).substr(start, length); }, lowercase : function(value){ return String(value).toLowerCase(); }, uppercase : function(value){ return String(value).toUpperCase(); }, capitalize : function(value){ return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase(); }, call : function(value, fn){ if(arguments.length > 2){ var args = Array.prototype.slice.call(arguments, 2); args.unshift(value); return eval(fn).apply(window, args); }else{ return eval(fn).call(window, value); } }, usMoney : function(v){ v = (Math.round((v-0)*100))/100; v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v); v = String(v); var ps = v.split('.'); var whole = ps[0]; var sub = ps[1] ? '.'+ ps[1] : '.00'; var r = /(\d+)(\d{3})/; while (r.test(whole)) { whole = whole.replace(r, '$1' + ',' + '$2'); } v = whole + sub; if(v.charAt(0) == '-'){ return '-$' + v.substr(1); } return "$" + v; }, date : function(v, format){ if(!v){ return ""; } if(!Ext.isDate(v)){ v = new Date(Date.parse(v)); } return v.dateFormat(format || "m/d/Y"); }, dateRenderer : function(format){ return function(v){ return Ext.util.Format.date(v, format); }; }, stripTagsRE : /<\/?[^>]+>/gi, stripTags : function(v){ return !v ? v : String(v).replace(this.stripTagsRE, ""); }, stripScriptsRe : /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, stripScripts : function(v){ return !v ? v : String(v).replace(this.stripScriptsRe, ""); }, fileSize : function(size){ if(size < 1024) { return size + " bytes"; } else if(size < 1048576) { return (Math.round(((size*10) / 1024))/10) + " KB"; } else { return (Math.round(((size*10) / 1048576))/10) + " MB"; } }, math : function(){ var fns = {}; return function(v, a){ if(!fns[a]){ fns[a] = new Function('v', 'return v ' + a + ';'); } return fns[a](v); } }() }; }(); Ext.XTemplate = function(){ Ext.XTemplate.superclass.constructor.apply(this, arguments); var s = this.html; s = ['<tpl>', s, '</tpl>'].join(''); var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/; var nameRe = /^<tpl\b[^>]*?for="(.*?)"/; var ifRe = /^<tpl\b[^>]*?if="(.*?)"/; var execRe = /^<tpl\b[^>]*?exec="(.*?)"/; var m, id = 0; var tpls = []; while(m = s.match(re)){ var m2 = m[0].match(nameRe); var m3 = m[0].match(ifRe); var m4 = m[0].match(execRe); var exp = null, fn = null, exec = null; var name = m2 && m2[1] ? m2[1] : ''; if(m3){ exp = m3 && m3[1] ? m3[1] : null; if(exp){ fn = new Function('values', 'parent', 'xindex', 'xcount', 'with(values){ return '+(Ext.util.Format.htmlDecode(exp))+'; }'); } } if(m4){ exp = m4 && m4[1] ? m4[1] : null; if(exp){ exec = new Function('values', 'parent', 'xindex', 'xcount', 'with(values){ '+(Ext.util.Format.htmlDecode(exp))+'; }'); } } if(name){ switch(name){ case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break; case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break; default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }'); } } tpls.push({ id: id, target: name, exec: exec, test: fn, body: m[1]||'' }); s = s.replace(m[0], '{xtpl'+ id + '}'); ++id; } for(var i = tpls.length-1; i >= 0; --i){ this.compileTpl(tpls[i]); } this.master = tpls[tpls.length-1]; this.tpls = tpls; }; Ext.extend(Ext.XTemplate, Ext.Template, { re : /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\\]\s?[\d\.\+\-\*\\\(\)]+)?\}/g, codeRe : /\{\[((?:\\\]|.|\n)*?)\]\}/g, applySubTemplate : function(id, values, parent, xindex, xcount){ var t = this.tpls[id]; if(t.test && !t.test.call(this, values, parent, xindex, xcount)){ return ''; } if(t.exec && t.exec.call(this, values, parent, xindex, xcount)){ return ''; } var vs = t.target ? t.target.call(this, values, parent) : values; parent = t.target ? values : parent; if(t.target && Ext.isArray(vs)){ var buf = []; for(var i = 0, len = vs.length; i < len; i++){ buf[buf.length] = t.compiled.call(this, vs[i], parent, i+1, len); } return buf.join(''); } return t.compiled.call(this, vs, parent, xindex, xcount); }, compileTpl : function(tpl){ var fm = Ext.util.Format; var useF = this.disableFormats !== true; var sep = Ext.isGecko ? "+" : ","; var fn = function(m, name, format, args, math){ if(name.substr(0, 4) == 'xtpl'){ return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent, xindex, xcount)'+sep+"'"; } var v; if(name === '.'){ v = 'values'; }else if(name === '#'){ v = 'xindex'; }else if(name.indexOf('.') != -1){ v = name; }else{ v = "values['" + name + "']"; } if(math){ v = '(' + v + math + ')'; } if(format && useF){ args = args ? ',' + args : ""; if(format.substr(0, 5) != "this."){ format = "fm." + format + '('; }else{ format = 'this.call("'+ format.substr(5) + '", '; args = ", values"; } }else{ args= ''; format = "("+v+" === undefined ? '' : "; } return "'"+ sep + format + v + args + ")"+sep+"'"; }; var codeFn = function(m, code){ return "'"+ sep +'('+code+')'+sep+"'"; }; var body; if(Ext.isGecko){ body = "tpl.compiled = function(values, parent, xindex, xcount){ return '" + tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn) + "';};"; }else{ body = ["tpl.compiled = function(values, parent, xindex, xcount){ return ['"]; body.push(tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn)); body.push("'].join('');};"); body = body.join(''); } eval(body); return this; }, apply : function(values){ return this.master.compiled.call(this, values, {}, 1, 1); }, applyTemplate : function(values){ return this.master.compiled.call(this, values, {}, 1, 1); }, compile : function(){return this;} }); Ext.XTemplate.from = function(el){ el = Ext.getDom(el); return new Ext.XTemplate(el.value || el.innerHTML); }; Ext.util.CSS = function(){ var rules = null; var doc = document; var camelRe = /(-[a-z])/gi; var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); }; return { createStyleSheet : function(cssText, id){ var ss; var head = doc.getElementsByTagName("head")[0]; var rules = doc.createElement("style"); rules.setAttribute("type", "text/css"); if(id){ rules.setAttribute("id", id); } if(Ext.isIE){ head.appendChild(rules); ss = rules.styleSheet; ss.cssText = cssText; }else{ try{ rules.appendChild(doc.createTextNode(cssText)); }catch(e){ rules.cssText = cssText; } head.appendChild(rules); ss = rules.styleSheet ? rules.styleSheet : (rules.sheet || doc.styleSheets[doc.styleSheets.length-1]); } this.cacheStyleSheet(ss); return ss; }, removeStyleSheet : function(id){ var existing = doc.getElementById(id); if(existing){ existing.parentNode.removeChild(existing); } }, swapStyleSheet : function(id, url){ this.removeStyleSheet(id); var ss = doc.createElement("link"); ss.setAttribute("rel", "stylesheet"); ss.setAttribute("type", "text/css"); ss.setAttribute("id", id); ss.setAttribute("href", url); doc.getElementsByTagName("head")[0].appendChild(ss); }, refreshCache : function(){ return this.getRules(true); }, cacheStyleSheet : function(ss){ if(!rules){ rules = {}; } try{ var ssRules = ss.cssRules || ss.rules; for(var j = ssRules.length-1; j >= 0; --j){ rules[ssRules[j].selectorText] = ssRules[j]; } }catch(e){} }, getRules : function(refreshCache){ if(rules == null || refreshCache){ rules = {}; var ds = doc.styleSheets; for(var i =0, len = ds.length; i < len; i++){ try{ this.cacheStyleSheet(ds[i]); }catch(e){} } } return rules; }, getRule : function(selector, refreshCache){ var rs = this.getRules(refreshCache); if(!Ext.isArray(selector)){ return rs[selector]; } for(var i = 0; i < selector.length; i++){ if(rs[selector[i]]){ return rs[selector[i]]; } } return null; }, updateRule : function(selector, property, value){ if(!Ext.isArray(selector)){ var rule = this.getRule(selector); if(rule){ rule.style[property.replace(camelRe, camelFn)] = value; return true; } }else{ for(var i = 0; i < selector.length; i++){ if(this.updateRule(selector[i], property, value)){ return true; } } } return false; } }; }(); Ext.util.ClickRepeater = function(el, config) { this.el = Ext.get(el); this.el.unselectable(); Ext.apply(this, config); this.addEvents( "mousedown", "click", "mouseup" ); this.el.on("mousedown", this.handleMouseDown, this); if(this.preventDefault || this.stopDefault){ this.el.on("click", function(e){ if(this.preventDefault){ e.preventDefault(); } if(this.stopDefault){ e.stopEvent(); } }, this); } if(this.handler){ this.on("click", this.handler, this.scope || this); } Ext.util.ClickRepeater.superclass.constructor.call(this); }; Ext.extend(Ext.util.ClickRepeater, Ext.util.Observable, { interval : 20, delay: 250, preventDefault : true, stopDefault : false, timer : 0, handleMouseDown : function(){ clearTimeout(this.timer); this.el.blur(); if(this.pressClass){ this.el.addClass(this.pressClass); } this.mousedownTime = new Date(); Ext.getDoc().on("mouseup", this.handleMouseUp, this); this.el.on("mouseout", this.handleMouseOut, this); this.fireEvent("mousedown", this); this.fireEvent("click", this); if (this.accelerate) { this.delay = 400; } this.timer = this.click.defer(this.delay || this.interval, this); }, click : function(){ this.fireEvent("click", this); this.timer = this.click.defer(this.accelerate ? this.easeOutExpo(this.mousedownTime.getElapsed(), 400, -390, 12000) : this.interval, this); }, easeOutExpo : function (t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, handleMouseOut : function(){ clearTimeout(this.timer); if(this.pressClass){ this.el.removeClass(this.pressClass); } this.el.on("mouseover", this.handleMouseReturn, this); }, handleMouseReturn : function(){ this.el.un("mouseover", this.handleMouseReturn); if(this.pressClass){ this.el.addClass(this.pressClass); } this.click(); }, handleMouseUp : function(){ clearTimeout(this.timer); this.el.un("mouseover", this.handleMouseReturn); this.el.un("mouseout", this.handleMouseOut); Ext.getDoc().un("mouseup", this.handleMouseUp); this.el.removeClass(this.pressClass); this.fireEvent("mouseup", this); } }); Ext.KeyNav = function(el, config){ this.el = Ext.get(el); Ext.apply(this, config); if(!this.disabled){ this.disabled = true; this.enable(); } }; Ext.KeyNav.prototype = { disabled : false, defaultEventAction: "stopEvent", forceKeyDown : false, prepareEvent : function(e){ var k = e.getKey(); var h = this.keyToHandler[k]; if(Ext.isSafari && h && k >= 37 && k <= 40){ e.stopEvent(); } }, relay : function(e){ var k = e.getKey(); var h = this.keyToHandler[k]; if(h && this[h]){ if(this.doRelay(e, this[h], h) !== true){ e[this.defaultEventAction](); } } }, doRelay : function(e, h, hname){ return h.call(this.scope || this, e); }, enter : false, left : false, right : false, up : false, down : false, tab : false, esc : false, pageUp : false, pageDown : false, del : false, home : false, end : false, keyToHandler : { 37 : "left", 39 : "right", 38 : "up", 40 : "down", 33 : "pageUp", 34 : "pageDown", 46 : "del", 36 : "home", 35 : "end", 13 : "enter", 27 : "esc", 9 : "tab" }, enable: function(){ if(this.disabled){ if(this.forceKeyDown || Ext.isIE || Ext.isAir){ this.el.on("keydown", this.relay, this); }else{ this.el.on("keydown", this.prepareEvent, this); this.el.on("keypress", this.relay, this); } this.disabled = false; } }, disable: function(){ if(!this.disabled){ if(this.forceKeyDown || Ext.isIE || Ext.isAir){ this.el.un("keydown", this.relay); }else{ this.el.un("keydown", this.prepareEvent); this.el.un("keypress", this.relay); } this.disabled = true; } } }; Ext.KeyMap = function(el, config, eventName){ this.el = Ext.get(el); this.eventName = eventName || "keydown"; this.bindings = []; if(config){ this.addBinding(config); } this.enable(); }; Ext.KeyMap.prototype = { stopEvent : false, addBinding : function(config){ if(Ext.isArray(config)){ for(var i = 0, len = config.length; i < len; i++){ this.addBinding(config[i]); } return; } var keyCode = config.key, shift = config.shift, ctrl = config.ctrl, alt = config.alt, fn = config.fn || config.handler, scope = config.scope; if(typeof keyCode == "string"){ var ks = []; var keyString = keyCode.toUpperCase(); for(var j = 0, len = keyString.length; j < len; j++){ ks.push(keyString.charCodeAt(j)); } keyCode = ks; } var keyArray = Ext.isArray(keyCode); var handler = function(e){ if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){ var k = e.getKey(); if(keyArray){ for(var i = 0, len = keyCode.length; i < len; i++){ if(keyCode[i] == k){ if(this.stopEvent){ e.stopEvent(); } fn.call(scope || window, k, e); return; } } }else{ if(k == keyCode){ if(this.stopEvent){ e.stopEvent(); } fn.call(scope || window, k, e); } } } }; this.bindings.push(handler); }, on : function(key, fn, scope){ var keyCode, shift, ctrl, alt; if(typeof key == "object" && !Ext.isArray(key)){ keyCode = key.key; shift = key.shift; ctrl = key.ctrl; alt = key.alt; }else{ keyCode = key; } this.addBinding({ key: keyCode, shift: shift, ctrl: ctrl, alt: alt, fn: fn, scope: scope }) }, handleKeyDown : function(e){ if(this.enabled){ var b = this.bindings; for(var i = 0, len = b.length; i < len; i++){ b[i].call(this, e); } } }, isEnabled : function(){ return this.enabled; }, enable: function(){ if(!this.enabled){ this.el.on(this.eventName, this.handleKeyDown, this); this.enabled = true; } }, disable: function(){ if(this.enabled){ this.el.removeListener(this.eventName, this.handleKeyDown, this); this.enabled = false; } } }; Ext.util.TextMetrics = function(){ var shared; return { measure : function(el, text, fixedWidth){ if(!shared){ shared = Ext.util.TextMetrics.Instance(el, fixedWidth); } shared.bind(el); shared.setFixedWidth(fixedWidth || 'auto'); return shared.getSize(text); }, createInstance : function(el, fixedWidth){ return Ext.util.TextMetrics.Instance(el, fixedWidth); } }; }(); Ext.util.TextMetrics.Instance = function(bindTo, fixedWidth){ var ml = new Ext.Element(document.createElement('div')); document.body.appendChild(ml.dom); ml.position('absolute'); ml.setLeftTop(-1000, -1000); ml.hide(); if(fixedWidth){ ml.setWidth(fixedWidth); } var instance = { getSize : function(text){ ml.update(text); var s = ml.getSize(); ml.update(''); return s; }, bind : function(el){ ml.setStyle( Ext.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height') ); }, setFixedWidth : function(width){ ml.setWidth(width); }, getWidth : function(text){ ml.dom.style.width = 'auto'; return this.getSize(text).width; }, getHeight : function(text){ return this.getSize(text).height; } }; instance.bind(bindTo); return instance; }; Ext.Element.measureText = Ext.util.TextMetrics.measure; (function() { var Event=Ext.EventManager; var Dom=Ext.lib.Dom; Ext.dd.DragDrop = function(id, sGroup, config) { if(id) { this.init(id, sGroup, config); } }; Ext.dd.DragDrop.prototype = { id: null, config: null, dragElId: null, handleElId: null, invalidHandleTypes: null, invalidHandleIds: null, invalidHandleClasses: null, startPageX: 0, startPageY: 0, groups: null, locked: false, lock: function() { this.locked = true; }, unlock: function() { this.locked = false; }, isTarget: true, padding: null, _domRef: null, __ygDragDrop: true, constrainX: false, constrainY: false, minX: 0, maxX: 0, minY: 0, maxY: 0, maintainOffset: false, xTicks: null, yTicks: null, primaryButtonOnly: true, available: false, hasOuterHandles: false, b4StartDrag: function(x, y) { }, startDrag: function(x, y) { }, b4Drag: function(e) { }, onDrag: function(e) { }, onDragEnter: function(e, id) { }, b4DragOver: function(e) { }, onDragOver: function(e, id) { }, b4DragOut: function(e) { }, onDragOut: function(e, id) { }, b4DragDrop: function(e) { }, onDragDrop: function(e, id) { }, onInvalidDrop: function(e) { }, b4EndDrag: function(e) { }, endDrag: function(e) { }, b4MouseDown: function(e) { }, onMouseDown: function(e) { }, onMouseUp: function(e) { }, onAvailable: function () { }, defaultPadding : {left:0, right:0, top:0, bottom:0}, constrainTo : function(constrainTo, pad, inContent){ if(typeof pad == "number"){ pad = {left: pad, right:pad, top:pad, bottom:pad}; } pad = pad || this.defaultPadding; var b = Ext.get(this.getEl()).getBox(); var ce = Ext.get(constrainTo); var s = ce.getScroll(); var c, cd = ce.dom; if(cd == document.body){ c = { x: s.left, y: s.top, width: Ext.lib.Dom.getViewWidth(), height: Ext.lib.Dom.getViewHeight()}; }else{ var xy = ce.getXY(); c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight}; } var topSpace = b.y - c.y; var leftSpace = b.x - c.x; this.resetConstraints(); this.setXConstraint(leftSpace - (pad.left||0), c.width - leftSpace - b.width - (pad.right||0), this.xTickSize ); this.setYConstraint(topSpace - (pad.top||0), c.height - topSpace - b.height - (pad.bottom||0), this.yTickSize ); }, getEl: function() { if (!this._domRef) { this._domRef = Ext.getDom(this.id); } return this._domRef; }, getDragEl: function() { return Ext.getDom(this.dragElId); }, init: function(id, sGroup, config) { this.initTarget(id, sGroup, config); Event.on(this.id, "mousedown", this.handleMouseDown, this); }, initTarget: function(id, sGroup, config) { this.config = config || {}; this.DDM = Ext.dd.DDM; this.groups = {}; if (typeof id !== "string") { id = Ext.id(id); } this.id = id; this.addToGroup((sGroup) ? sGroup : "default"); this.handleElId = id; this.setDragElId(id); this.invalidHandleTypes = { A: "A" }; this.invalidHandleIds = {}; this.invalidHandleClasses = []; this.applyConfig(); this.handleOnAvailable(); }, applyConfig: function() { this.padding = this.config.padding || [0, 0, 0, 0]; this.isTarget = (this.config.isTarget !== false); this.maintainOffset = (this.config.maintainOffset); this.primaryButtonOnly = (this.config.primaryButtonOnly !== false); }, handleOnAvailable: function() { this.available = true; this.resetConstraints(); this.onAvailable(); }, setPadding: function(iTop, iRight, iBot, iLeft) { if (!iRight && 0 !== iRight) { this.padding = [iTop, iTop, iTop, iTop]; } else if (!iBot && 0 !== iBot) { this.padding = [iTop, iRight, iTop, iRight]; } else { this.padding = [iTop, iRight, iBot, iLeft]; } }, setInitPosition: function(diffX, diffY) { var el = this.getEl(); if (!this.DDM.verifyEl(el)) { return; } var dx = diffX || 0; var dy = diffY || 0; var p = Dom.getXY( el ); this.initPageX = p[0] - dx; this.initPageY = p[1] - dy; this.lastPageX = p[0]; this.lastPageY = p[1]; this.setStartPosition(p); }, setStartPosition: function(pos) { var p = pos || Dom.getXY( this.getEl() ); this.deltaSetXY = null; this.startPageX = p[0]; this.startPageY = p[1]; }, addToGroup: function(sGroup) { this.groups[sGroup] = true; this.DDM.regDragDrop(this, sGroup); }, removeFromGroup: function(sGroup) { if (this.groups[sGroup]) { delete this.groups[sGroup]; } this.DDM.removeDDFromGroup(this, sGroup); }, setDragElId: function(id) { this.dragElId = id; }, setHandleElId: function(id) { if (typeof id !== "string") { id = Ext.id(id); } this.handleElId = id; this.DDM.regHandle(this.id, id); }, setOuterHandleElId: function(id) { if (typeof id !== "string") { id = Ext.id(id); } Event.on(id, "mousedown", this.handleMouseDown, this); this.setHandleElId(id); this.hasOuterHandles = true; }, unreg: function() { Event.un(this.id, "mousedown", this.handleMouseDown); this._domRef = null; this.DDM._remove(this); }, destroy : function(){ this.unreg(); }, isLocked: function() { return (this.DDM.isLocked() || this.locked); }, handleMouseDown: function(e, oDD){ if (this.primaryButtonOnly && e.button != 0) { return; } if (this.isLocked()) { return; } this.DDM.refreshCache(this.groups); var pt = new Ext.lib.Point(Ext.lib.Event.getPageX(e), Ext.lib.Event.getPageY(e)); if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) { } else { if (this.clickValidator(e)) { this.setStartPosition(); this.b4MouseDown(e); this.onMouseDown(e); this.DDM.handleMouseDown(e, this); this.DDM.stopEvent(e); } else { } } }, clickValidator: function(e) { var target = e.getTarget(); return ( this.isValidHandleChild(target) && (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) ); }, addInvalidHandleType: function(tagName) { var type = tagName.toUpperCase(); this.invalidHandleTypes[type] = type; }, addInvalidHandleId: function(id) { if (typeof id !== "string") { id = Ext.id(id); } this.invalidHandleIds[id] = id; }, addInvalidHandleClass: function(cssClass) { this.invalidHandleClasses.push(cssClass); }, removeInvalidHandleType: function(tagName) { var type = tagName.toUpperCase(); delete this.invalidHandleTypes[type]; }, removeInvalidHandleId: function(id) { if (typeof id !== "string") { id = Ext.id(id); } delete this.invalidHandleIds[id]; }, removeInvalidHandleClass: function(cssClass) { for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) { if (this.invalidHandleClasses[i] == cssClass) { delete this.invalidHandleClasses[i]; } } }, isValidHandleChild: function(node) { var valid = true; var nodeName; try { nodeName = node.nodeName.toUpperCase(); } catch(e) { nodeName = node.nodeName; } valid = valid && !this.invalidHandleTypes[nodeName]; valid = valid && !this.invalidHandleIds[node.id]; for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) { valid = !Dom.hasClass(node, this.invalidHandleClasses[i]); } return valid; }, setXTicks: function(iStartX, iTickSize) { this.xTicks = []; this.xTickSize = iTickSize; var tickMap = {}; for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) { if (!tickMap[i]) { this.xTicks[this.xTicks.length] = i; tickMap[i] = true; } } for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) { if (!tickMap[i]) { this.xTicks[this.xTicks.length] = i; tickMap[i] = true; } } this.xTicks.sort(this.DDM.numericSort) ; }, setYTicks: function(iStartY, iTickSize) { this.yTicks = []; this.yTickSize = iTickSize; var tickMap = {}; for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) { if (!tickMap[i]) { this.yTicks[this.yTicks.length] = i; tickMap[i] = true; } } for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) { if (!tickMap[i]) { this.yTicks[this.yTicks.length] = i; tickMap[i] = true; } } this.yTicks.sort(this.DDM.numericSort) ; }, setXConstraint: function(iLeft, iRight, iTickSize) { this.leftConstraint = iLeft; this.rightConstraint = iRight; this.minX = this.initPageX - iLeft; this.maxX = this.initPageX + iRight; if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); } this.constrainX = true; }, clearConstraints: function() { this.constrainX = false; this.constrainY = false; this.clearTicks(); }, clearTicks: function() { this.xTicks = null; this.yTicks = null; this.xTickSize = 0; this.yTickSize = 0; }, setYConstraint: function(iUp, iDown, iTickSize) { this.topConstraint = iUp; this.bottomConstraint = iDown; this.minY = this.initPageY - iUp; this.maxY = this.initPageY + iDown; if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); } this.constrainY = true; }, resetConstraints: function() { if (this.initPageX || this.initPageX === 0) { var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0; var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0; this.setInitPosition(dx, dy); } else { this.setInitPosition(); } if (this.constrainX) { this.setXConstraint( this.leftConstraint, this.rightConstraint, this.xTickSize ); } if (this.constrainY) { this.setYConstraint( this.topConstraint, this.bottomConstraint, this.yTickSize ); } }, getTick: function(val, tickArray) { if (!tickArray) { return val; } else if (tickArray[0] >= val) { return tickArray[0]; } else { for (var i=0, len=tickArray.length; i<len; ++i) { var next = i + 1; if (tickArray[next] && tickArray[next] >= val) { var diff1 = val - tickArray[i]; var diff2 = tickArray[next] - val; return (diff2 > diff1) ? tickArray[i] : tickArray[next]; } } return tickArray[tickArray.length - 1]; } }, toString: function() { return ("DragDrop " + this.id); } }; })(); if (!Ext.dd.DragDropMgr) { Ext.dd.DragDropMgr = function() { var Event = Ext.EventManager; return { ids: {}, handleIds: {}, dragCurrent: null, dragOvers: {}, deltaX: 0, deltaY: 0, preventDefault: true, stopPropagation: true, initalized: false, locked: false, init: function() { this.initialized = true; }, POINT: 0, INTERSECT: 1, mode: 0, _execOnAll: function(sMethod, args) { for (var i in this.ids) { for (var j in this.ids[i]) { var oDD = this.ids[i][j]; if (! this.isTypeOfDD(oDD)) { continue; } oDD[sMethod].apply(oDD, args); } } }, _onLoad: function() { this.init(); Event.on(document, "mouseup", this.handleMouseUp, this, true); Event.on(document, "mousemove", this.handleMouseMove, this, true); Event.on(window, "unload", this._onUnload, this, true); Event.on(window, "resize", this._onResize, this, true); }, _onResize: function(e) { this._execOnAll("resetConstraints", []); }, lock: function() { this.locked = true; }, unlock: function() { this.locked = false; }, isLocked: function() { return this.locked; }, locationCache: {}, useCache: true, clickPixelThresh: 3, clickTimeThresh: 350, dragThreshMet: false, clickTimeout: null, startX: 0, startY: 0, regDragDrop: function(oDD, sGroup) { if (!this.initialized) { this.init(); } if (!this.ids[sGroup]) { this.ids[sGroup] = {}; } this.ids[sGroup][oDD.id] = oDD; }, removeDDFromGroup: function(oDD, sGroup) { if (!this.ids[sGroup]) { this.ids[sGroup] = {}; } var obj = this.ids[sGroup]; if (obj && obj[oDD.id]) { delete obj[oDD.id]; } }, _remove: function(oDD) { for (var g in oDD.groups) { if (g && this.ids[g][oDD.id]) { delete this.ids[g][oDD.id]; } } delete this.handleIds[oDD.id]; }, regHandle: function(sDDId, sHandleId) { if (!this.handleIds[sDDId]) { this.handleIds[sDDId] = {}; } this.handleIds[sDDId][sHandleId] = sHandleId; }, isDragDrop: function(id) { return ( this.getDDById(id) ) ? true : false; }, getRelated: function(p_oDD, bTargetsOnly) { var oDDs = []; for (var i in p_oDD.groups) { for (j in this.ids[i]) { var dd = this.ids[i][j]; if (! this.isTypeOfDD(dd)) { continue; } if (!bTargetsOnly || dd.isTarget) { oDDs[oDDs.length] = dd; } } } return oDDs; }, isLegalTarget: function (oDD, oTargetDD) { var targets = this.getRelated(oDD, true); for (var i=0, len=targets.length;i<len;++i) { if (targets[i].id == oTargetDD.id) { return true; } } return false; }, isTypeOfDD: function (oDD) { return (oDD && oDD.__ygDragDrop); }, isHandle: function(sDDId, sHandleId) { return ( this.handleIds[sDDId] && this.handleIds[sDDId][sHandleId] ); }, getDDById: function(id) { for (var i in this.ids) { if (this.ids[i][id]) { return this.ids[i][id]; } } return null; }, handleMouseDown: function(e, oDD) { if(Ext.QuickTips){ Ext.QuickTips.disable(); } this.currentTarget = e.getTarget(); this.dragCurrent = oDD; var el = oDD.getEl(); this.startX = e.getPageX(); this.startY = e.getPageY(); this.deltaX = this.startX - el.offsetLeft; this.deltaY = this.startY - el.offsetTop; this.dragThreshMet = false; this.clickTimeout = setTimeout( function() { var DDM = Ext.dd.DDM; DDM.startDrag(DDM.startX, DDM.startY); }, this.clickTimeThresh ); }, startDrag: function(x, y) { clearTimeout(this.clickTimeout); if (this.dragCurrent) { this.dragCurrent.b4StartDrag(x, y); this.dragCurrent.startDrag(x, y); } this.dragThreshMet = true; }, handleMouseUp: function(e) { if(Ext.QuickTips){ Ext.QuickTips.enable(); } if (! this.dragCurrent) { return; } clearTimeout(this.clickTimeout); if (this.dragThreshMet) { this.fireEvents(e, true); } else { } this.stopDrag(e); this.stopEvent(e); }, stopEvent: function(e){ if(this.stopPropagation) { e.stopPropagation(); } if (this.preventDefault) { e.preventDefault(); } }, stopDrag: function(e) { if (this.dragCurrent) { if (this.dragThreshMet) { this.dragCurrent.b4EndDrag(e); this.dragCurrent.endDrag(e); } this.dragCurrent.onMouseUp(e); } this.dragCurrent = null; this.dragOvers = {}; }, handleMouseMove: function(e) { if (! this.dragCurrent) { return true; } if (Ext.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) { this.stopEvent(e); return this.handleMouseUp(e); } if (!this.dragThreshMet) { var diffX = Math.abs(this.startX - e.getPageX()); var diffY = Math.abs(this.startY - e.getPageY()); if (diffX > this.clickPixelThresh || diffY > this.clickPixelThresh) { this.startDrag(this.startX, this.startY); } } if (this.dragThreshMet) { this.dragCurrent.b4Drag(e); this.dragCurrent.onDrag(e); if(!this.dragCurrent.moveOnly){ this.fireEvents(e, false); } } this.stopEvent(e); return true; }, fireEvents: function(e, isDrop) { var dc = this.dragCurrent; if (!dc || dc.isLocked()) { return; } var pt = e.getPoint(); var oldOvers = []; var outEvts = []; var overEvts = []; var dropEvts = []; var enterEvts = []; for (var i in this.dragOvers) { var ddo = this.dragOvers[i]; if (! this.isTypeOfDD(ddo)) { continue; } if (! this.isOverTarget(pt, ddo, this.mode)) { outEvts.push( ddo ); } oldOvers[i] = true; delete this.dragOvers[i]; } for (var sGroup in dc.groups) { if ("string" != typeof sGroup) { continue; } for (i in this.ids[sGroup]) { var oDD = this.ids[sGroup][i]; if (! this.isTypeOfDD(oDD)) { continue; } if (oDD.isTarget && !oDD.isLocked() && oDD != dc) { if (this.isOverTarget(pt, oDD, this.mode)) { if (isDrop) { dropEvts.push( oDD ); } else { if (!oldOvers[oDD.id]) { enterEvts.push( oDD ); } else { overEvts.push( oDD ); } this.dragOvers[oDD.id] = oDD; } } } } } if (this.mode) { if (outEvts.length) { dc.b4DragOut(e, outEvts); dc.onDragOut(e, outEvts); } if (enterEvts.length) { dc.onDragEnter(e, enterEvts); } if (overEvts.length) { dc.b4DragOver(e, overEvts); dc.onDragOver(e, overEvts); } if (dropEvts.length) { dc.b4DragDrop(e, dropEvts); dc.onDragDrop(e, dropEvts); } } else { var len = 0; for (i=0, len=outEvts.length; i<len; ++i) { dc.b4DragOut(e, outEvts[i].id); dc.onDragOut(e, outEvts[i].id); } for (i=0,len=enterEvts.length; i<len; ++i) { dc.onDragEnter(e, enterEvts[i].id); } for (i=0,len=overEvts.length; i<len; ++i) { dc.b4DragOver(e, overEvts[i].id); dc.onDragOver(e, overEvts[i].id); } for (i=0, len=dropEvts.length; i<len; ++i) { dc.b4DragDrop(e, dropEvts[i].id); dc.onDragDrop(e, dropEvts[i].id); } } if (isDrop && !dropEvts.length) { dc.onInvalidDrop(e); } }, getBestMatch: function(dds) { var winner = null; var len = dds.length; if (len == 1) { winner = dds[0]; } else { for (var i=0; i<len; ++i) { var dd = dds[i]; if (dd.cursorIsOver) { winner = dd; break; } else { if (!winner || winner.overlap.getArea() < dd.overlap.getArea()) { winner = dd; } } } } return winner; }, refreshCache: function(groups) { for (var sGroup in groups) { if ("string" != typeof sGroup) { continue; } for (var i in this.ids[sGroup]) { var oDD = this.ids[sGroup][i]; if (this.isTypeOfDD(oDD)) { var loc = this.getLocation(oDD); if (loc) { this.locationCache[oDD.id] = loc; } else { delete this.locationCache[oDD.id]; } } } } }, verifyEl: function(el) { if (el) { var parent; if(Ext.isIE){ try{ parent = el.offsetParent; }catch(e){} }else{ parent = el.offsetParent; } if (parent) { return true; } } return false; }, getLocation: function(oDD) { if (! this.isTypeOfDD(oDD)) { return null; } var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l; try { pos= Ext.lib.Dom.getXY(el); } catch (e) { } if (!pos) { return null; } x1 = pos[0]; x2 = x1 + el.offsetWidth; y1 = pos[1]; y2 = y1 + el.offsetHeight; t = y1 - oDD.padding[0]; r = x2 + oDD.padding[1]; b = y2 + oDD.padding[2]; l = x1 - oDD.padding[3]; return new Ext.lib.Region( t, r, b, l ); }, isOverTarget: function(pt, oTarget, intersect) { var loc = this.locationCache[oTarget.id]; if (!loc || !this.useCache) { loc = this.getLocation(oTarget); this.locationCache[oTarget.id] = loc; } if (!loc) { return false; } oTarget.cursorIsOver = loc.contains( pt ); var dc = this.dragCurrent; if (!dc || !dc.getTargetCoord || (!intersect && !dc.constrainX && !dc.constrainY)) { return oTarget.cursorIsOver; } oTarget.overlap = null; var pos = dc.getTargetCoord(pt.x, pt.y); var el = dc.getDragEl(); var curRegion = new Ext.lib.Region( pos.y, pos.x + el.offsetWidth, pos.y + el.offsetHeight, pos.x ); var overlap = curRegion.intersect(loc); if (overlap) { oTarget.overlap = overlap; return (intersect) ? true : oTarget.cursorIsOver; } else { return false; } }, _onUnload: function(e, me) { Ext.dd.DragDropMgr.unregAll(); }, unregAll: function() { if (this.dragCurrent) { this.stopDrag(); this.dragCurrent = null; } this._execOnAll("unreg", []); for (var i in this.elementCache) { delete this.elementCache[i]; } this.elementCache = {}; this.ids = {}; }, elementCache: {}, getElWrapper: function(id) { var oWrapper = this.elementCache[id]; if (!oWrapper || !oWrapper.el) { oWrapper = this.elementCache[id] = new this.ElementWrapper(Ext.getDom(id)); } return oWrapper; }, getElement: function(id) { return Ext.getDom(id); }, getCss: function(id) { var el = Ext.getDom(id); return (el) ? el.style : null; }, ElementWrapper: function(el) { this.el = el || null; this.id = this.el && el.id; this.css = this.el && el.style; }, getPosX: function(el) { return Ext.lib.Dom.getX(el); }, getPosY: function(el) { return Ext.lib.Dom.getY(el); }, swapNode: function(n1, n2) { if (n1.swapNode) { n1.swapNode(n2); } else { var p = n2.parentNode; var s = n2.nextSibling; if (s == n1) { p.insertBefore(n1, n2); } else if (n2 == n1.nextSibling) { p.insertBefore(n2, n1); } else { n1.parentNode.replaceChild(n2, n1); p.insertBefore(n1, s); } } }, getScroll: function () { var t, l, dde=document.documentElement, db=document.body; if (dde && (dde.scrollTop || dde.scrollLeft)) { t = dde.scrollTop; l = dde.scrollLeft; } else if (db) { t = db.scrollTop; l = db.scrollLeft; } else { } return { top: t, left: l }; }, getStyle: function(el, styleProp) { return Ext.fly(el).getStyle(styleProp); }, getScrollTop: function () { return this.getScroll().top; }, getScrollLeft: function () { return this.getScroll().left; }, moveToEl: function (moveEl, targetEl) { var aCoord = Ext.lib.Dom.getXY(targetEl); Ext.lib.Dom.setXY(moveEl, aCoord); }, numericSort: function(a, b) { return (a - b); }, _timeoutCount: 0, _addListeners: function() { var DDM = Ext.dd.DDM; if ( Ext.lib.Event && document ) { DDM._onLoad(); } else { if (DDM._timeoutCount > 2000) { } else { setTimeout(DDM._addListeners, 10); if (document && document.body) { DDM._timeoutCount += 1; } } } }, handleWasClicked: function(node, id) { if (this.isHandle(id, node.id)) { return true; } else { var p = node.parentNode; while (p) { if (this.isHandle(id, p.id)) { return true; } else { p = p.parentNode; } } } return false; } }; }(); Ext.dd.DDM = Ext.dd.DragDropMgr; Ext.dd.DDM._addListeners(); } Ext.dd.DD = function(id, sGroup, config) { if (id) { this.init(id, sGroup, config); } }; Ext.extend(Ext.dd.DD, Ext.dd.DragDrop, { scroll: true, autoOffset: function(iPageX, iPageY) { var x = iPageX - this.startPageX; var y = iPageY - this.startPageY; this.setDelta(x, y); }, setDelta: function(iDeltaX, iDeltaY) { this.deltaX = iDeltaX; this.deltaY = iDeltaY; }, setDragElPos: function(iPageX, iPageY) { var el = this.getDragEl(); this.alignElWithMouse(el, iPageX, iPageY); }, alignElWithMouse: function(el, iPageX, iPageY) { var oCoord = this.getTargetCoord(iPageX, iPageY); var fly = el.dom ? el : Ext.fly(el, '_dd'); if (!this.deltaSetXY) { var aCoord = [oCoord.x, oCoord.y]; fly.setXY(aCoord); var newLeft = fly.getLeft(true); var newTop = fly.getTop(true); this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ]; } else { fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]); } this.cachePosition(oCoord.x, oCoord.y); this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth); return oCoord; }, cachePosition: function(iPageX, iPageY) { if (iPageX) { this.lastPageX = iPageX; this.lastPageY = iPageY; } else { var aCoord = Ext.lib.Dom.getXY(this.getEl()); this.lastPageX = aCoord[0]; this.lastPageY = aCoord[1]; } }, autoScroll: function(x, y, h, w) { if (this.scroll) { var clientH = Ext.lib.Dom.getViewHeight(); var clientW = Ext.lib.Dom.getViewWidth(); var st = this.DDM.getScrollTop(); var sl = this.DDM.getScrollLeft(); var bot = h + y; var right = w + x; var toBot = (clientH + st - y - this.deltaY); var toRight = (clientW + sl - x - this.deltaX); var thresh = 40; var scrAmt = (document.all) ? 80 : 30; if ( bot > clientH && toBot < thresh ) { window.scrollTo(sl, st + scrAmt); } if ( y < st && st > 0 && y - st < thresh ) { window.scrollTo(sl, st - scrAmt); } if ( right > clientW && toRight < thresh ) { window.scrollTo(sl + scrAmt, st); } if ( x < sl && sl > 0 && x - sl < thresh ) { window.scrollTo(sl - scrAmt, st); } } }, getTargetCoord: function(iPageX, iPageY) { var x = iPageX - this.deltaX; var y = iPageY - this.deltaY; if (this.constrainX) { if (x < this.minX) { x = this.minX; } if (x > this.maxX) { x = this.maxX; } } if (this.constrainY) { if (y < this.minY) { y = this.minY; } if (y > this.maxY) { y = this.maxY; } } x = this.getTick(x, this.xTicks); y = this.getTick(y, this.yTicks); return {x:x, y:y}; }, applyConfig: function() { Ext.dd.DD.superclass.applyConfig.call(this); this.scroll = (this.config.scroll !== false); }, b4MouseDown: function(e) { this.autoOffset(e.getPageX(), e.getPageY()); }, b4Drag: function(e) { this.setDragElPos(e.getPageX(), e.getPageY()); }, toString: function() { return ("DD " + this.id); } }); Ext.dd.DDProxy = function(id, sGroup, config) { if (id) { this.init(id, sGroup, config); this.initFrame(); } }; Ext.dd.DDProxy.dragElId = "ygddfdiv"; Ext.extend(Ext.dd.DDProxy, Ext.dd.DD, { resizeFrame: true, centerFrame: false, createFrame: function() { var self = this; var body = document.body; if (!body || !body.firstChild) { setTimeout( function() { self.createFrame(); }, 50 ); return; } var div = this.getDragEl(); if (!div) { div = document.createElement("div"); div.id = this.dragElId; var s = div.style; s.position = "absolute"; s.visibility = "hidden"; s.cursor = "move"; s.border = "2px solid #aaa"; s.zIndex = 999; body.insertBefore(div, body.firstChild); } }, initFrame: function() { this.createFrame(); }, applyConfig: function() { Ext.dd.DDProxy.superclass.applyConfig.call(this); this.resizeFrame = (this.config.resizeFrame !== false); this.centerFrame = (this.config.centerFrame); this.setDragElId(this.config.dragElId || Ext.dd.DDProxy.dragElId); }, showFrame: function(iPageX, iPageY) { var el = this.getEl(); var dragEl = this.getDragEl(); var s = dragEl.style; this._resizeProxy(); if (this.centerFrame) { this.setDelta( Math.round(parseInt(s.width, 10)/2), Math.round(parseInt(s.height, 10)/2) ); } this.setDragElPos(iPageX, iPageY); Ext.fly(dragEl).show(); }, _resizeProxy: function() { if (this.resizeFrame) { var el = this.getEl(); Ext.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight); } }, b4MouseDown: function(e) { var x = e.getPageX(); var y = e.getPageY(); this.autoOffset(x, y); this.setDragElPos(x, y); }, b4StartDrag: function(x, y) { this.showFrame(x, y); }, b4EndDrag: function(e) { Ext.fly(this.getDragEl()).hide(); }, endDrag: function(e) { var lel = this.getEl(); var del = this.getDragEl(); del.style.visibility = ""; this.beforeMove(); lel.style.visibility = "hidden"; Ext.dd.DDM.moveToEl(lel, del); del.style.visibility = "hidden"; lel.style.visibility = ""; this.afterDrag(); }, beforeMove : function(){ }, afterDrag : function(){ }, toString: function() { return ("DDProxy " + this.id); } }); Ext.dd.DDTarget = function(id, sGroup, config) { if (id) { this.initTarget(id, sGroup, config); } }; Ext.extend(Ext.dd.DDTarget, Ext.dd.DragDrop, { toString: function() { return ("DDTarget " + this.id); } }); Ext.dd.DragTracker = function(config){ Ext.apply(this, config); this.addEvents( 'mousedown', 'mouseup', 'mousemove', 'dragstart', 'dragend', 'drag' ); this.dragRegion = new Ext.lib.Region(0,0,0,0); if(this.el){ this.initEl(this.el); } } Ext.extend(Ext.dd.DragTracker, Ext.util.Observable, { active: false, tolerance: 5, autoStart: false, initEl: function(el){ this.el = Ext.get(el); el.on('mousedown', this.onMouseDown, this, this.delegate ? {delegate: this.delegate} : undefined); }, destroy : function(){ this.el.un('mousedown', this.onMouseDown, this); }, onMouseDown: function(e, target){ if(this.fireEvent('mousedown', this, e) !== false && this.onBeforeStart(e) !== false){ this.startXY = this.lastXY = e.getXY(); this.dragTarget = this.delegate ? target : this.el.dom; e.preventDefault(); var doc = Ext.getDoc(); doc.on('mouseup', this.onMouseUp, this); doc.on('mousemove', this.onMouseMove, this); doc.on('selectstart', this.stopSelect, this); if(this.autoStart){ this.timer = this.triggerStart.defer(this.autoStart === true ? 1000 : this.autoStart, this); } } }, onMouseMove: function(e, target){ e.preventDefault(); var xy = e.getXY(), s = this.startXY; this.lastXY = xy; if(!this.active){ if(Math.abs(s[0]-xy[0]) > this.tolerance || Math.abs(s[1]-xy[1]) > this.tolerance){ this.triggerStart(); }else{ return; } } this.fireEvent('mousemove', this, e); this.onDrag(e); this.fireEvent('drag', this, e); }, onMouseUp: function(e){ var doc = Ext.getDoc(); doc.un('mousemove', this.onMouseMove, this); doc.un('mouseup', this.onMouseUp, this); doc.un('selectstart', this.stopSelect, this); e.preventDefault(); this.clearStart(); this.active = false; delete this.elRegion; this.fireEvent('mouseup', this, e); this.onEnd(e); this.fireEvent('dragend', this, e); }, triggerStart: function(isTimer){ this.clearStart(); this.active = true; this.onStart(this.startXY); this.fireEvent('dragstart', this, this.startXY); }, clearStart : function(){ if(this.timer){ clearTimeout(this.timer); delete this.timer; } }, stopSelect : function(e){ e.stopEvent(); return false; }, onBeforeStart : function(e){ }, onStart : function(xy){ }, onDrag : function(e){ }, onEnd : function(e){ }, getDragTarget : function(){ return this.dragTarget; }, getDragCt : function(){ return this.el; }, getXY : function(constrain){ return constrain ? this.constrainModes[constrain].call(this, this.lastXY) : this.lastXY; }, getOffset : function(constrain){ var xy = this.getXY(constrain); var s = this.startXY; return [s[0]-xy[0], s[1]-xy[1]]; }, constrainModes: { 'point' : function(xy){ if(!this.elRegion){ this.elRegion = this.getDragCt().getRegion(); } var dr = this.dragRegion; dr.left = xy[0]; dr.top = xy[1]; dr.right = xy[0]; dr.bottom = xy[1]; dr.constrainTo(this.elRegion); return [dr.left, dr.top]; } } }); Ext.dd.ScrollManager = function(){ var ddm = Ext.dd.DragDropMgr; var els = {}; var dragEl = null; var proc = {}; var onStop = function(e){ dragEl = null; clearProc(); }; var triggerRefresh = function(){ if(ddm.dragCurrent){ ddm.refreshCache(ddm.dragCurrent.groups); } }; var doScroll = function(){ if(ddm.dragCurrent){ var dds = Ext.dd.ScrollManager; var inc = proc.el.ddScrollConfig ? proc.el.ddScrollConfig.increment : dds.increment; if(!dds.animate){ if(proc.el.scroll(proc.dir, inc)){ triggerRefresh(); } }else{ proc.el.scroll(proc.dir, inc, true, dds.animDuration, triggerRefresh); } } }; var clearProc = function(){ if(proc.id){ clearInterval(proc.id); } proc.id = 0; proc.el = null; proc.dir = ""; }; var startProc = function(el, dir){ clearProc(); proc.el = el; proc.dir = dir; proc.id = setInterval(doScroll, Ext.dd.ScrollManager.frequency); }; var onFire = function(e, isDrop){ if(isDrop || !ddm.dragCurrent){ return; } var dds = Ext.dd.ScrollManager; if(!dragEl || dragEl != ddm.dragCurrent){ dragEl = ddm.dragCurrent; dds.refreshCache(); } var xy = Ext.lib.Event.getXY(e); var pt = new Ext.lib.Point(xy[0], xy[1]); for(var id in els){ var el = els[id], r = el._region; var c = el.ddScrollConfig ? el.ddScrollConfig : dds; if(r && r.contains(pt) && el.isScrollable()){ if(r.bottom - pt.y <= c.vthresh){ if(proc.el != el){ startProc(el, "down"); } return; }else if(r.right - pt.x <= c.hthresh){ if(proc.el != el){ startProc(el, "left"); } return; }else if(pt.y - r.top <= c.vthresh){ if(proc.el != el){ startProc(el, "up"); } return; }else if(pt.x - r.left <= c.hthresh){ if(proc.el != el){ startProc(el, "right"); } return; } } } clearProc(); }; ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm); ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm); return { register : function(el){ if(Ext.isArray(el)){ for(var i = 0, len = el.length; i < len; i++) { this.register(el[i]); } }else{ el = Ext.get(el); els[el.id] = el; } }, unregister : function(el){ if(Ext.isArray(el)){ for(var i = 0, len = el.length; i < len; i++) { this.unregister(el[i]); } }else{ el = Ext.get(el); delete els[el.id]; } }, vthresh : 25, hthresh : 25, increment : 100, frequency : 500, animate: true, animDuration: .4, refreshCache : function(){ for(var id in els){ if(typeof els[id] == 'object'){ els[id]._region = els[id].getRegion(); } } } }; }(); Ext.dd.Registry = function(){ var elements = {}; var handles = {}; var autoIdSeed = 0; var getId = function(el, autogen){ if(typeof el == "string"){ return el; } var id = el.id; if(!id && autogen !== false){ id = "extdd-" + (++autoIdSeed); el.id = id; } return id; }; return { register : function(el, data){ data = data || {}; if(typeof el == "string"){ el = document.getElementById(el); } data.ddel = el; elements[getId(el)] = data; if(data.isHandle !== false){ handles[data.ddel.id] = data; } if(data.handles){ var hs = data.handles; for(var i = 0, len = hs.length; i < len; i++){ handles[getId(hs[i])] = data; } } }, unregister : function(el){ var id = getId(el, false); var data = elements[id]; if(data){ delete elements[id]; if(data.handles){ var hs = data.handles; for(var i = 0, len = hs.length; i < len; i++){ delete handles[getId(hs[i], false)]; } } } }, getHandle : function(id){ if(typeof id != "string"){ id = id.id; } return handles[id]; }, getHandleFromEvent : function(e){ var t = Ext.lib.Event.getTarget(e); return t ? handles[t.id] : null; }, getTarget : function(id){ if(typeof id != "string"){ id = id.id; } return elements[id]; }, getTargetFromEvent : function(e){ var t = Ext.lib.Event.getTarget(e); return t ? elements[t.id] || handles[t.id] : null; } }; }(); Ext.dd.StatusProxy = function(config){ Ext.apply(this, config); this.id = this.id || Ext.id(); this.el = new Ext.Layer({ dh: { id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [ {tag: "div", cls: "x-dd-drop-icon"}, {tag: "div", cls: "x-dd-drag-ghost"} ] }, shadow: !config || config.shadow !== false }); this.ghost = Ext.get(this.el.dom.childNodes[1]); this.dropStatus = this.dropNotAllowed; }; Ext.dd.StatusProxy.prototype = { dropAllowed : "x-dd-drop-ok", dropNotAllowed : "x-dd-drop-nodrop", setStatus : function(cssClass){ cssClass = cssClass || this.dropNotAllowed; if(this.dropStatus != cssClass){ this.el.replaceClass(this.dropStatus, cssClass); this.dropStatus = cssClass; } }, reset : function(clearGhost){ this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed; this.dropStatus = this.dropNotAllowed; if(clearGhost){ this.ghost.update(""); } }, update : function(html){ if(typeof html == "string"){ this.ghost.update(html); }else{ this.ghost.update(""); html.style.margin = "0"; this.ghost.dom.appendChild(html); } }, getEl : function(){ return this.el; }, getGhost : function(){ return this.ghost; }, hide : function(clear){ this.el.hide(); if(clear){ this.reset(true); } }, stop : function(){ if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){ this.anim.stop(); } }, show : function(){ this.el.show(); }, sync : function(){ this.el.sync(); }, repair : function(xy, callback, scope){ this.callback = callback; this.scope = scope; if(xy && this.animRepair !== false){ this.el.addClass("x-dd-drag-repair"); this.el.hideUnders(true); this.anim = this.el.shift({ duration: this.repairDuration || .5, easing: 'easeOut', xy: xy, stopFx: true, callback: this.afterRepair, scope: this }); }else{ this.afterRepair(); } }, afterRepair : function(){ this.hide(true); if(typeof this.callback == "function"){ this.callback.call(this.scope || this); } this.callback = null; this.scope = null; } }; Ext.dd.DragSource = function(el, config){ this.el = Ext.get(el); if(!this.dragData){ this.dragData = {}; } Ext.apply(this, config); if(!this.proxy){ this.proxy = new Ext.dd.StatusProxy(); } Ext.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group, {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true}); this.dragging = false; }; Ext.extend(Ext.dd.DragSource, Ext.dd.DDProxy, { dropAllowed : "x-dd-drop-ok", dropNotAllowed : "x-dd-drop-nodrop", getDragData : function(e){ return this.dragData; }, onDragEnter : function(e, id){ var target = Ext.dd.DragDropMgr.getDDById(id); this.cachedTarget = target; if(this.beforeDragEnter(target, e, id) !== false){ if(target.isNotifyTarget){ var status = target.notifyEnter(this, e, this.dragData); this.proxy.setStatus(status); }else{ this.proxy.setStatus(this.dropAllowed); } if(this.afterDragEnter){ this.afterDragEnter(target, e, id); } } }, beforeDragEnter : function(target, e, id){ return true; }, alignElWithMouse: function() { Ext.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments); this.proxy.sync(); }, onDragOver : function(e, id){ var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id); if(this.beforeDragOver(target, e, id) !== false){ if(target.isNotifyTarget){ var status = target.notifyOver(this, e, this.dragData); this.proxy.setStatus(status); } if(this.afterDragOver){ this.afterDragOver(target, e, id); } } }, beforeDragOver : function(target, e, id){ return true; }, onDragOut : function(e, id){ var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id); if(this.beforeDragOut(target, e, id) !== false){ if(target.isNotifyTarget){ target.notifyOut(this, e, this.dragData); } this.proxy.reset(); if(this.afterDragOut){ this.afterDragOut(target, e, id); } } this.cachedTarget = null; }, beforeDragOut : function(target, e, id){ return true; }, onDragDrop : function(e, id){ var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id); if(this.beforeDragDrop(target, e, id) !== false){ if(target.isNotifyTarget){ if(target.notifyDrop(this, e, this.dragData)){ this.onValidDrop(target, e, id); }else{ this.onInvalidDrop(target, e, id); } }else{ this.onValidDrop(target, e, id); } if(this.afterDragDrop){ this.afterDragDrop(target, e, id); } } delete this.cachedTarget; }, beforeDragDrop : function(target, e, id){ return true; }, onValidDrop : function(target, e, id){ this.hideProxy(); if(this.afterValidDrop){ this.afterValidDrop(target, e, id); } }, getRepairXY : function(e, data){ return this.el.getXY(); }, onInvalidDrop : function(target, e, id){ this.beforeInvalidDrop(target, e, id); if(this.cachedTarget){ if(this.cachedTarget.isNotifyTarget){ this.cachedTarget.notifyOut(this, e, this.dragData); } this.cacheTarget = null; } this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this); if(this.afterInvalidDrop){ this.afterInvalidDrop(e, id); } }, afterRepair : function(){ if(Ext.enableFx){ this.el.highlight(this.hlColor || "c3daf9"); } this.dragging = false; }, beforeInvalidDrop : function(target, e, id){ return true; }, handleMouseDown : function(e){ if(this.dragging) { return; } var data = this.getDragData(e); if(data && this.onBeforeDrag(data, e) !== false){ this.dragData = data; this.proxy.stop(); Ext.dd.DragSource.superclass.handleMouseDown.apply(this, arguments); } }, onBeforeDrag : function(data, e){ return true; }, onStartDrag : Ext.emptyFn, startDrag : function(x, y){ this.proxy.reset(); this.dragging = true; this.proxy.update(""); this.onInitDrag(x, y); this.proxy.show(); }, onInitDrag : function(x, y){ var clone = this.el.dom.cloneNode(true); clone.id = Ext.id(); this.proxy.update(clone); this.onStartDrag(x, y); return true; }, getProxy : function(){ return this.proxy; }, hideProxy : function(){ this.proxy.hide(); this.proxy.reset(true); this.dragging = false; }, triggerCacheRefresh : function(){ Ext.dd.DDM.refreshCache(this.groups); }, b4EndDrag: function(e) { }, endDrag : function(e){ this.onEndDrag(this.dragData, e); }, onEndDrag : function(data, e){ }, autoOffset : function(x, y) { this.setDelta(-12, -20); } }); Ext.dd.DropTarget = function(el, config){ this.el = Ext.get(el); Ext.apply(this, config); if(this.containerScroll){ Ext.dd.ScrollManager.register(this.el); } Ext.dd.DropTarget.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group, {isTarget: true}); }; Ext.extend(Ext.dd.DropTarget, Ext.dd.DDTarget, { dropAllowed : "x-dd-drop-ok", dropNotAllowed : "x-dd-drop-nodrop", isTarget : true, isNotifyTarget : true, notifyEnter : function(dd, e, data){ if(this.overClass){ this.el.addClass(this.overClass); } return this.dropAllowed; }, notifyOver : function(dd, e, data){ return this.dropAllowed; }, notifyOut : function(dd, e, data){ if(this.overClass){ this.el.removeClass(this.overClass); } }, notifyDrop : function(dd, e, data){ return false; } }); Ext.dd.DragZone = function(el, config){ Ext.dd.DragZone.superclass.constructor.call(this, el, config); if(this.containerScroll){ Ext.dd.ScrollManager.register(this.el); } }; Ext.extend(Ext.dd.DragZone, Ext.dd.DragSource, { getDragData : function(e){ return Ext.dd.Registry.getHandleFromEvent(e); }, onInitDrag : function(x, y){ this.proxy.update(this.dragData.ddel.cloneNode(true)); this.onStartDrag(x, y); return true; }, afterRepair : function(){ if(Ext.enableFx){ Ext.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9"); } this.dragging = false; }, getRepairXY : function(e){ return Ext.Element.fly(this.dragData.ddel).getXY(); } }); Ext.dd.DropZone = function(el, config){ Ext.dd.DropZone.superclass.constructor.call(this, el, config); }; Ext.extend(Ext.dd.DropZone, Ext.dd.DropTarget, { getTargetFromEvent : function(e){ return Ext.dd.Registry.getTargetFromEvent(e); }, onNodeEnter : function(n, dd, e, data){ }, onNodeOver : function(n, dd, e, data){ return this.dropAllowed; }, onNodeOut : function(n, dd, e, data){ }, onNodeDrop : function(n, dd, e, data){ return false; }, onContainerOver : function(dd, e, data){ return this.dropNotAllowed; }, onContainerDrop : function(dd, e, data){ return false; }, notifyEnter : function(dd, e, data){ return this.dropNotAllowed; }, notifyOver : function(dd, e, data){ var n = this.getTargetFromEvent(e); if(!n){ if(this.lastOverNode){ this.onNodeOut(this.lastOverNode, dd, e, data); this.lastOverNode = null; } return this.onContainerOver(dd, e, data); } if(this.lastOverNode != n){ if(this.lastOverNode){ this.onNodeOut(this.lastOverNode, dd, e, data); } this.onNodeEnter(n, dd, e, data); this.lastOverNode = n; } return this.onNodeOver(n, dd, e, data); }, notifyOut : function(dd, e, data){ if(this.lastOverNode){ this.onNodeOut(this.lastOverNode, dd, e, data); this.lastOverNode = null; } }, notifyDrop : function(dd, e, data){ if(this.lastOverNode){ this.onNodeOut(this.lastOverNode, dd, e, data); this.lastOverNode = null; } var n = this.getTargetFromEvent(e); return n ? this.onNodeDrop(n, dd, e, data) : this.onContainerDrop(dd, e, data); }, triggerCacheRefresh : function(){ Ext.dd.DDM.refreshCache(this.groups); } }); Ext.data.SortTypes = { none : function(s){ return s; }, stripTagsRE : /<\/?[^>]+>/gi, asText : function(s){ return String(s).replace(this.stripTagsRE, ""); }, asUCText : function(s){ return String(s).toUpperCase().replace(this.stripTagsRE, ""); }, asUCString : function(s) { return String(s).toUpperCase(); }, asDate : function(s) { if(!s){ return 0; } if(Ext.isDate(s)){ return s.getTime(); } return Date.parse(String(s)); }, asFloat : function(s) { var val = parseFloat(String(s).replace(/,/g, "")); if(isNaN(val)) val = 0; return val; }, asInt : function(s) { var val = parseInt(String(s).replace(/,/g, "")); if(isNaN(val)) val = 0; return val; } }; Ext.data.Record = function(data, id){ this.id = (id || id === 0) ? id : ++Ext.data.Record.AUTO_ID; this.data = data; }; Ext.data.Record.create = function(o){ var f = Ext.extend(Ext.data.Record, {}); var p = f.prototype; p.fields = new Ext.util.MixedCollection(false, function(field){ return field.name; }); for(var i = 0, len = o.length; i < len; i++){ p.fields.add(new Ext.data.Field(o[i])); } f.getField = function(name){ return p.fields.get(name); }; return f; }; Ext.data.Record.AUTO_ID = 1000; Ext.data.Record.EDIT = 'edit'; Ext.data.Record.REJECT = 'reject'; Ext.data.Record.COMMIT = 'commit'; Ext.data.Record.prototype = { dirty : false, editing : false, error: null, modified: null, join : function(store){ this.store = store; }, set : function(name, value){ if(String(this.data[name]) == String(value)){ return; } this.dirty = true; if(!this.modified){ this.modified = {}; } if(typeof this.modified[name] == 'undefined'){ this.modified[name] = this.data[name]; } this.data[name] = value; if(!this.editing && this.store){ this.store.afterEdit(this); } }, get : function(name){ return this.data[name]; }, beginEdit : function(){ this.editing = true; this.modified = {}; }, cancelEdit : function(){ this.editing = false; delete this.modified; }, endEdit : function(){ this.editing = false; if(this.dirty && this.store){ this.store.afterEdit(this); } }, reject : function(silent){ var m = this.modified; for(var n in m){ if(typeof m[n] != "function"){ this.data[n] = m[n]; } } this.dirty = false; delete this.modified; this.editing = false; if(this.store && silent !== true){ this.store.afterReject(this); } }, commit : function(silent){ this.dirty = false; delete this.modified; this.editing = false; if(this.store && silent !== true){ this.store.afterCommit(this); } }, getChanges : function(){ var m = this.modified, cs = {}; for(var n in m){ if(m.hasOwnProperty(n)){ cs[n] = this.data[n]; } } return cs; }, hasError : function(){ return this.error != null; }, clearError : function(){ this.error = null; }, copy : function(newId) { return new this.constructor(Ext.apply({}, this.data), newId || this.id); }, isModified : function(fieldName){ return this.modified && this.modified.hasOwnProperty(fieldName); } }; Ext.StoreMgr = Ext.apply(new Ext.util.MixedCollection(), { register : function(){ for(var i = 0, s; s = arguments[i]; i++){ this.add(s); } }, unregister : function(){ for(var i = 0, s; s = arguments[i]; i++){ this.remove(this.lookup(s)); } }, lookup : function(id){ return typeof id == "object" ? id : this.get(id); }, getKey : function(o){ return o.storeId || o.id; } }); Ext.data.Store = function(config){ this.data = new Ext.util.MixedCollection(false); this.data.getKey = function(o){ return o.id; }; this.baseParams = {}; this.paramNames = { "start" : "start", "limit" : "limit", "sort" : "sort", "dir" : "dir" }; if(config && config.data){ this.inlineData = config.data; delete config.data; } Ext.apply(this, config); if(this.url && !this.proxy){ this.proxy = new Ext.data.HttpProxy({url: this.url}); } if(this.reader){ if(!this.recordType){ this.recordType = this.reader.recordType; } if(this.reader.onMetaChange){ this.reader.onMetaChange = this.onMetaChange.createDelegate(this); } } if(this.recordType){ this.fields = this.recordType.prototype.fields; } this.modified = []; this.addEvents( 'datachanged', 'metachange', 'add', 'remove', 'update', 'clear', 'beforeload', 'load', 'loadexception' ); if(this.proxy){ this.relayEvents(this.proxy, ["loadexception"]); } this.sortToggle = {}; if(this.sortInfo){ this.setDefaultSort(this.sortInfo.field, this.sortInfo.direction); } Ext.data.Store.superclass.constructor.call(this); if(this.storeId || this.id){ Ext.StoreMgr.register(this); } if(this.inlineData){ this.loadData(this.inlineData); delete this.inlineData; }else if(this.autoLoad){ this.load.defer(10, this, [ typeof this.autoLoad == 'object' ? this.autoLoad : undefined]); } }; Ext.extend(Ext.data.Store, Ext.util.Observable, { remoteSort : false, pruneModifiedRecords : false, lastOptions : null, destroy : function(){ if(this.id){ Ext.StoreMgr.unregister(this); } this.data = null; this.purgeListeners(); }, add : function(records){ records = [].concat(records); if(records.length < 1){ return; } for(var i = 0, len = records.length; i < len; i++){ records[i].join(this); } var index = this.data.length; this.data.addAll(records); if(this.snapshot){ this.snapshot.addAll(records); } this.fireEvent("add", this, records, index); }, addSorted : function(record){ var index = this.findInsertIndex(record); this.insert(index, record); }, remove : function(record){ var index = this.data.indexOf(record); this.data.removeAt(index); if(this.pruneModifiedRecords){ this.modified.remove(record); } if(this.snapshot){ this.snapshot.remove(record); } this.fireEvent("remove", this, record, index); }, removeAll : function(){ this.data.clear(); if(this.snapshot){ this.snapshot.clear(); } if(this.pruneModifiedRecords){ this.modified = []; } this.fireEvent("clear", this); }, insert : function(index, records){ records = [].concat(records); for(var i = 0, len = records.length; i < len; i++){ this.data.insert(index, records[i]); records[i].join(this); } this.fireEvent("add", this, records, index); }, indexOf : function(record){ return this.data.indexOf(record); }, indexOfId : function(id){ return this.data.indexOfKey(id); }, getById : function(id){ return this.data.key(id); }, getAt : function(index){ return this.data.itemAt(index); }, getRange : function(start, end){ return this.data.getRange(start, end); }, storeOptions : function(o){ o = Ext.apply({}, o); delete o.callback; delete o.scope; this.lastOptions = o; }, load : function(options){ options = options || {}; if(this.fireEvent("beforeload", this, options) !== false){ this.storeOptions(options); var p = Ext.apply(options.params || {}, this.baseParams); if(this.sortInfo && this.remoteSort){ var pn = this.paramNames; p[pn["sort"]] = this.sortInfo.field; p[pn["dir"]] = this.sortInfo.direction; } this.proxy.load(p, this.reader, this.loadRecords, this, options); return true; } else { return false; } }, reload : function(options){ this.load(Ext.applyIf(options||{}, this.lastOptions)); }, loadRecords : function(o, options, success){ if(!o || success === false){ if(success !== false){ this.fireEvent("load", this, [], options); } if(options.callback){ options.callback.call(options.scope || this, [], options, false); } return; } var r = o.records, t = o.totalRecords || r.length; if(!options || options.add !== true){ if(this.pruneModifiedRecords){ this.modified = []; } for(var i = 0, len = r.length; i < len; i++){ r[i].join(this); } if(this.snapshot){ this.data = this.snapshot; delete this.snapshot; } this.data.clear(); this.data.addAll(r); this.totalLength = t; this.applySort(); this.fireEvent("datachanged", this); }else{ this.totalLength = Math.max(t, this.data.length+r.length); this.add(r); } this.fireEvent("load", this, r, options); if(options.callback){ options.callback.call(options.scope || this, r, options, true); } }, loadData : function(o, append){ var r = this.reader.readRecords(o); this.loadRecords(r, {add: append}, true); }, getCount : function(){ return this.data.length || 0; }, getTotalCount : function(){ return this.totalLength || 0; }, getSortState : function(){ return this.sortInfo; }, applySort : function(){ if(this.sortInfo && !this.remoteSort){ var s = this.sortInfo, f = s.field; this.sortData(f, s.direction); } }, sortData : function(f, direction){ direction = direction || 'ASC'; var st = this.fields.get(f).sortType; var fn = function(r1, r2){ var v1 = st(r1.data[f]), v2 = st(r2.data[f]); return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0); }; this.data.sort(direction, fn); if(this.snapshot && this.snapshot != this.data){ this.snapshot.sort(direction, fn); } }, setDefaultSort : function(field, dir){ dir = dir ? dir.toUpperCase() : "ASC"; this.sortInfo = {field: field, direction: dir}; this.sortToggle[field] = dir; }, sort : function(fieldName, dir){ var f = this.fields.get(fieldName); if(!f){ return false; } if(!dir){ if(this.sortInfo && this.sortInfo.field == f.name){ dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC"); }else{ dir = f.sortDir; } } var st = (this.sortToggle) ? this.sortToggle[f.name] : null; var si = (this.sortInfo) ? this.sortInfo : null; this.sortToggle[f.name] = dir; this.sortInfo = {field: f.name, direction: dir}; if(!this.remoteSort){ this.applySort(); this.fireEvent("datachanged", this); }else{ if (!this.load(this.lastOptions)) { if (st) { this.sortToggle[f.name] = st; } if (si) { this.sortInfo = si; } } } }, each : function(fn, scope){ this.data.each(fn, scope); }, getModifiedRecords : function(){ return this.modified; }, createFilterFn : function(property, value, anyMatch, caseSensitive){ if(Ext.isEmpty(value, false)){ return false; } value = this.data.createValueMatcher(value, anyMatch, caseSensitive); return function(r){ return value.test(r.data[property]); }; }, sum : function(property, start, end){ var rs = this.data.items, v = 0; start = start || 0; end = (end || end === 0) ? end : rs.length-1; for(var i = start; i <= end; i++){ v += (rs[i].data[property] || 0); } return v; }, filter : function(property, value, anyMatch, caseSensitive){ var fn = this.createFilterFn(property, value, anyMatch, caseSensitive); return fn ? this.filterBy(fn) : this.clearFilter(); }, filterBy : function(fn, scope){ this.snapshot = this.snapshot || this.data; this.data = this.queryBy(fn, scope||this); this.fireEvent("datachanged", this); }, query : function(property, value, anyMatch, caseSensitive){ var fn = this.createFilterFn(property, value, anyMatch, caseSensitive); return fn ? this.queryBy(fn) : this.data.clone(); }, queryBy : function(fn, scope){ var data = this.snapshot || this.data; return data.filterBy(fn, scope||this); }, find : function(property, value, start, anyMatch, caseSensitive){ var fn = this.createFilterFn(property, value, anyMatch, caseSensitive); return fn ? this.data.findIndexBy(fn, null, start) : -1; }, findBy : function(fn, scope, start){ return this.data.findIndexBy(fn, scope, start); }, collect : function(dataIndex, allowNull, bypassFilter){ var d = (bypassFilter === true && this.snapshot) ? this.snapshot.items : this.data.items; var v, sv, r = [], l = {}; for(var i = 0, len = d.length; i < len; i++){ v = d[i].data[dataIndex]; sv = String(v); if((allowNull || !Ext.isEmpty(v)) && !l[sv]){ l[sv] = true; r[r.length] = v; } } return r; }, clearFilter : function(suppressEvent){ if(this.isFiltered()){ this.data = this.snapshot; delete this.snapshot; if(suppressEvent !== true){ this.fireEvent("datachanged", this); } } }, isFiltered : function(){ return this.snapshot && this.snapshot != this.data; }, afterEdit : function(record){ if(this.modified.indexOf(record) == -1){ this.modified.push(record); } this.fireEvent("update", this, record, Ext.data.Record.EDIT); }, afterReject : function(record){ this.modified.remove(record); this.fireEvent("update", this, record, Ext.data.Record.REJECT); }, afterCommit : function(record){ this.modified.remove(record); this.fireEvent("update", this, record, Ext.data.Record.COMMIT); }, commitChanges : function(){ var m = this.modified.slice(0); this.modified = []; for(var i = 0, len = m.length; i < len; i++){ m[i].commit(); } }, rejectChanges : function(){ var m = this.modified.slice(0); this.modified = []; for(var i = 0, len = m.length; i < len; i++){ m[i].reject(); } }, onMetaChange : function(meta, rtype, o){ this.recordType = rtype; this.fields = rtype.prototype.fields; delete this.snapshot; this.sortInfo = meta.sortInfo; this.modified = []; this.fireEvent('metachange', this, this.reader.meta); }, findInsertIndex : function(record){ this.suspendEvents(); var data = this.data.clone(); this.data.add(record); this.applySort(); var index = this.data.indexOf(record); this.data = data; this.resumeEvents(); return index; } }); Ext.data.SimpleStore = function(config){ Ext.data.SimpleStore.superclass.constructor.call(this, Ext.apply(config, { reader: new Ext.data.ArrayReader({ id: config.id }, Ext.data.Record.create(config.fields) ) })); }; Ext.extend(Ext.data.SimpleStore, Ext.data.Store, { loadData : function(data, append){ if(this.expandData === true){ var r = []; for(var i = 0, len = data.length; i < len; i++){ r[r.length] = [data[i]]; } data = r; } Ext.data.SimpleStore.superclass.loadData.call(this, data, append); } }); Ext.data.JsonStore = function(c){ Ext.data.JsonStore.superclass.constructor.call(this, Ext.apply(c, { proxy: !c.data ? new Ext.data.HttpProxy({url: c.url}) : undefined, reader: new Ext.data.JsonReader(c, c.fields) })); }; Ext.extend(Ext.data.JsonStore, Ext.data.Store); Ext.data.Field = function(config){ if(typeof config == "string"){ config = {name: config}; } Ext.apply(this, config); if(!this.type){ this.type = "auto"; } var st = Ext.data.SortTypes; if(typeof this.sortType == "string"){ this.sortType = st[this.sortType]; } if(!this.sortType){ switch(this.type){ case "string": this.sortType = st.asUCString; break; case "date": this.sortType = st.asDate; break; default: this.sortType = st.none; } } var stripRe = /[\$,%]/g; if(!this.convert){ var cv, dateFormat = this.dateFormat; switch(this.type){ case "": case "auto": case undefined: cv = function(v){ return v; }; break; case "string": cv = function(v){ return (v === undefined || v === null) ? '' : String(v); }; break; case "int": cv = function(v){ return v !== undefined && v !== null && v !== '' ? parseInt(String(v).replace(stripRe, ""), 10) : ''; }; break; case "float": cv = function(v){ return v !== undefined && v !== null && v !== '' ? parseFloat(String(v).replace(stripRe, ""), 10) : ''; }; break; case "bool": case "boolean": cv = function(v){ return v === true || v === "true" || v == 1; }; break; case "date": cv = function(v){ if(!v){ return ''; } if(Ext.isDate(v)){ return v; } if(dateFormat){ if(dateFormat == "timestamp"){ return new Date(v*1000); } if(dateFormat == "time"){ return new Date(parseInt(v, 10)); } return Date.parseDate(v, dateFormat); } var parsed = Date.parse(v); return parsed ? new Date(parsed) : null; }; break; } this.convert = cv; } }; Ext.data.Field.prototype = { dateFormat: null, defaultValue: "", mapping: null, sortType : null, sortDir : "ASC" }; Ext.data.DataReader = function(meta, recordType){ this.meta = meta; this.recordType = Ext.isArray(recordType) ? Ext.data.Record.create(recordType) : recordType; }; Ext.data.DataReader.prototype = { }; Ext.data.DataProxy = function(){ this.addEvents( 'beforeload', 'load', 'loadexception' ); Ext.data.DataProxy.superclass.constructor.call(this); }; Ext.extend(Ext.data.DataProxy, Ext.util.Observable); Ext.data.MemoryProxy = function(data){ Ext.data.MemoryProxy.superclass.constructor.call(this); this.data = data; }; Ext.extend(Ext.data.MemoryProxy, Ext.data.DataProxy, { load : function(params, reader, callback, scope, arg){ params = params || {}; var result; try { result = reader.readRecords(this.data); }catch(e){ this.fireEvent("loadexception", this, arg, null, e); callback.call(scope, null, arg, false); return; } callback.call(scope, result, arg, true); }, update : function(params, records){ } }); Ext.data.HttpProxy = function(conn){ Ext.data.HttpProxy.superclass.constructor.call(this); this.conn = conn; this.useAjax = !conn || !conn.events; }; Ext.extend(Ext.data.HttpProxy, Ext.data.DataProxy, { getConnection : function(){ return this.useAjax ? Ext.Ajax : this.conn; }, load : function(params, reader, callback, scope, arg){ if(this.fireEvent("beforeload", this, params) !== false){ var o = { params : params || {}, request: { callback : callback, scope : scope, arg : arg }, reader: reader, callback : this.loadResponse, scope: this }; if(this.useAjax){ Ext.applyIf(o, this.conn); if(this.activeRequest){ Ext.Ajax.abort(this.activeRequest); } this.activeRequest = Ext.Ajax.request(o); }else{ this.conn.request(o); } }else{ callback.call(scope||this, null, arg, false); } }, loadResponse : function(o, success, response){ delete this.activeRequest; if(!success){ this.fireEvent("loadexception", this, o, response); o.request.callback.call(o.request.scope, null, o.request.arg, false); return; } var result; try { result = o.reader.read(response); }catch(e){ this.fireEvent("loadexception", this, o, response, e); o.request.callback.call(o.request.scope, null, o.request.arg, false); return; } this.fireEvent("load", this, o, o.request.arg); o.request.callback.call(o.request.scope, result, o.request.arg, true); }, update : function(dataSet){ }, updateResponse : function(dataSet){ } }); Ext.data.ScriptTagProxy = function(config){ Ext.data.ScriptTagProxy.superclass.constructor.call(this); Ext.apply(this, config); this.head = document.getElementsByTagName("head")[0]; }; Ext.data.ScriptTagProxy.TRANS_ID = 1000; Ext.extend(Ext.data.ScriptTagProxy, Ext.data.DataProxy, { timeout : 30000, callbackParam : "callback", nocache : true, load : function(params, reader, callback, scope, arg){ if(this.fireEvent("beforeload", this, params) !== false){ var p = Ext.urlEncode(Ext.apply(params, this.extraParams)); var url = this.url; url += (url.indexOf("?") != -1 ? "&" : "?") + p; if(this.nocache){ url += "&_dc=" + (new Date().getTime()); } var transId = ++Ext.data.ScriptTagProxy.TRANS_ID; var trans = { id : transId, cb : "stcCallback"+transId, scriptId : "stcScript"+transId, params : params, arg : arg, url : url, callback : callback, scope : scope, reader : reader }; var conn = this; window[trans.cb] = function(o){ conn.handleResponse(o, trans); }; url += String.format("&{0}={1}", this.callbackParam, trans.cb); if(this.autoAbort !== false){ this.abort(); } trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]); var script = document.createElement("script"); script.setAttribute("src", url); script.setAttribute("type", "text/javascript"); script.setAttribute("id", trans.scriptId); this.head.appendChild(script); this.trans = trans; }else{ callback.call(scope||this, null, arg, false); } }, isLoading : function(){ return this.trans ? true : false; }, abort : function(){ if(this.isLoading()){ this.destroyTrans(this.trans); } }, destroyTrans : function(trans, isLoaded){ this.head.removeChild(document.getElementById(trans.scriptId)); clearTimeout(trans.timeoutId); if(isLoaded){ window[trans.cb] = undefined; try{ delete window[trans.cb]; }catch(e){} }else{ window[trans.cb] = function(){ window[trans.cb] = undefined; try{ delete window[trans.cb]; }catch(e){} }; } }, handleResponse : function(o, trans){ this.trans = false; this.destroyTrans(trans, true); var result; try { result = trans.reader.readRecords(o); }catch(e){ this.fireEvent("loadexception", this, o, trans.arg, e); trans.callback.call(trans.scope||window, null, trans.arg, false); return; } this.fireEvent("load", this, o, trans.arg); trans.callback.call(trans.scope||window, result, trans.arg, true); }, handleFailure : function(trans){ this.trans = false; this.destroyTrans(trans, false); this.fireEvent("loadexception", this, null, trans.arg); trans.callback.call(trans.scope||window, null, trans.arg, false); } }); Ext.data.JsonReader = function(meta, recordType){ meta = meta || {}; Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields); }; Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, { read : function(response){ var json = response.responseText; var o = eval("("+json+")"); if(!o) { throw {message: "JsonReader.read: Json object not found"}; } if(o.metaData){ delete this.ef; this.meta = o.metaData; this.recordType = Ext.data.Record.create(o.metaData.fields); this.onMetaChange(this.meta, this.recordType, o); } return this.readRecords(o); }, onMetaChange : function(meta, recordType, o){ }, simpleAccess: function(obj, subsc) { return obj[subsc]; }, getJsonAccessor: function(){ var re = /[\[\.]/; return function(expr) { try { return(re.test(expr)) ? new Function("obj", "return obj." + expr) : function(obj){ return obj[expr]; }; } catch(e){} return Ext.emptyFn; }; }(), readRecords : function(o){ this.jsonData = o; var s = this.meta, Record = this.recordType, f = Record.prototype.fields, fi = f.items, fl = f.length; if (!this.ef) { if(s.totalProperty) { this.getTotal = this.getJsonAccessor(s.totalProperty); } if(s.successProperty) { this.getSuccess = this.getJsonAccessor(s.successProperty); } this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;}; if (s.id) { var g = this.getJsonAccessor(s.id); this.getId = function(rec) { var r = g(rec); return (r === undefined || r === "") ? null : r; }; } else { this.getId = function(){return null;}; } this.ef = []; for(var i = 0; i < fl; i++){ f = fi[i]; var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name; this.ef[i] = this.getJsonAccessor(map); } } var root = this.getRoot(o), c = root.length, totalRecords = c, success = true; if(s.totalProperty){ var v = parseInt(this.getTotal(o), 10); if(!isNaN(v)){ totalRecords = v; } } if(s.successProperty){ var v = this.getSuccess(o); if(v === false || v === 'false'){ success = false; } } var records = []; for(var i = 0; i < c; i++){ var n = root[i]; var values = {}; var id = this.getId(n); for(var j = 0; j < fl; j++){ f = fi[j]; var v = this.ef[j](n); values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, n); } var record = new Record(values, id); record.json = n; records[i] = record; } return { success : success, records : records, totalRecords : totalRecords }; } }); Ext.data.XmlReader = function(meta, recordType){ meta = meta || {}; Ext.data.XmlReader.superclass.constructor.call(this, meta, recordType || meta.fields); }; Ext.extend(Ext.data.XmlReader, Ext.data.DataReader, { read : function(response){ var doc = response.responseXML; if(!doc) { throw {message: "XmlReader.read: XML Document not available"}; } return this.readRecords(doc); }, readRecords : function(doc){ this.xmlData = doc; var root = doc.documentElement || doc; var q = Ext.DomQuery; var recordType = this.recordType, fields = recordType.prototype.fields; var sid = this.meta.id; var totalRecords = 0, success = true; if(this.meta.totalRecords){ totalRecords = q.selectNumber(this.meta.totalRecords, root, 0); } if(this.meta.success){ var sv = q.selectValue(this.meta.success, root, true); success = sv !== false && sv !== 'false'; } var records = []; var ns = q.select(this.meta.record, root); for(var i = 0, len = ns.length; i < len; i++) { var n = ns[i]; var values = {}; var id = sid ? q.selectValue(sid, n) : undefined; for(var j = 0, jlen = fields.length; j < jlen; j++){ var f = fields.items[j]; var v = q.selectValue(f.mapping || f.name, n, f.defaultValue); v = f.convert(v, n); values[f.name] = v; } var record = new recordType(values, id); record.node = n; records[records.length] = record; } return { success : success, records : records, totalRecords : totalRecords || records.length }; } }); Ext.data.ArrayReader = Ext.extend(Ext.data.JsonReader, { readRecords : function(o){ var sid = this.meta ? this.meta.id : null; var recordType = this.recordType, fields = recordType.prototype.fields; var records = []; var root = o; for(var i = 0; i < root.length; i++){ var n = root[i]; var values = {}; var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null); for(var j = 0, jlen = fields.length; j < jlen; j++){ var f = fields.items[j]; var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j; var v = n[k] !== undefined ? n[k] : f.defaultValue; v = f.convert(v, n); values[f.name] = v; } var record = new recordType(values, id); record.json = n; records[records.length] = record; } return { records : records, totalRecords : records.length }; } }); Ext.data.Tree = function(root){ this.nodeHash = {}; this.root = null; if(root){ this.setRootNode(root); } this.addEvents( "append", "remove", "move", "insert", "beforeappend", "beforeremove", "beforemove", "beforeinsert" ); Ext.data.Tree.superclass.constructor.call(this); }; Ext.extend(Ext.data.Tree, Ext.util.Observable, { pathSeparator: "/", proxyNodeEvent : function(){ return this.fireEvent.apply(this, arguments); }, getRootNode : function(){ return this.root; }, setRootNode : function(node){ this.root = node; node.ownerTree = this; node.isRoot = true; this.registerNode(node); return node; }, getNodeById : function(id){ return this.nodeHash[id]; }, registerNode : function(node){ this.nodeHash[node.id] = node; }, unregisterNode : function(node){ delete this.nodeHash[node.id]; }, toString : function(){ return "[Tree"+(this.id?" "+this.id:"")+"]"; } }); Ext.data.Node = function(attributes){ this.attributes = attributes || {}; this.leaf = this.attributes.leaf; this.id = this.attributes.id; if(!this.id){ this.id = Ext.id(null, "ynode-"); this.attributes.id = this.id; } this.childNodes = []; if(!this.childNodes.indexOf){ this.childNodes.indexOf = function(o){ for(var i = 0, len = this.length; i < len; i++){ if(this[i] == o) return i; } return -1; }; } this.parentNode = null; this.firstChild = null; this.lastChild = null; this.previousSibling = null; this.nextSibling = null; this.addEvents({ "append" : true, "remove" : true, "move" : true, "insert" : true, "beforeappend" : true, "beforeremove" : true, "beforemove" : true, "beforeinsert" : true }); this.listeners = this.attributes.listeners; Ext.data.Node.superclass.constructor.call(this); }; Ext.extend(Ext.data.Node, Ext.util.Observable, { fireEvent : function(evtName){ if(Ext.data.Node.superclass.fireEvent.apply(this, arguments) === false){ return false; } var ot = this.getOwnerTree(); if(ot){ if(ot.proxyNodeEvent.apply(ot, arguments) === false){ return false; } } return true; }, isLeaf : function(){ return this.leaf === true; }, setFirstChild : function(node){ this.firstChild = node; }, setLastChild : function(node){ this.lastChild = node; }, isLast : function(){ return (!this.parentNode ? true : this.parentNode.lastChild == this); }, isFirst : function(){ return (!this.parentNode ? true : this.parentNode.firstChild == this); }, hasChildNodes : function(){ return !this.isLeaf() && this.childNodes.length > 0; }, appendChild : function(node){ var multi = false; if(Ext.isArray(node)){ multi = node; }else if(arguments.length > 1){ multi = arguments; } if(multi){ for(var i = 0, len = multi.length; i < len; i++) { this.appendChild(multi[i]); } }else{ if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){ return false; } var index = this.childNodes.length; var oldParent = node.parentNode; if(oldParent){ if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){ return false; } oldParent.removeChild(node); } index = this.childNodes.length; if(index == 0){ this.setFirstChild(node); } this.childNodes.push(node); node.parentNode = this; var ps = this.childNodes[index-1]; if(ps){ node.previousSibling = ps; ps.nextSibling = node; }else{ node.previousSibling = null; } node.nextSibling = null; this.setLastChild(node); node.setOwnerTree(this.getOwnerTree()); this.fireEvent("append", this.ownerTree, this, node, index); if(oldParent){ node.fireEvent("move", this.ownerTree, node, oldParent, this, index); } return node; } }, removeChild : function(node){ var index = this.childNodes.indexOf(node); if(index == -1){ return false; } if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){ return false; } this.childNodes.splice(index, 1); if(node.previousSibling){ node.previousSibling.nextSibling = node.nextSibling; } if(node.nextSibling){ node.nextSibling.previousSibling = node.previousSibling; } if(this.firstChild == node){ this.setFirstChild(node.nextSibling); } if(this.lastChild == node){ this.setLastChild(node.previousSibling); } node.setOwnerTree(null); node.parentNode = null; node.previousSibling = null; node.nextSibling = null; this.fireEvent("remove", this.ownerTree, this, node); return node; }, insertBefore : function(node, refNode){ if(!refNode){ return this.appendChild(node); } if(node == refNode){ return false; } if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){ return false; } var index = this.childNodes.indexOf(refNode); var oldParent = node.parentNode; var refIndex = index; if(oldParent == this && this.childNodes.indexOf(node) < index){ refIndex--; } if(oldParent){ if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){ return false; } oldParent.removeChild(node); } if(refIndex == 0){ this.setFirstChild(node); } this.childNodes.splice(refIndex, 0, node); node.parentNode = this; var ps = this.childNodes[refIndex-1]; if(ps){ node.previousSibling = ps; ps.nextSibling = node; }else{ node.previousSibling = null; } node.nextSibling = refNode; refNode.previousSibling = node; node.setOwnerTree(this.getOwnerTree()); this.fireEvent("insert", this.ownerTree, this, node, refNode); if(oldParent){ node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode); } return node; }, remove : function(){ this.parentNode.removeChild(this); return this; }, item : function(index){ return this.childNodes[index]; }, replaceChild : function(newChild, oldChild){ this.insertBefore(newChild, oldChild); this.removeChild(oldChild); return oldChild; }, indexOf : function(child){ return this.childNodes.indexOf(child); }, getOwnerTree : function(){ if(!this.ownerTree){ var p = this; while(p){ if(p.ownerTree){ this.ownerTree = p.ownerTree; break; } p = p.parentNode; } } return this.ownerTree; }, getDepth : function(){ var depth = 0; var p = this; while(p.parentNode){ ++depth; p = p.parentNode; } return depth; }, setOwnerTree : function(tree){ if(tree != this.ownerTree){ if(this.ownerTree){ this.ownerTree.unregisterNode(this); } this.ownerTree = tree; var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { cs[i].setOwnerTree(tree); } if(tree){ tree.registerNode(this); } } }, getPath : function(attr){ attr = attr || "id"; var p = this.parentNode; var b = [this.attributes[attr]]; while(p){ b.unshift(p.attributes[attr]); p = p.parentNode; } var sep = this.getOwnerTree().pathSeparator; return sep + b.join(sep); }, bubble : function(fn, scope, args){ var p = this; while(p){ if(fn.apply(scope || p, args || [p]) === false){ break; } p = p.parentNode; } }, cascade : function(fn, scope, args){ if(fn.apply(scope || this, args || [this]) !== false){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { cs[i].cascade(fn, scope, args); } } }, eachChild : function(fn, scope, args){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { if(fn.apply(scope || this, args || [cs[i]]) === false){ break; } } }, findChild : function(attribute, value){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { if(cs[i].attributes[attribute] == value){ return cs[i]; } } return null; }, findChildBy : function(fn, scope){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { if(fn.call(scope||cs[i], cs[i]) === true){ return cs[i]; } } return null; }, sort : function(fn, scope){ var cs = this.childNodes; var len = cs.length; if(len > 0){ var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn; cs.sort(sortFn); for(var i = 0; i < len; i++){ var n = cs[i]; n.previousSibling = cs[i-1]; n.nextSibling = cs[i+1]; if(i == 0){ this.setFirstChild(n); } if(i == len-1){ this.setLastChild(n); } } } }, contains : function(node){ return node.isAncestor(this); }, isAncestor : function(node){ var p = this.parentNode; while(p){ if(p == node){ return true; } p = p.parentNode; } return false; }, toString : function(){ return "[Node"+(this.id?" "+this.id:"")+"]"; } }); Ext.data.GroupingStore = Ext.extend(Ext.data.Store, { remoteGroup : false, groupOnSort:false, clearGrouping : function(){ this.groupField = false; if(this.remoteGroup){ if(this.baseParams){ delete this.baseParams.groupBy; } this.reload(); }else{ this.applySort(); this.fireEvent('datachanged', this); } }, groupBy : function(field, forceRegroup){ if(this.groupField == field && !forceRegroup){ return; } this.groupField = field; if(this.remoteGroup){ if(!this.baseParams){ this.baseParams = {}; } this.baseParams['groupBy'] = field; } if(this.groupOnSort){ this.sort(field); return; } if(this.remoteGroup){ this.reload(); }else{ var si = this.sortInfo || {}; if(si.field != field){ this.applySort(); }else{ this.sortData(field); } this.fireEvent('datachanged', this); } }, applySort : function(){ Ext.data.GroupingStore.superclass.applySort.call(this); if(!this.groupOnSort && !this.remoteGroup){ var gs = this.getGroupState(); if(gs && gs != this.sortInfo.field){ this.sortData(this.groupField); } } }, applyGrouping : function(alwaysFireChange){ if(this.groupField !== false){ this.groupBy(this.groupField, true); return true; }else{ if(alwaysFireChange === true){ this.fireEvent('datachanged', this); } return false; } }, getGroupState : function(){ return this.groupOnSort && this.groupField !== false ? (this.sortInfo ? this.sortInfo.field : undefined) : this.groupField; } }); Ext.ComponentMgr = function(){ var all = new Ext.util.MixedCollection(); var types = {}; return { register : function(c){ all.add(c); }, unregister : function(c){ all.remove(c); }, get : function(id){ return all.get(id); }, onAvailable : function(id, fn, scope){ all.on("add", function(index, o){ if(o.id == id){ fn.call(scope || o, o); all.un("add", fn, scope); } }); }, all : all, registerType : function(xtype, cls){ types[xtype] = cls; cls.xtype = xtype; }, create : function(config, defaultType){ return new types[config.xtype || defaultType](config); } }; }(); Ext.reg = Ext.ComponentMgr.registerType; Ext.Component = function(config){ config = config || {}; if(config.initialConfig){ if(config.isAction){ this.baseAction = config; } config = config.initialConfig; }else if(config.tagName || config.dom || typeof config == "string"){ config = {applyTo: config, id: config.id || config}; } this.initialConfig = config; Ext.apply(this, config); this.addEvents( 'disable', 'enable', 'beforeshow', 'show', 'beforehide', 'hide', 'beforerender', 'render', 'beforedestroy', 'destroy', 'beforestaterestore', 'staterestore', 'beforestatesave', 'statesave' ); this.getId(); Ext.ComponentMgr.register(this); Ext.Component.superclass.constructor.call(this); if(this.baseAction){ this.baseAction.addComponent(this); } this.initComponent(); if(this.plugins){ if(Ext.isArray(this.plugins)){ for(var i = 0, len = this.plugins.length; i < len; i++){ this.plugins[i].init(this); } }else{ this.plugins.init(this); } } if(this.stateful !== false){ this.initState(config); } if(this.applyTo){ this.applyToMarkup(this.applyTo); delete this.applyTo; }else if(this.renderTo){ this.render(this.renderTo); delete this.renderTo; } }; Ext.Component.AUTO_ID = 1000; Ext.extend(Ext.Component, Ext.util.Observable, { disabledClass : "x-item-disabled", allowDomMove : true, autoShow : false, hideMode: 'display', hideParent: false, hidden : false, disabled : false, rendered : false, ctype : "Ext.Component", actionMode : "el", getActionEl : function(){ return this[this.actionMode]; }, initComponent : Ext.emptyFn, render : function(container, position){ if(!this.rendered && this.fireEvent("beforerender", this) !== false){ if(!container && this.el){ this.el = Ext.get(this.el); container = this.el.dom.parentNode; this.allowDomMove = false; } this.container = Ext.get(container); if(this.ctCls){ this.container.addClass(this.ctCls); } this.rendered = true; if(position !== undefined){ if(typeof position == 'number'){ position = this.container.dom.childNodes[position]; }else{ position = Ext.getDom(position); } } this.onRender(this.container, position || null); if(this.autoShow){ this.el.removeClass(['x-hidden','x-hide-' + this.hideMode]); } if(this.cls){ this.el.addClass(this.cls); delete this.cls; } if(this.style){ this.el.applyStyles(this.style); delete this.style; } this.fireEvent("render", this); this.afterRender(this.container); if(this.hidden){ this.hide(); } if(this.disabled){ this.disable(); } this.initStateEvents(); } return this; }, initState : function(config){ if(Ext.state.Manager){ var state = Ext.state.Manager.get(this.stateId || this.id); if(state){ if(this.fireEvent('beforestaterestore', this, state) !== false){ this.applyState(state); this.fireEvent('staterestore', this, state); } } } }, initStateEvents : function(){ if(this.stateEvents){ for(var i = 0, e; e = this.stateEvents[i]; i++){ this.on(e, this.saveState, this, {delay:100}); } } }, applyState : function(state, config){ if(state){ Ext.apply(this, state); } }, getState : function(){ return null; }, saveState : function(){ if(Ext.state.Manager){ var state = this.getState(); if(this.fireEvent('beforestatesave', this, state) !== false){ Ext.state.Manager.set(this.stateId || this.id, state); this.fireEvent('statesave', this, state); } } }, applyToMarkup : function(el){ this.allowDomMove = false; this.el = Ext.get(el); this.render(this.el.dom.parentNode); }, addClass : function(cls){ if(this.el){ this.el.addClass(cls); }else{ this.cls = this.cls ? this.cls + ' ' + cls : cls; } }, removeClass : function(cls){ if(this.el){ this.el.removeClass(cls); }else if(this.cls){ this.cls = this.cls.split(' ').remove(cls).join(' '); } }, onRender : function(ct, position){ if(this.autoEl){ if(typeof this.autoEl == 'string'){ this.el = document.createElement(this.autoEl); }else{ var div = document.createElement('div'); Ext.DomHelper.overwrite(div, this.autoEl); this.el = div.firstChild; } if (!this.el.id) { this.el.id = this.getId(); } } if(this.el){ this.el = Ext.get(this.el); if(this.allowDomMove !== false){ ct.dom.insertBefore(this.el.dom, position); } } }, getAutoCreate : function(){ var cfg = typeof this.autoCreate == "object" ? this.autoCreate : Ext.apply({}, this.defaultAutoCreate); if(this.id && !cfg.id){ cfg.id = this.id; } return cfg; }, afterRender : Ext.emptyFn, destroy : function(){ if(this.fireEvent("beforedestroy", this) !== false){ this.beforeDestroy(); if(this.rendered){ this.el.removeAllListeners(); this.el.remove(); if(this.actionMode == "container"){ this.container.remove(); } } this.onDestroy(); Ext.ComponentMgr.unregister(this); this.fireEvent("destroy", this); this.purgeListeners(); } }, beforeDestroy : Ext.emptyFn, onDestroy : Ext.emptyFn, getEl : function(){ return this.el; }, getId : function(){ return this.id || (this.id = "ext-comp-" + (++Ext.Component.AUTO_ID)); }, getItemId : function(){ return this.itemId || this.getId(); }, focus : function(selectText, delay){ if(delay){ this.focus.defer(typeof delay == 'number' ? delay : 10, this, [selectText, false]); return; } if(this.rendered){ this.el.focus(); if(selectText === true){ this.el.dom.select(); } } return this; }, blur : function(){ if(this.rendered){ this.el.blur(); } return this; }, disable : function(){ if(this.rendered){ this.onDisable(); } this.disabled = true; this.fireEvent("disable", this); return this; }, onDisable : function(){ this.getActionEl().addClass(this.disabledClass); this.el.dom.disabled = true; }, enable : function(){ if(this.rendered){ this.onEnable(); } this.disabled = false; this.fireEvent("enable", this); return this; }, onEnable : function(){ this.getActionEl().removeClass(this.disabledClass); this.el.dom.disabled = false; }, setDisabled : function(disabled){ this[disabled ? "disable" : "enable"](); }, show: function(){ if(this.fireEvent("beforeshow", this) !== false){ this.hidden = false; if(this.autoRender){ this.render(typeof this.autoRender == 'boolean' ? Ext.getBody() : this.autoRender); } if(this.rendered){ this.onShow(); } this.fireEvent("show", this); } return this; }, onShow : function(){ if(this.hideParent){ this.container.removeClass('x-hide-' + this.hideMode); }else{ this.getActionEl().removeClass('x-hide-' + this.hideMode); } }, hide: function(){ if(this.fireEvent("beforehide", this) !== false){ this.hidden = true; if(this.rendered){ this.onHide(); } this.fireEvent("hide", this); } return this; }, onHide : function(){ if(this.hideParent){ this.container.addClass('x-hide-' + this.hideMode); }else{ this.getActionEl().addClass('x-hide-' + this.hideMode); } }, setVisible: function(visible){ if(visible) { this.show(); }else{ this.hide(); } return this; }, isVisible : function(){ return this.rendered && this.getActionEl().isVisible(); }, cloneConfig : function(overrides){ overrides = overrides || {}; var id = overrides.id || Ext.id(); var cfg = Ext.applyIf(overrides, this.initialConfig); cfg.id = id; return new this.constructor(cfg); }, getXType : function(){ return this.constructor.xtype; }, isXType : function(xtype, shallow){ return !shallow ? ('/' + this.getXTypes() + '/').indexOf('/' + xtype + '/') != -1 : this.constructor.xtype == xtype; }, getXTypes : function(){ var tc = this.constructor; if(!tc.xtypes){ var c = [], sc = this; while(sc && sc.constructor.xtype){ c.unshift(sc.constructor.xtype); sc = sc.constructor.superclass; } tc.xtypeChain = c; tc.xtypes = c.join('/'); } return tc.xtypes; }, findParentBy: function(fn) { for (var p = this.ownerCt; (p != null) && !fn(p, this); p = p.ownerCt); return p || null; }, findParentByType: function(xtype) { return typeof xtype == 'function' ? this.findParentBy(function(p){ return p.constructor === xtype; }) : this.findParentBy(function(p){ return p.constructor.xtype === xtype; }); } }); Ext.reg('component', Ext.Component); Ext.Action = function(config){ this.initialConfig = config; this.items = []; } Ext.Action.prototype = { isAction : true, setText : function(text){ this.initialConfig.text = text; this.callEach('setText', [text]); }, getText : function(){ return this.initialConfig.text; }, setIconClass : function(cls){ this.initialConfig.iconCls = cls; this.callEach('setIconClass', [cls]); }, getIconClass : function(){ return this.initialConfig.iconCls; }, setDisabled : function(v){ this.initialConfig.disabled = v; this.callEach('setDisabled', [v]); }, enable : function(){ this.setDisabled(false); }, disable : function(){ this.setDisabled(true); }, isDisabled : function(){ return this.initialConfig.disabled; }, setHidden : function(v){ this.initialConfig.hidden = v; this.callEach('setVisible', [!v]); }, show : function(){ this.setHidden(false); }, hide : function(){ this.setHidden(true); }, isHidden : function(){ return this.initialConfig.hidden; }, setHandler : function(fn, scope){ this.initialConfig.handler = fn; this.initialConfig.scope = scope; this.callEach('setHandler', [fn, scope]); }, each : function(fn, scope){ Ext.each(this.items, fn, scope); }, callEach : function(fnName, args){ var cs = this.items; for(var i = 0, len = cs.length; i < len; i++){ cs[i][fnName].apply(cs[i], args); } }, addComponent : function(comp){ this.items.push(comp); comp.on('destroy', this.removeComponent, this); }, removeComponent : function(comp){ this.items.remove(comp); }, execute : function(){ this.initialConfig.handler.apply(this.initialConfig.scope || window, arguments); } }; (function(){ Ext.Layer = function(config, existingEl){ config = config || {}; var dh = Ext.DomHelper; var cp = config.parentEl, pel = cp ? Ext.getDom(cp) : document.body; if(existingEl){ this.dom = Ext.getDom(existingEl); } if(!this.dom){ var o = config.dh || {tag: "div", cls: "x-layer"}; this.dom = dh.append(pel, o); } if(config.cls){ this.addClass(config.cls); } this.constrain = config.constrain !== false; this.visibilityMode = Ext.Element.VISIBILITY; if(config.id){ this.id = this.dom.id = config.id; }else{ this.id = Ext.id(this.dom); } this.zindex = config.zindex || this.getZIndex(); this.position("absolute", this.zindex); if(config.shadow){ this.shadowOffset = config.shadowOffset || 4; this.shadow = new Ext.Shadow({ offset : this.shadowOffset, mode : config.shadow }); }else{ this.shadowOffset = 0; } this.useShim = config.shim !== false && Ext.useShims; this.useDisplay = config.useDisplay; this.hide(); }; var supr = Ext.Element.prototype; var shims = []; Ext.extend(Ext.Layer, Ext.Element, { getZIndex : function(){ return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000; }, getShim : function(){ if(!this.useShim){ return null; } if(this.shim){ return this.shim; } var shim = shims.shift(); if(!shim){ shim = this.createShim(); shim.enableDisplayMode('block'); shim.dom.style.display = 'none'; shim.dom.style.visibility = 'visible'; } var pn = this.dom.parentNode; if(shim.dom.parentNode != pn){ pn.insertBefore(shim.dom, this.dom); } shim.setStyle('z-index', this.getZIndex()-2); this.shim = shim; return shim; }, hideShim : function(){ if(this.shim){ this.shim.setDisplayed(false); shims.push(this.shim); delete this.shim; } }, disableShadow : function(){ if(this.shadow){ this.shadowDisabled = true; this.shadow.hide(); this.lastShadowOffset = this.shadowOffset; this.shadowOffset = 0; } }, enableShadow : function(show){ if(this.shadow){ this.shadowDisabled = false; this.shadowOffset = this.lastShadowOffset; delete this.lastShadowOffset; if(show){ this.sync(true); } } }, sync : function(doShow){ var sw = this.shadow; if(!this.updating && this.isVisible() && (sw || this.useShim)){ var sh = this.getShim(); var w = this.getWidth(), h = this.getHeight(); var l = this.getLeft(true), t = this.getTop(true); if(sw && !this.shadowDisabled){ if(doShow && !sw.isVisible()){ sw.show(this); }else{ sw.realign(l, t, w, h); } if(sh){ if(doShow){ sh.show(); } var a = sw.adjusts, s = sh.dom.style; s.left = (Math.min(l, l+a.l))+"px"; s.top = (Math.min(t, t+a.t))+"px"; s.width = (w+a.w)+"px"; s.height = (h+a.h)+"px"; } }else if(sh){ if(doShow){ sh.show(); } sh.setSize(w, h); sh.setLeftTop(l, t); } } }, destroy : function(){ this.hideShim(); if(this.shadow){ this.shadow.hide(); } this.removeAllListeners(); Ext.removeNode(this.dom); Ext.Element.uncache(this.id); }, remove : function(){ this.destroy(); }, beginUpdate : function(){ this.updating = true; }, endUpdate : function(){ this.updating = false; this.sync(true); }, hideUnders : function(negOffset){ if(this.shadow){ this.shadow.hide(); } this.hideShim(); }, constrainXY : function(){ if(this.constrain){ var vw = Ext.lib.Dom.getViewWidth(), vh = Ext.lib.Dom.getViewHeight(); var s = Ext.getDoc().getScroll(); var xy = this.getXY(); var x = xy[0], y = xy[1]; var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset; var moved = false; if((x + w) > vw+s.left){ x = vw - w - this.shadowOffset; moved = true; } if((y + h) > vh+s.top){ y = vh - h - this.shadowOffset; moved = true; } if(x < s.left){ x = s.left; moved = true; } if(y < s.top){ y = s.top; moved = true; } if(moved){ if(this.avoidY){ var ay = this.avoidY; if(y <= ay && (y+h) >= ay){ y = ay-h-5; } } xy = [x, y]; this.storeXY(xy); supr.setXY.call(this, xy); this.sync(); } } }, isVisible : function(){ return this.visible; }, showAction : function(){ this.visible = true; if(this.useDisplay === true){ this.setDisplayed(""); }else if(this.lastXY){ supr.setXY.call(this, this.lastXY); }else if(this.lastLT){ supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]); } }, hideAction : function(){ this.visible = false; if(this.useDisplay === true){ this.setDisplayed(false); }else{ this.setLeftTop(-10000,-10000); } }, setVisible : function(v, a, d, c, e){ if(v){ this.showAction(); } if(a && v){ var cb = function(){ this.sync(true); if(c){ c(); } }.createDelegate(this); supr.setVisible.call(this, true, true, d, cb, e); }else{ if(!v){ this.hideUnders(true); } var cb = c; if(a){ cb = function(){ this.hideAction(); if(c){ c(); } }.createDelegate(this); } supr.setVisible.call(this, v, a, d, cb, e); if(v){ this.sync(true); }else if(!a){ this.hideAction(); } } }, storeXY : function(xy){ delete this.lastLT; this.lastXY = xy; }, storeLeftTop : function(left, top){ delete this.lastXY; this.lastLT = [left, top]; }, beforeFx : function(){ this.beforeAction(); return Ext.Layer.superclass.beforeFx.apply(this, arguments); }, afterFx : function(){ Ext.Layer.superclass.afterFx.apply(this, arguments); this.sync(this.isVisible()); }, beforeAction : function(){ if(!this.updating && this.shadow){ this.shadow.hide(); } }, setLeft : function(left){ this.storeLeftTop(left, this.getTop(true)); supr.setLeft.apply(this, arguments); this.sync(); }, setTop : function(top){ this.storeLeftTop(this.getLeft(true), top); supr.setTop.apply(this, arguments); this.sync(); }, setLeftTop : function(left, top){ this.storeLeftTop(left, top); supr.setLeftTop.apply(this, arguments); this.sync(); }, setXY : function(xy, a, d, c, e){ this.fixDisplay(); this.beforeAction(); this.storeXY(xy); var cb = this.createCB(c); supr.setXY.call(this, xy, a, d, cb, e); if(!a){ cb(); } }, createCB : function(c){ var el = this; return function(){ el.constrainXY(); el.sync(true); if(c){ c(); } }; }, setX : function(x, a, d, c, e){ this.setXY([x, this.getY()], a, d, c, e); }, setY : function(y, a, d, c, e){ this.setXY([this.getX(), y], a, d, c, e); }, setSize : function(w, h, a, d, c, e){ this.beforeAction(); var cb = this.createCB(c); supr.setSize.call(this, w, h, a, d, cb, e); if(!a){ cb(); } }, setWidth : function(w, a, d, c, e){ this.beforeAction(); var cb = this.createCB(c); supr.setWidth.call(this, w, a, d, cb, e); if(!a){ cb(); } }, setHeight : function(h, a, d, c, e){ this.beforeAction(); var cb = this.createCB(c); supr.setHeight.call(this, h, a, d, cb, e); if(!a){ cb(); } }, setBounds : function(x, y, w, h, a, d, c, e){ this.beforeAction(); var cb = this.createCB(c); if(!a){ this.storeXY([x, y]); supr.setXY.call(this, [x, y]); supr.setSize.call(this, w, h, a, d, cb, e); cb(); }else{ supr.setBounds.call(this, x, y, w, h, a, d, cb, e); } return this; }, setZIndex : function(zindex){ this.zindex = zindex; this.setStyle("z-index", zindex + 2); if(this.shadow){ this.shadow.setZIndex(zindex + 1); } if(this.shim){ this.shim.setStyle("z-index", zindex); } } }); })(); Ext.Shadow = function(config){ Ext.apply(this, config); if(typeof this.mode != "string"){ this.mode = this.defaultMode; } var o = this.offset, a = {h: 0}; var rad = Math.floor(this.offset/2); switch(this.mode.toLowerCase()){ case "drop": a.w = 0; a.l = a.t = o; a.t -= 1; if(Ext.isIE){ a.l -= this.offset + rad; a.t -= this.offset + rad; a.w -= rad; a.h -= rad; a.t += 1; } break; case "sides": a.w = (o*2); a.l = -o; a.t = o-1; if(Ext.isIE){ a.l -= (this.offset - rad); a.t -= this.offset + rad; a.l += 1; a.w -= (this.offset - rad)*2; a.w -= rad + 1; a.h -= 1; } break; case "frame": a.w = a.h = (o*2); a.l = a.t = -o; a.t += 1; a.h -= 2; if(Ext.isIE){ a.l -= (this.offset - rad); a.t -= (this.offset - rad); a.l += 1; a.w -= (this.offset + rad + 1); a.h -= (this.offset + rad); a.h += 1; } break; }; this.adjusts = a; }; Ext.Shadow.prototype = { offset: 4, defaultMode: "drop", show : function(target){ target = Ext.get(target); if(!this.el){ this.el = Ext.Shadow.Pool.pull(); if(this.el.dom.nextSibling != target.dom){ this.el.insertBefore(target); } } this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1); if(Ext.isIE){ this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")"; } this.realign( target.getLeft(true), target.getTop(true), target.getWidth(), target.getHeight() ); this.el.dom.style.display = "block"; }, isVisible : function(){ return this.el ? true : false; }, realign : function(l, t, w, h){ if(!this.el){ return; } var a = this.adjusts, d = this.el.dom, s = d.style; var iea = 0; s.left = (l+a.l)+"px"; s.top = (t+a.t)+"px"; var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px"; if(s.width != sws || s.height != shs){ s.width = sws; s.height = shs; if(!Ext.isIE){ var cn = d.childNodes; var sww = Math.max(0, (sw-12))+"px"; cn[0].childNodes[1].style.width = sww; cn[1].childNodes[1].style.width = sww; cn[2].childNodes[1].style.width = sww; cn[1].style.height = Math.max(0, (sh-12))+"px"; } } }, hide : function(){ if(this.el){ this.el.dom.style.display = "none"; Ext.Shadow.Pool.push(this.el); delete this.el; } }, setZIndex : function(z){ this.zIndex = z; if(this.el){ this.el.setStyle("z-index", z); } } }; Ext.Shadow.Pool = function(){ var p = []; var markup = Ext.isIE ? '<div class="x-ie-shadow"></div>' : '<div class="x-shadow"><div class="xst"><div class="xstl"></div><div class="xstc"></div><div class="xstr"></div></div><div class="xsc"><div class="xsml"></div><div class="xsmc"></div><div class="xsmr"></div></div><div class="xsb"><div class="xsbl"></div><div class="xsbc"></div><div class="xsbr"></div></div></div>'; return { pull : function(){ var sh = p.shift(); if(!sh){ sh = Ext.get(Ext.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup)); sh.autoBoxAdjust = false; } return sh; }, push : function(sh){ p.push(sh); } }; }(); Ext.BoxComponent = Ext.extend(Ext.Component, { initComponent : function(){ Ext.BoxComponent.superclass.initComponent.call(this); this.addEvents( 'resize', 'move' ); }, boxReady : false, deferHeight: false, setSize : function(w, h){ if(typeof w == 'object'){ h = w.height; w = w.width; } if(!this.boxReady){ this.width = w; this.height = h; return this; } if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){ return this; } this.lastSize = {width: w, height: h}; var adj = this.adjustSize(w, h); var aw = adj.width, ah = adj.height; if(aw !== undefined || ah !== undefined){ var rz = this.getResizeEl(); if(!this.deferHeight && aw !== undefined && ah !== undefined){ rz.setSize(aw, ah); }else if(!this.deferHeight && ah !== undefined){ rz.setHeight(ah); }else if(aw !== undefined){ rz.setWidth(aw); } this.onResize(aw, ah, w, h); this.fireEvent('resize', this, aw, ah, w, h); } return this; }, setWidth : function(width){ return this.setSize(width); }, setHeight : function(height){ return this.setSize(undefined, height); }, getSize : function(){ return this.el.getSize(); }, getPosition : function(local){ if(local === true){ return [this.el.getLeft(true), this.el.getTop(true)]; } return this.xy || this.el.getXY(); }, getBox : function(local){ var s = this.el.getSize(); if(local === true){ s.x = this.el.getLeft(true); s.y = this.el.getTop(true); }else{ var xy = this.xy || this.el.getXY(); s.x = xy[0]; s.y = xy[1]; } return s; }, updateBox : function(box){ this.setSize(box.width, box.height); this.setPagePosition(box.x, box.y); return this; }, getResizeEl : function(){ return this.resizeEl || this.el; }, getPositionEl : function(){ return this.positionEl || this.el; }, setPosition : function(x, y){ if(x && typeof x[1] == 'number'){ y = x[1]; x = x[0]; } this.x = x; this.y = y; if(!this.boxReady){ return this; } var adj = this.adjustPosition(x, y); var ax = adj.x, ay = adj.y; var el = this.getPositionEl(); if(ax !== undefined || ay !== undefined){ if(ax !== undefined && ay !== undefined){ el.setLeftTop(ax, ay); }else if(ax !== undefined){ el.setLeft(ax); }else if(ay !== undefined){ el.setTop(ay); } this.onPosition(ax, ay); this.fireEvent('move', this, ax, ay); } return this; }, setPagePosition : function(x, y){ if(x && typeof x[1] == 'number'){ y = x[1]; x = x[0]; } this.pageX = x; this.pageY = y; if(!this.boxReady){ return; } if(x === undefined || y === undefined){ return; } var p = this.el.translatePoints(x, y); this.setPosition(p.left, p.top); return this; }, onRender : function(ct, position){ Ext.BoxComponent.superclass.onRender.call(this, ct, position); if(this.resizeEl){ this.resizeEl = Ext.get(this.resizeEl); } if(this.positionEl){ this.positionEl = Ext.get(this.positionEl); } }, afterRender : function(){ Ext.BoxComponent.superclass.afterRender.call(this); this.boxReady = true; this.setSize(this.width, this.height); if(this.x || this.y){ this.setPosition(this.x, this.y); }else if(this.pageX || this.pageY){ this.setPagePosition(this.pageX, this.pageY); } }, syncSize : function(){ delete this.lastSize; this.setSize(this.autoWidth ? undefined : this.el.getWidth(), this.autoHeight ? undefined : this.el.getHeight()); return this; }, onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){ }, onPosition : function(x, y){ }, adjustSize : function(w, h){ if(this.autoWidth){ w = 'auto'; } if(this.autoHeight){ h = 'auto'; } return {width : w, height: h}; }, adjustPosition : function(x, y){ return {x : x, y: y}; } }); Ext.reg('box', Ext.BoxComponent); Ext.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){ this.el = Ext.get(dragElement, true); this.el.dom.unselectable = "on"; this.resizingEl = Ext.get(resizingElement, true); this.orientation = orientation || Ext.SplitBar.HORIZONTAL; this.minSize = 0; this.maxSize = 2000; this.animate = false; this.useShim = false; this.shim = null; if(!existingProxy){ this.proxy = Ext.SplitBar.createProxy(this.orientation); }else{ this.proxy = Ext.get(existingProxy).dom; } this.dd = new Ext.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id}); this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this); this.dd.endDrag = this.onEndProxyDrag.createDelegate(this); this.dragSpecs = {}; this.adapter = new Ext.SplitBar.BasicLayoutAdapter(); this.adapter.init(this); if(this.orientation == Ext.SplitBar.HORIZONTAL){ this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Ext.SplitBar.LEFT : Ext.SplitBar.RIGHT); this.el.addClass("x-splitbar-h"); }else{ this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Ext.SplitBar.TOP : Ext.SplitBar.BOTTOM); this.el.addClass("x-splitbar-v"); } this.addEvents( "resize", "moved", "beforeresize", "beforeapply" ); Ext.SplitBar.superclass.constructor.call(this); }; Ext.extend(Ext.SplitBar, Ext.util.Observable, { onStartProxyDrag : function(x, y){ this.fireEvent("beforeresize", this); this.overlay = Ext.DomHelper.append(document.body, {cls: "x-drag-overlay", html: "&#160;"}, true); this.overlay.unselectable(); this.overlay.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true)); this.overlay.show(); Ext.get(this.proxy).setDisplayed("block"); var size = this.adapter.getElementSize(this); this.activeMinSize = this.getMinimumSize();; this.activeMaxSize = this.getMaximumSize();; var c1 = size - this.activeMinSize; var c2 = Math.max(this.activeMaxSize - size, 0); if(this.orientation == Ext.SplitBar.HORIZONTAL){ this.dd.resetConstraints(); this.dd.setXConstraint( this.placement == Ext.SplitBar.LEFT ? c1 : c2, this.placement == Ext.SplitBar.LEFT ? c2 : c1 ); this.dd.setYConstraint(0, 0); }else{ this.dd.resetConstraints(); this.dd.setXConstraint(0, 0); this.dd.setYConstraint( this.placement == Ext.SplitBar.TOP ? c1 : c2, this.placement == Ext.SplitBar.TOP ? c2 : c1 ); } this.dragSpecs.startSize = size; this.dragSpecs.startPoint = [x, y]; Ext.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y); }, onEndProxyDrag : function(e){ Ext.get(this.proxy).setDisplayed(false); var endPoint = Ext.lib.Event.getXY(e); if(this.overlay){ this.overlay.remove(); delete this.overlay; } var newSize; if(this.orientation == Ext.SplitBar.HORIZONTAL){ newSize = this.dragSpecs.startSize + (this.placement == Ext.SplitBar.LEFT ? endPoint[0] - this.dragSpecs.startPoint[0] : this.dragSpecs.startPoint[0] - endPoint[0] ); }else{ newSize = this.dragSpecs.startSize + (this.placement == Ext.SplitBar.TOP ? endPoint[1] - this.dragSpecs.startPoint[1] : this.dragSpecs.startPoint[1] - endPoint[1] ); } newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize); if(newSize != this.dragSpecs.startSize){ if(this.fireEvent('beforeapply', this, newSize) !== false){ this.adapter.setElementSize(this, newSize); this.fireEvent("moved", this, newSize); this.fireEvent("resize", this, newSize); } } }, getAdapter : function(){ return this.adapter; }, setAdapter : function(adapter){ this.adapter = adapter; this.adapter.init(this); }, getMinimumSize : function(){ return this.minSize; }, setMinimumSize : function(minSize){ this.minSize = minSize; }, getMaximumSize : function(){ return this.maxSize; }, setMaximumSize : function(maxSize){ this.maxSize = maxSize; }, setCurrentSize : function(size){ var oldAnimate = this.animate; this.animate = false; this.adapter.setElementSize(this, size); this.animate = oldAnimate; }, destroy : function(removeEl){ if(this.shim){ this.shim.remove(); } this.dd.unreg(); Ext.removeNode(this.proxy); if(removeEl){ this.el.remove(); } } }); Ext.SplitBar.createProxy = function(dir){ var proxy = new Ext.Element(document.createElement("div")); proxy.unselectable(); var cls = 'x-splitbar-proxy'; proxy.addClass(cls + ' ' + (dir == Ext.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v')); document.body.appendChild(proxy.dom); return proxy.dom; }; Ext.SplitBar.BasicLayoutAdapter = function(){ }; Ext.SplitBar.BasicLayoutAdapter.prototype = { init : function(s){ }, getElementSize : function(s){ if(s.orientation == Ext.SplitBar.HORIZONTAL){ return s.resizingEl.getWidth(); }else{ return s.resizingEl.getHeight(); } }, setElementSize : function(s, newSize, onComplete){ if(s.orientation == Ext.SplitBar.HORIZONTAL){ if(!s.animate){ s.resizingEl.setWidth(newSize); if(onComplete){ onComplete(s, newSize); } }else{ s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut'); } }else{ if(!s.animate){ s.resizingEl.setHeight(newSize); if(onComplete){ onComplete(s, newSize); } }else{ s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut'); } } } }; Ext.SplitBar.AbsoluteLayoutAdapter = function(container){ this.basic = new Ext.SplitBar.BasicLayoutAdapter(); this.container = Ext.get(container); }; Ext.SplitBar.AbsoluteLayoutAdapter.prototype = { init : function(s){ this.basic.init(s); }, getElementSize : function(s){ return this.basic.getElementSize(s); }, setElementSize : function(s, newSize, onComplete){ this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s])); }, moveSplitter : function(s){ var yes = Ext.SplitBar; switch(s.placement){ case yes.LEFT: s.el.setX(s.resizingEl.getRight()); break; case yes.RIGHT: s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px"); break; case yes.TOP: s.el.setY(s.resizingEl.getBottom()); break; case yes.BOTTOM: s.el.setY(s.resizingEl.getTop() - s.el.getHeight()); break; } } }; Ext.SplitBar.VERTICAL = 1; Ext.SplitBar.HORIZONTAL = 2; Ext.SplitBar.LEFT = 1; Ext.SplitBar.RIGHT = 2; Ext.SplitBar.TOP = 3; Ext.SplitBar.BOTTOM = 4; Ext.Container = Ext.extend(Ext.BoxComponent, { autoDestroy: true, defaultType: 'panel', initComponent : function(){ Ext.Container.superclass.initComponent.call(this); this.addEvents( 'afterlayout', 'beforeadd', 'beforeremove', 'add', 'remove' ); var items = this.items; if(items){ delete this.items; if(Ext.isArray(items)){ this.add.apply(this, items); }else{ this.add(items); } } }, initItems : function(){ if(!this.items){ this.items = new Ext.util.MixedCollection(false, this.getComponentId); this.getLayout(); } }, setLayout : function(layout){ if(this.layout && this.layout != layout){ this.layout.setContainer(null); } this.initItems(); this.layout = layout; layout.setContainer(this); }, render : function(){ Ext.Container.superclass.render.apply(this, arguments); if(this.layout){ if(typeof this.layout == 'string'){ this.layout = new Ext.Container.LAYOUTS[this.layout.toLowerCase()](this.layoutConfig); } this.setLayout(this.layout); if(this.activeItem !== undefined){ var item = this.activeItem; delete this.activeItem; this.layout.setActiveItem(item); return; } } if(!this.ownerCt){ this.doLayout(); } if(this.monitorResize === true){ Ext.EventManager.onWindowResize(this.doLayout, this, [false]); } }, getLayoutTarget : function(){ return this.el; }, getComponentId : function(comp){ return comp.itemId || comp.id; }, add : function(comp){ if(!this.items){ this.initItems(); } var a = arguments, len = a.length; if(len > 1){ for(var i = 0; i < len; i++) { this.add(a[i]); } return; } var c = this.lookupComponent(this.applyDefaults(comp)); var pos = this.items.length; if(this.fireEvent('beforeadd', this, c, pos) !== false && this.onBeforeAdd(c) !== false){ this.items.add(c); c.ownerCt = this; this.fireEvent('add', this, c, pos); } return c; }, insert : function(index, comp){ if(!this.items){ this.initItems(); } var a = arguments, len = a.length; if(len > 2){ for(var i = len-1; i >= 1; --i) { this.insert(index, a[i]); } return; } var c = this.lookupComponent(this.applyDefaults(comp)); if(c.ownerCt == this && this.items.indexOf(c) < index){ --index; } if(this.fireEvent('beforeadd', this, c, index) !== false && this.onBeforeAdd(c) !== false){ this.items.insert(index, c); c.ownerCt = this; this.fireEvent('add', this, c, index); } return c; }, applyDefaults : function(c){ if(this.defaults){ if(typeof c == 'string'){ c = Ext.ComponentMgr.get(c); Ext.apply(c, this.defaults); }else if(!c.events){ Ext.applyIf(c, this.defaults); }else{ Ext.apply(c, this.defaults); } } return c; }, onBeforeAdd : function(item){ if(item.ownerCt){ item.ownerCt.remove(item, false); } if(this.hideBorders === true){ item.border = (item.border === true); } }, remove : function(comp, autoDestroy){ var c = this.getComponent(comp); if(c && this.fireEvent('beforeremove', this, c) !== false){ this.items.remove(c); delete c.ownerCt; if(autoDestroy === true || (autoDestroy !== false && this.autoDestroy)){ c.destroy(); } if(this.layout && this.layout.activeItem == c){ delete this.layout.activeItem; } this.fireEvent('remove', this, c); } return c; }, getComponent : function(comp){ if(typeof comp == 'object'){ return comp; } return this.items.get(comp); }, lookupComponent : function(comp){ if(typeof comp == 'string'){ return Ext.ComponentMgr.get(comp); }else if(!comp.events){ return this.createComponent(comp); } return comp; }, createComponent : function(config){ return Ext.ComponentMgr.create(config, this.defaultType); }, doLayout : function(shallow){ if(this.rendered && this.layout){ this.layout.layout(); } if(shallow !== false && this.items){ var cs = this.items.items; for(var i = 0, len = cs.length; i < len; i++) { var c = cs[i]; if(c.doLayout){ c.doLayout(); } } } }, getLayout : function(){ if(!this.layout){ var layout = new Ext.layout.ContainerLayout(this.layoutConfig); this.setLayout(layout); } return this.layout; }, onDestroy : function(){ if(this.items){ var cs = this.items.items; for(var i = 0, len = cs.length; i < len; i++) { Ext.destroy(cs[i]); } } if(this.monitorResize){ Ext.EventManager.removeResizeListener(this.doLayout, this); } Ext.Container.superclass.onDestroy.call(this); }, bubble : function(fn, scope, args){ var p = this; while(p){ if(fn.apply(scope || p, args || [p]) === false){ break; } p = p.ownerCt; } }, cascade : function(fn, scope, args){ if(fn.apply(scope || this, args || [this]) !== false){ if(this.items){ var cs = this.items.items; for(var i = 0, len = cs.length; i < len; i++){ if(cs[i].cascade){ cs[i].cascade(fn, scope, args); }else{ fn.apply(scope || this, args || [cs[i]]); } } } } }, findById : function(id){ var m, ct = this; this.cascade(function(c){ if(ct != c && c.id === id){ m = c; return false; } }); return m || null; }, findByType : function(xtype){ return typeof xtype == 'function' ? this.findBy(function(c){ return c.constructor === xtype; }) : this.findBy(function(c){ return c.constructor.xtype === xtype; }); }, find : function(prop, value){ return this.findBy(function(c){ return c[prop] === value; }); }, findBy : function(fn, scope){ var m = [], ct = this; this.cascade(function(c){ if(ct != c && fn.call(scope || c, c, ct) === true){ m.push(c); } }); return m; } }); Ext.Container.LAYOUTS = {}; Ext.reg('container', Ext.Container); Ext.layout.ContainerLayout = function(config){ Ext.apply(this, config); }; Ext.layout.ContainerLayout.prototype = { monitorResize:false, activeItem : null, layout : function(){ var target = this.container.getLayoutTarget(); this.onLayout(this.container, target); this.container.fireEvent('afterlayout', this.container, this); }, onLayout : function(ct, target){ this.renderAll(ct, target); }, isValidParent : function(c, target){ var el = c.getPositionEl ? c.getPositionEl() : c.getEl(); return el.dom.parentNode == target.dom; }, renderAll : function(ct, target){ var items = ct.items.items; for(var i = 0, len = items.length; i < len; i++) { var c = items[i]; if(c && (!c.rendered || !this.isValidParent(c, target))){ this.renderItem(c, i, target); } } }, renderItem : function(c, position, target){ if(c && !c.rendered){ c.render(target, position); if(this.extraCls){ var t = c.getPositionEl ? c.getPositionEl() : c; t.addClass(this.extraCls); } if (this.renderHidden && c != this.activeItem) { c.hide(); } }else if(c && !this.isValidParent(c, target)){ if(this.extraCls){ c.addClass(this.extraCls); } if(typeof position == 'number'){ position = target.dom.childNodes[position]; } target.dom.insertBefore(c.getEl().dom, position || null); if (this.renderHidden && c != this.activeItem) { c.hide(); } } }, onResize: function(){ if(this.container.collapsed){ return; } var b = this.container.bufferResize; if(b){ if(!this.resizeTask){ this.resizeTask = new Ext.util.DelayedTask(this.layout, this); this.resizeBuffer = typeof b == 'number' ? b : 100; } this.resizeTask.delay(this.resizeBuffer); }else{ this.layout(); } }, setContainer : function(ct){ if(this.monitorResize && ct != this.container){ if(this.container){ this.container.un('resize', this.onResize, this); } if(ct){ ct.on('resize', this.onResize, this); } } this.container = ct; }, parseMargins : function(v){ var ms = v.split(' '); var len = ms.length; if(len == 1){ ms[1] = ms[0]; ms[2] = ms[0]; ms[3] = ms[0]; } if(len == 2){ ms[2] = ms[0]; ms[3] = ms[1]; } return { top:parseInt(ms[0], 10) || 0, right:parseInt(ms[1], 10) || 0, bottom:parseInt(ms[2], 10) || 0, left:parseInt(ms[3], 10) || 0 }; } }; Ext.Container.LAYOUTS['auto'] = Ext.layout.ContainerLayout; Ext.layout.FitLayout = Ext.extend(Ext.layout.ContainerLayout, { monitorResize:true, onLayout : function(ct, target){ Ext.layout.FitLayout.superclass.onLayout.call(this, ct, target); if(!this.container.collapsed){ this.setItemSize(this.activeItem || ct.items.itemAt(0), target.getStyleSize()); } }, setItemSize : function(item, size){ if(item && size.height > 0){ item.setSize(size); } } }); Ext.Container.LAYOUTS['fit'] = Ext.layout.FitLayout; Ext.layout.CardLayout = Ext.extend(Ext.layout.FitLayout, { deferredRender : false, renderHidden : true, setActiveItem : function(item){ item = this.container.getComponent(item); if(this.activeItem != item){ if(this.activeItem){ this.activeItem.hide(); } this.activeItem = item; item.show(); this.layout(); } }, renderAll : function(ct, target){ if(this.deferredRender){ this.renderItem(this.activeItem, undefined, target); }else{ Ext.layout.CardLayout.superclass.renderAll.call(this, ct, target); } } }); Ext.Container.LAYOUTS['card'] = Ext.layout.CardLayout; Ext.layout.AnchorLayout = Ext.extend(Ext.layout.ContainerLayout, { monitorResize:true, getAnchorViewSize : function(ct, target){ return target.dom == document.body ? target.getViewSize() : target.getStyleSize(); }, onLayout : function(ct, target){ Ext.layout.AnchorLayout.superclass.onLayout.call(this, ct, target); var size = this.getAnchorViewSize(ct, target); var w = size.width, h = size.height; if(w < 20 || h < 20){ return; } var aw, ah; if(ct.anchorSize){ if(typeof ct.anchorSize == 'number'){ aw = ct.anchorSize; }else{ aw = ct.anchorSize.width; ah = ct.anchorSize.height; } }else{ aw = ct.initialConfig.width; ah = ct.initialConfig.height; } var cs = ct.items.items, len = cs.length, i, c, a, cw, ch; for(i = 0; i < len; i++){ c = cs[i]; if(c.anchor){ a = c.anchorSpec; if(!a){ var vs = c.anchor.split(' '); c.anchorSpec = a = { right: this.parseAnchor(vs[0], c.initialConfig.width, aw), bottom: this.parseAnchor(vs[1], c.initialConfig.height, ah) }; } cw = a.right ? this.adjustWidthAnchor(a.right(w), c) : undefined; ch = a.bottom ? this.adjustHeightAnchor(a.bottom(h), c) : undefined; if(cw || ch){ c.setSize(cw || undefined, ch || undefined); } } } }, parseAnchor : function(a, start, cstart){ if(a && a != 'none'){ var last; if(/^(r|right|b|bottom)$/i.test(a)){ var diff = cstart - start; return function(v){ if(v !== last){ last = v; return v - diff; } } }else if(a.indexOf('%') != -1){ var ratio = parseFloat(a.replace('%', ''))*.01; return function(v){ if(v !== last){ last = v; return Math.floor(v*ratio); } } }else{ a = parseInt(a, 10); if(!isNaN(a)){ return function(v){ if(v !== last){ last = v; return v + a; } } } } } return false; }, adjustWidthAnchor : function(value, comp){ return value; }, adjustHeightAnchor : function(value, comp){ return value; } }); Ext.Container.LAYOUTS['anchor'] = Ext.layout.AnchorLayout; Ext.layout.ColumnLayout = Ext.extend(Ext.layout.ContainerLayout, { monitorResize:true, extraCls: 'x-column', scrollOffset : 0, isValidParent : function(c, target){ return c.getEl().dom.parentNode == this.innerCt.dom; }, onLayout : function(ct, target){ var cs = ct.items.items, len = cs.length, c, i; if(!this.innerCt){ target.addClass('x-column-layout-ct'); this.innerCt = target.createChild({cls:'x-column-inner'}); this.innerCt.createChild({cls:'x-clear'}); } this.renderAll(ct, this.innerCt); var size = target.getViewSize(); if(size.width < 1 && size.height < 1){ return; } var w = size.width - target.getPadding('lr') - this.scrollOffset, h = size.height - target.getPadding('tb'), pw = w; this.innerCt.setWidth(w); for(i = 0; i < len; i++){ c = cs[i]; if(!c.columnWidth){ pw -= (c.getSize().width + c.getEl().getMargins('lr')); } } pw = pw < 0 ? 0 : pw; for(i = 0; i < len; i++){ c = cs[i]; if(c.columnWidth){ c.setSize(Math.floor(c.columnWidth*pw) - c.getEl().getMargins('lr')); } } } }); Ext.Container.LAYOUTS['column'] = Ext.layout.ColumnLayout; Ext.layout.BorderLayout = Ext.extend(Ext.layout.ContainerLayout, { monitorResize:true, rendered : false, onLayout : function(ct, target){ var collapsed; if(!this.rendered){ target.position(); target.addClass('x-border-layout-ct'); var items = ct.items.items; collapsed = []; for(var i = 0, len = items.length; i < len; i++) { var c = items[i]; var pos = c.region; if(c.collapsed){ collapsed.push(c); } c.collapsed = false; if(!c.rendered){ c.cls = c.cls ? c.cls +' x-border-panel' : 'x-border-panel'; c.render(target, i); } this[pos] = pos != 'center' && c.split ? new Ext.layout.BorderLayout.SplitRegion(this, c.initialConfig, pos) : new Ext.layout.BorderLayout.Region(this, c.initialConfig, pos); this[pos].render(target, c); } this.rendered = true; } var size = target.getViewSize(); if(size.width < 20 || size.height < 20){ if(collapsed){ this.restoreCollapsed = collapsed; } return; }else if(this.restoreCollapsed){ collapsed = this.restoreCollapsed; delete this.restoreCollapsed; } var w = size.width, h = size.height; var centerW = w, centerH = h, centerY = 0, centerX = 0; var n = this.north, s = this.south, west = this.west, e = this.east, c = this.center; if(!c){ throw 'No center region defined in BorderLayout ' + ct.id; } if(n && n.isVisible()){ var b = n.getSize(); var m = n.getMargins(); b.width = w - (m.left+m.right); b.x = m.left; b.y = m.top; centerY = b.height + b.y + m.bottom; centerH -= centerY; n.applyLayout(b); } if(s && s.isVisible()){ var b = s.getSize(); var m = s.getMargins(); b.width = w - (m.left+m.right); b.x = m.left; var totalHeight = (b.height + m.top + m.bottom); b.y = h - totalHeight + m.top; centerH -= totalHeight; s.applyLayout(b); } if(west && west.isVisible()){ var b = west.getSize(); var m = west.getMargins(); b.height = centerH - (m.top+m.bottom); b.x = m.left; b.y = centerY + m.top; var totalWidth = (b.width + m.left + m.right); centerX += totalWidth; centerW -= totalWidth; west.applyLayout(b); } if(e && e.isVisible()){ var b = e.getSize(); var m = e.getMargins(); b.height = centerH - (m.top+m.bottom); var totalWidth = (b.width + m.left + m.right); b.x = w - totalWidth + m.left; b.y = centerY + m.top; centerW -= totalWidth; e.applyLayout(b); } var m = c.getMargins(); var centerBox = { x: centerX + m.left, y: centerY + m.top, width: centerW - (m.left+m.right), height: centerH - (m.top+m.bottom) }; c.applyLayout(centerBox); if(collapsed){ for(var i = 0, len = collapsed.length; i < len; i++){ collapsed[i].collapse(false); } } if(Ext.isIE && Ext.isStrict){ target.repaint(); } } }); Ext.layout.BorderLayout.Region = function(layout, config, pos){ Ext.apply(this, config); this.layout = layout; this.position = pos; this.state = {}; if(typeof this.margins == 'string'){ this.margins = this.layout.parseMargins(this.margins); } this.margins = Ext.applyIf(this.margins || {}, this.defaultMargins); if(this.collapsible){ if(typeof this.cmargins == 'string'){ this.cmargins = this.layout.parseMargins(this.cmargins); } if(this.collapseMode == 'mini' && !this.cmargins){ this.cmargins = {left:0,top:0,right:0,bottom:0}; }else{ this.cmargins = Ext.applyIf(this.cmargins || {}, pos == 'north' || pos == 'south' ? this.defaultNSCMargins : this.defaultEWCMargins); } } }; Ext.layout.BorderLayout.Region.prototype = { collapsible : false, split:false, floatable: true, minWidth:50, minHeight:50, defaultMargins : {left:0,top:0,right:0,bottom:0}, defaultNSCMargins : {left:5,top:5,right:5,bottom:5}, defaultEWCMargins : {left:5,top:0,right:5,bottom:0}, isCollapsed : false, render : function(ct, p){ this.panel = p; p.el.enableDisplayMode(); this.targetEl = ct; this.el = p.el; var gs = p.getState, ps = this.position; p.getState = function(){ return Ext.apply(gs.call(p) || {}, this.state); }.createDelegate(this); if(ps != 'center'){ p.allowQueuedExpand = false; p.on({ beforecollapse: this.beforeCollapse, collapse: this.onCollapse, beforeexpand: this.beforeExpand, expand: this.onExpand, hide: this.onHide, show: this.onShow, scope: this }); if(this.collapsible){ p.collapseEl = 'el'; p.slideAnchor = this.getSlideAnchor(); } if(p.tools && p.tools.toggle){ p.tools.toggle.addClass('x-tool-collapse-'+ps); p.tools.toggle.addClassOnOver('x-tool-collapse-'+ps+'-over'); } } }, getCollapsedEl : function(){ if(!this.collapsedEl){ if(!this.toolTemplate){ var tt = new Ext.Template( '<div class="x-tool x-tool-{id}">&#160;</div>' ); tt.disableFormats = true; tt.compile(); Ext.layout.BorderLayout.Region.prototype.toolTemplate = tt; } this.collapsedEl = this.targetEl.createChild({ cls: "x-layout-collapsed x-layout-collapsed-"+this.position, id: this.panel.id + '-xcollapsed' }); this.collapsedEl.enableDisplayMode('block'); if(this.collapseMode == 'mini'){ this.collapsedEl.addClass('x-layout-cmini-'+this.position); this.miniCollapsedEl = this.collapsedEl.createChild({ cls: "x-layout-mini x-layout-mini-"+this.position, html: "&#160;" }); this.miniCollapsedEl.addClassOnOver('x-layout-mini-over'); this.collapsedEl.addClassOnOver("x-layout-collapsed-over"); this.collapsedEl.on('click', this.onExpandClick, this, {stopEvent:true}); }else { var t = this.toolTemplate.append( this.collapsedEl.dom, {id:'expand-'+this.position}, true); t.addClassOnOver('x-tool-expand-'+this.position+'-over'); t.on('click', this.onExpandClick, this, {stopEvent:true}); if(this.floatable !== false){ this.collapsedEl.addClassOnOver("x-layout-collapsed-over"); this.collapsedEl.on("click", this.collapseClick, this); } } } return this.collapsedEl; }, onExpandClick : function(e){ if(this.isSlid){ this.afterSlideIn(); this.panel.expand(false); }else{ this.panel.expand(); } }, onCollapseClick : function(e){ this.panel.collapse(); }, beforeCollapse : function(p, animate){ this.lastAnim = animate; if(this.splitEl){ this.splitEl.hide(); } this.getCollapsedEl().show(); this.panel.el.setStyle('z-index', 100); this.isCollapsed = true; this.layout.layout(); }, onCollapse : function(animate){ this.panel.el.setStyle('z-index', 1); if(this.lastAnim === false || this.panel.animCollapse === false){ this.getCollapsedEl().dom.style.visibility = 'visible'; }else{ this.getCollapsedEl().slideIn(this.panel.slideAnchor, {duration:.2}); } this.state.collapsed = true; this.panel.saveState(); }, beforeExpand : function(animate){ var c = this.getCollapsedEl(); this.el.show(); if(this.position == 'east' || this.position == 'west'){ this.panel.setSize(undefined, c.getHeight()); }else{ this.panel.setSize(c.getWidth(), undefined); } c.hide(); c.dom.style.visibility = 'hidden'; this.panel.el.setStyle('z-index', 100); }, onExpand : function(){ this.isCollapsed = false; if(this.splitEl){ this.splitEl.show(); } this.layout.layout(); this.panel.el.setStyle('z-index', 1); this.state.collapsed = false; this.panel.saveState(); }, collapseClick : function(e){ if(this.isSlid){ e.stopPropagation(); this.slideIn(); }else{ e.stopPropagation(); this.slideOut(); } }, onHide : function(){ if(this.isCollapsed){ this.getCollapsedEl().hide(); }else if(this.splitEl){ this.splitEl.hide(); } }, onShow : function(){ if(this.isCollapsed){ this.getCollapsedEl().show(); }else if(this.splitEl){ this.splitEl.show(); } }, isVisible : function(){ return !this.panel.hidden; }, getMargins : function(){ return this.isCollapsed && this.cmargins ? this.cmargins : this.margins; }, getSize : function(){ return this.isCollapsed ? this.getCollapsedEl().getSize() : this.panel.getSize(); }, setPanel : function(panel){ this.panel = panel; }, getMinWidth: function(){ return this.minWidth; }, getMinHeight: function(){ return this.minHeight; }, applyLayoutCollapsed : function(box){ var ce = this.getCollapsedEl(); ce.setLeftTop(box.x, box.y); ce.setSize(box.width, box.height); }, applyLayout : function(box){ if(this.isCollapsed){ this.applyLayoutCollapsed(box); }else{ this.panel.setPosition(box.x, box.y); this.panel.setSize(box.width, box.height); } }, beforeSlide: function(){ this.panel.beforeEffect(); }, afterSlide : function(){ this.panel.afterEffect(); }, initAutoHide : function(){ if(this.autoHide !== false){ if(!this.autoHideHd){ var st = new Ext.util.DelayedTask(this.slideIn, this); this.autoHideHd = { "mouseout": function(e){ if(!e.within(this.el, true)){ st.delay(500); } }, "mouseover" : function(e){ st.cancel(); }, scope : this }; } this.el.on(this.autoHideHd); } }, clearAutoHide : function(){ if(this.autoHide !== false){ this.el.un("mouseout", this.autoHideHd.mouseout); this.el.un("mouseover", this.autoHideHd.mouseover); } }, clearMonitor : function(){ Ext.getDoc().un("click", this.slideInIf, this); }, slideOut : function(){ if(this.isSlid || this.el.hasActiveFx()){ return; } this.isSlid = true; var ts = this.panel.tools; if(ts && ts.toggle){ ts.toggle.hide(); } this.el.show(); if(this.position == 'east' || this.position == 'west'){ this.panel.setSize(undefined, this.collapsedEl.getHeight()); }else{ this.panel.setSize(this.collapsedEl.getWidth(), undefined); } this.restoreLT = [this.el.dom.style.left, this.el.dom.style.top]; this.el.alignTo(this.collapsedEl, this.getCollapseAnchor()); this.el.setStyle("z-index", 102); if(this.animFloat !== false){ this.beforeSlide(); this.el.slideIn(this.getSlideAnchor(), { callback: function(){ this.afterSlide(); this.initAutoHide(); Ext.getDoc().on("click", this.slideInIf, this); }, scope: this, block: true }); }else{ this.initAutoHide(); Ext.getDoc().on("click", this.slideInIf, this); } }, afterSlideIn : function(){ this.clearAutoHide(); this.isSlid = false; this.clearMonitor(); this.el.setStyle("z-index", ""); this.el.dom.style.left = this.restoreLT[0]; this.el.dom.style.top = this.restoreLT[1]; var ts = this.panel.tools; if(ts && ts.toggle){ ts.toggle.show(); } }, slideIn : function(cb){ if(!this.isSlid || this.el.hasActiveFx()){ Ext.callback(cb); return; } this.isSlid = false; if(this.animFloat !== false){ this.beforeSlide(); this.el.slideOut(this.getSlideAnchor(), { callback: function(){ this.el.hide(); this.afterSlide(); this.afterSlideIn(); Ext.callback(cb); }, scope: this, block: true }); }else{ this.el.hide(); this.afterSlideIn(); } }, slideInIf : function(e){ if(!e.within(this.el)){ this.slideIn(); } }, anchors : { "west" : "left", "east" : "right", "north" : "top", "south" : "bottom" }, sanchors : { "west" : "l", "east" : "r", "north" : "t", "south" : "b" }, canchors : { "west" : "tl-tr", "east" : "tr-tl", "north" : "tl-bl", "south" : "bl-tl" }, getAnchor : function(){ return this.anchors[this.position]; }, getCollapseAnchor : function(){ return this.canchors[this.position]; }, getSlideAnchor : function(){ return this.sanchors[this.position]; }, getAlignAdj : function(){ var cm = this.cmargins; switch(this.position){ case "west": return [0, 0]; break; case "east": return [0, 0]; break; case "north": return [0, 0]; break; case "south": return [0, 0]; break; } }, getExpandAdj : function(){ var c = this.collapsedEl, cm = this.cmargins; switch(this.position){ case "west": return [-(cm.right+c.getWidth()+cm.left), 0]; break; case "east": return [cm.right+c.getWidth()+cm.left, 0]; break; case "north": return [0, -(cm.top+cm.bottom+c.getHeight())]; break; case "south": return [0, cm.top+cm.bottom+c.getHeight()]; break; } } }; Ext.layout.BorderLayout.SplitRegion = function(layout, config, pos){ Ext.layout.BorderLayout.SplitRegion.superclass.constructor.call(this, layout, config, pos); this.applyLayout = this.applyFns[pos]; }; Ext.extend(Ext.layout.BorderLayout.SplitRegion, Ext.layout.BorderLayout.Region, { splitTip : "Drag to resize.", collapsibleSplitTip : "Drag to resize. Double click to hide.", useSplitTips : false, splitSettings : { north : { orientation: Ext.SplitBar.VERTICAL, placement: Ext.SplitBar.TOP, maxFn : 'getVMaxSize', minProp: 'minHeight', maxProp: 'maxHeight' }, south : { orientation: Ext.SplitBar.VERTICAL, placement: Ext.SplitBar.BOTTOM, maxFn : 'getVMaxSize', minProp: 'minHeight', maxProp: 'maxHeight' }, east : { orientation: Ext.SplitBar.HORIZONTAL, placement: Ext.SplitBar.RIGHT, maxFn : 'getHMaxSize', minProp: 'minWidth', maxProp: 'maxWidth' }, west : { orientation: Ext.SplitBar.HORIZONTAL, placement: Ext.SplitBar.LEFT, maxFn : 'getHMaxSize', minProp: 'minWidth', maxProp: 'maxWidth' } }, applyFns : { west : function(box){ if(this.isCollapsed){ return this.applyLayoutCollapsed(box); } var sd = this.splitEl.dom, s = sd.style; this.panel.setPosition(box.x, box.y); var sw = sd.offsetWidth; s.left = (box.x+box.width-sw)+'px'; s.top = (box.y)+'px'; s.height = Math.max(0, box.height)+'px'; this.panel.setSize(box.width-sw, box.height); }, east : function(box){ if(this.isCollapsed){ return this.applyLayoutCollapsed(box); } var sd = this.splitEl.dom, s = sd.style; var sw = sd.offsetWidth; this.panel.setPosition(box.x+sw, box.y); s.left = (box.x)+'px'; s.top = (box.y)+'px'; s.height = Math.max(0, box.height)+'px'; this.panel.setSize(box.width-sw, box.height); }, north : function(box){ if(this.isCollapsed){ return this.applyLayoutCollapsed(box); } var sd = this.splitEl.dom, s = sd.style; var sh = sd.offsetHeight; this.panel.setPosition(box.x, box.y); s.left = (box.x)+'px'; s.top = (box.y+box.height-sh)+'px'; s.width = Math.max(0, box.width)+'px'; this.panel.setSize(box.width, box.height-sh); }, south : function(box){ if(this.isCollapsed){ return this.applyLayoutCollapsed(box); } var sd = this.splitEl.dom, s = sd.style; var sh = sd.offsetHeight; this.panel.setPosition(box.x, box.y+sh); s.left = (box.x)+'px'; s.top = (box.y)+'px'; s.width = Math.max(0, box.width)+'px'; this.panel.setSize(box.width, box.height-sh); } }, render : function(ct, p){ Ext.layout.BorderLayout.SplitRegion.superclass.render.call(this, ct, p); var ps = this.position; this.splitEl = ct.createChild({ cls: "x-layout-split x-layout-split-"+ps, html: "&#160;", id: this.panel.id + '-xsplit' }); if(this.collapseMode == 'mini'){ this.miniSplitEl = this.splitEl.createChild({ cls: "x-layout-mini x-layout-mini-"+ps, html: "&#160;" }); this.miniSplitEl.addClassOnOver('x-layout-mini-over'); this.miniSplitEl.on('click', this.onCollapseClick, this, {stopEvent:true}); } var s = this.splitSettings[ps]; this.split = new Ext.SplitBar(this.splitEl.dom, p.el, s.orientation); this.split.placement = s.placement; this.split.getMaximumSize = this[s.maxFn].createDelegate(this); this.split.minSize = this.minSize || this[s.minProp]; this.split.on("beforeapply", this.onSplitMove, this); this.split.useShim = this.useShim === true; this.maxSize = this.maxSize || this[s.maxProp]; if(p.hidden){ this.splitEl.hide(); } if(this.useSplitTips){ this.splitEl.dom.title = this.collapsible ? this.collapsibleSplitTip : this.splitTip; } if(this.collapsible){ this.splitEl.on("dblclick", this.onCollapseClick, this); } }, getSize : function(){ if(this.isCollapsed){ return this.collapsedEl.getSize(); } var s = this.panel.getSize(); if(this.position == 'north' || this.position == 'south'){ s.height += this.splitEl.dom.offsetHeight; }else{ s.width += this.splitEl.dom.offsetWidth; } return s; }, getHMaxSize : function(){ var cmax = this.maxSize || 10000; var center = this.layout.center; return Math.min(cmax, (this.el.getWidth()+center.el.getWidth())-center.getMinWidth()); }, getVMaxSize : function(){ var cmax = this.maxSize || 10000; var center = this.layout.center; return Math.min(cmax, (this.el.getHeight()+center.el.getHeight())-center.getMinHeight()); }, onSplitMove : function(split, newSize){ var s = this.panel.getSize(); this.lastSplitSize = newSize; if(this.position == 'north' || this.position == 'south'){ this.panel.setSize(s.width, newSize); this.state.height = newSize; }else{ this.panel.setSize(newSize, s.height); this.state.width = newSize; } this.layout.layout(); this.panel.saveState(); return false; }, getSplitBar : function(){ return this.split; } }); Ext.Container.LAYOUTS['border'] = Ext.layout.BorderLayout; Ext.layout.FormLayout = Ext.extend(Ext.layout.AnchorLayout, { labelSeparator : ':', getAnchorViewSize : function(ct, target){ return ct.body.getStyleSize(); }, setContainer : function(ct){ Ext.layout.FormLayout.superclass.setContainer.call(this, ct); if(ct.labelAlign){ ct.addClass('x-form-label-'+ct.labelAlign); } if(ct.hideLabels){ this.labelStyle = "display:none"; this.elementStyle = "padding-left:0;"; this.labelAdjust = 0; }else{ this.labelSeparator = ct.labelSeparator || this.labelSeparator; ct.labelWidth = ct.labelWidth || 100; if(typeof ct.labelWidth == 'number'){ var pad = (typeof ct.labelPad == 'number' ? ct.labelPad : 5); this.labelAdjust = ct.labelWidth+pad; this.labelStyle = "width:"+ct.labelWidth+"px;"; this.elementStyle = "padding-left:"+(ct.labelWidth+pad)+'px'; } if(ct.labelAlign == 'top'){ this.labelStyle = "width:auto;"; this.labelAdjust = 0; this.elementStyle = "padding-left:0;"; } } if(!this.fieldTpl){ var t = new Ext.Template( '<div class="x-form-item {5}" tabIndex="-1">', '<label for="{0}" style="{2}" class="x-form-item-label">{1}{4}</label>', '<div class="x-form-element" id="x-form-el-{0}" style="{3}">', '</div><div class="{6}"></div>', '</div>' ); t.disableFormats = true; t.compile(); Ext.layout.FormLayout.prototype.fieldTpl = t; } }, renderItem : function(c, position, target){ if(c && !c.rendered && c.isFormField && c.inputType != 'hidden'){ var args = [ c.id, c.fieldLabel, c.labelStyle||this.labelStyle||'', this.elementStyle||'', typeof c.labelSeparator == 'undefined' ? this.labelSeparator : c.labelSeparator, (c.itemCls||this.container.itemCls||'') + (c.hideLabel ? ' x-hide-label' : ''), c.clearCls || 'x-form-clear-left' ]; if(typeof position == 'number'){ position = target.dom.childNodes[position] || null; } if(position){ this.fieldTpl.insertBefore(position, args); }else{ this.fieldTpl.append(target, args); } c.render('x-form-el-'+c.id); }else { Ext.layout.FormLayout.superclass.renderItem.apply(this, arguments); } }, adjustWidthAnchor : function(value, comp){ return value - (comp.isFormField ? (comp.hideLabel ? 0 : this.labelAdjust) : 0); }, isValidParent : function(c, target){ return true; } }); Ext.Container.LAYOUTS['form'] = Ext.layout.FormLayout; Ext.layout.Accordion = Ext.extend(Ext.layout.FitLayout, { fill : true, autoWidth : true, titleCollapse : true, hideCollapseTool : false, collapseFirst : false, animate : false, sequence : false, activeOnTop : false, renderItem : function(c){ if(this.animate === false){ c.animCollapse = false; } c.collapsible = true; if(this.autoWidth){ c.autoWidth = true; } if(this.titleCollapse){ c.titleCollapse = true; } if(this.hideCollapseTool){ c.hideCollapseTool = true; } if(this.collapseFirst !== undefined){ c.collapseFirst = this.collapseFirst; } if(!this.activeItem && !c.collapsed){ this.activeItem = c; }else if(this.activeItem){ c.collapsed = true; } Ext.layout.Accordion.superclass.renderItem.apply(this, arguments); c.header.addClass('x-accordion-hd'); c.on('beforeexpand', this.beforeExpand, this); }, beforeExpand : function(p, anim){ var ai = this.activeItem; if(ai){ if(this.sequence){ delete this.activeItem; ai.collapse({callback:function(){ p.expand(anim || true); }, scope: this}); return false; }else{ ai.collapse(this.animate); } } this.activeItem = p; if(this.activeOnTop){ p.el.dom.parentNode.insertBefore(p.el.dom, p.el.dom.parentNode.firstChild); } this.layout(); }, setItemSize : function(item, size){ if(this.fill && item){ var items = this.container.items.items; var hh = 0; for(var i = 0, len = items.length; i < len; i++){ var p = items[i]; if(p != item){ hh += (p.getSize().height - p.bwrap.getHeight()); } } size.height -= hh; item.setSize(size); } } }); Ext.Container.LAYOUTS['accordion'] = Ext.layout.Accordion; Ext.layout.TableLayout = Ext.extend(Ext.layout.ContainerLayout, { monitorResize:false, setContainer : function(ct){ Ext.layout.TableLayout.superclass.setContainer.call(this, ct); this.currentRow = 0; this.currentColumn = 0; this.cells = []; }, onLayout : function(ct, target){ var cs = ct.items.items, len = cs.length, c, i; if(!this.table){ target.addClass('x-table-layout-ct'); this.table = target.createChild( {tag:'table', cls:'x-table-layout', cellspacing: 0, cn: {tag: 'tbody'}}, null, true); this.renderAll(ct, target); } }, getRow : function(index){ var row = this.table.tBodies[0].childNodes[index]; if(!row){ row = document.createElement('tr'); this.table.tBodies[0].appendChild(row); } return row; }, getNextCell : function(c){ var cell = this.getNextNonSpan(this.currentColumn, this.currentRow); var curCol = this.currentColumn = cell[0], curRow = this.currentRow = cell[1]; for(var rowIndex = curRow; rowIndex < curRow + (c.rowspan || 1); rowIndex++){ if(!this.cells[rowIndex]){ this.cells[rowIndex] = []; } for(var colIndex = curCol; colIndex < curCol + (c.colspan || 1); colIndex++){ this.cells[rowIndex][colIndex] = true; } } var td = document.createElement('td'); if(c.cellId){ td.id = c.cellId; } var cls = 'x-table-layout-cell'; if(c.cellCls){ cls += ' ' + c.cellCls; } td.className = cls; if(c.colspan){ td.colSpan = c.colspan; } if(c.rowspan){ td.rowSpan = c.rowspan; } this.getRow(curRow).appendChild(td); return td; }, getNextNonSpan: function(colIndex, rowIndex){ var cols = this.columns; while((cols && colIndex >= cols) || (this.cells[rowIndex] && this.cells[rowIndex][colIndex])) { if(cols && colIndex >= cols){ rowIndex++; colIndex = 0; }else{ colIndex++; } } return [colIndex, rowIndex]; }, renderItem : function(c, position, target){ if(c && !c.rendered){ c.render(this.getNextCell(c)); } }, isValidParent : function(c, target){ return true; } }); Ext.Container.LAYOUTS['table'] = Ext.layout.TableLayout; Ext.layout.AbsoluteLayout = Ext.extend(Ext.layout.AnchorLayout, { extraCls: 'x-abs-layout-item', isForm: false, setContainer : function(ct){ Ext.layout.AbsoluteLayout.superclass.setContainer.call(this, ct); if(ct.isXType('form')){ this.isForm = true; } }, onLayout : function(ct, target){ if(this.isForm){ ct.body.position(); } else { target.position(); } Ext.layout.AbsoluteLayout.superclass.onLayout.call(this, ct, target); }, getAnchorViewSize : function(ct, target){ return this.isForm ? ct.body.getStyleSize() : Ext.layout.AbsoluteLayout.superclass.getAnchorViewSize.call(this, ct, target); }, isValidParent : function(c, target){ return this.isForm ? true : Ext.layout.AbsoluteLayout.superclass.isValidParent.call(this, c, target); }, adjustWidthAnchor : function(value, comp){ return value ? value - comp.getPosition(true)[0] : value; }, adjustHeightAnchor : function(value, comp){ return value ? value - comp.getPosition(true)[1] : value; } }); Ext.Container.LAYOUTS['absolute'] = Ext.layout.AbsoluteLayout; Ext.Viewport = Ext.extend(Ext.Container, { initComponent : function() { Ext.Viewport.superclass.initComponent.call(this); document.getElementsByTagName('html')[0].className += ' x-viewport'; this.el = Ext.getBody(); this.el.setHeight = Ext.emptyFn; this.el.setWidth = Ext.emptyFn; this.el.setSize = Ext.emptyFn; this.el.dom.scroll = 'no'; this.allowDomMove = false; this.autoWidth = true; this.autoHeight = true; Ext.EventManager.onWindowResize(this.fireResize, this); this.renderTo = this.el; }, fireResize : function(w, h){ this.fireEvent('resize', this, w, h, w, h); } }); Ext.reg('viewport', Ext.Viewport); Ext.Panel = Ext.extend(Ext.Container, { baseCls : 'x-panel', collapsedCls : 'x-panel-collapsed', maskDisabled: true, animCollapse: Ext.enableFx, headerAsText: true, buttonAlign: 'right', collapsed : false, collapseFirst: true, minButtonWidth:75, elements : 'body', toolTarget : 'header', collapseEl : 'bwrap', slideAnchor : 't', deferHeight: true, expandDefaults: { duration:.25 }, collapseDefaults: { duration:.25 }, initComponent : function(){ Ext.Panel.superclass.initComponent.call(this); this.addEvents( 'bodyresize', 'titlechange', 'collapse', 'expand', 'beforecollapse', 'beforeexpand', 'beforeclose', 'close', 'activate', 'deactivate' ); if(this.tbar){ this.elements += ',tbar'; if(typeof this.tbar == 'object'){ this.topToolbar = this.tbar; } delete this.tbar; } if(this.bbar){ this.elements += ',bbar'; if(typeof this.bbar == 'object'){ this.bottomToolbar = this.bbar; } delete this.bbar; } if(this.header === true){ this.elements += ',header'; delete this.header; }else if(this.title && this.header !== false){ this.elements += ',header'; } if(this.footer === true){ this.elements += ',footer'; delete this.footer; } if(this.buttons){ var btns = this.buttons; this.buttons = []; for(var i = 0, len = btns.length; i < len; i++) { if(btns[i].render){ this.buttons.push(btns[i]); }else{ this.addButton(btns[i]); } } } if(this.autoLoad){ this.on('render', this.doAutoLoad, this, {delay:10}); } }, createElement : function(name, pnode){ if(this[name]){ pnode.appendChild(this[name].dom); return; } if(name === 'bwrap' || this.elements.indexOf(name) != -1){ if(this[name+'Cfg']){ this[name] = Ext.fly(pnode).createChild(this[name+'Cfg']); }else{ var el = document.createElement('div'); el.className = this[name+'Cls']; this[name] = Ext.get(pnode.appendChild(el)); } } }, onRender : function(ct, position){ Ext.Panel.superclass.onRender.call(this, ct, position); this.createClasses(); if(this.el){ this.el.addClass(this.baseCls); this.header = this.el.down('.'+this.headerCls); this.bwrap = this.el.down('.'+this.bwrapCls); var cp = this.bwrap ? this.bwrap : this.el; this.tbar = cp.down('.'+this.tbarCls); this.body = cp.down('.'+this.bodyCls); this.bbar = cp.down('.'+this.bbarCls); this.footer = cp.down('.'+this.footerCls); this.fromMarkup = true; }else{ this.el = ct.createChild({ id: this.id, cls: this.baseCls }, position); } var el = this.el, d = el.dom; if(this.cls){ this.el.addClass(this.cls); } if(this.buttons){ this.elements += ',footer'; } if(this.frame){ el.insertHtml('afterBegin', String.format(Ext.Element.boxMarkup, this.baseCls)); this.createElement('header', d.firstChild.firstChild.firstChild); this.createElement('bwrap', d); var bw = this.bwrap.dom; var ml = d.childNodes[1], bl = d.childNodes[2]; bw.appendChild(ml); bw.appendChild(bl); var mc = bw.firstChild.firstChild.firstChild; this.createElement('tbar', mc); this.createElement('body', mc); this.createElement('bbar', mc); this.createElement('footer', bw.lastChild.firstChild.firstChild); if(!this.footer){ this.bwrap.dom.lastChild.className += ' x-panel-nofooter'; } }else{ this.createElement('header', d); this.createElement('bwrap', d); var bw = this.bwrap.dom; this.createElement('tbar', bw); this.createElement('body', bw); this.createElement('bbar', bw); this.createElement('footer', bw); if(!this.header){ this.body.addClass(this.bodyCls + '-noheader'); if(this.tbar){ this.tbar.addClass(this.tbarCls + '-noheader'); } } } if(this.border === false){ this.el.addClass(this.baseCls + '-noborder'); this.body.addClass(this.bodyCls + '-noborder'); if(this.header){ this.header.addClass(this.headerCls + '-noborder'); } if(this.footer){ this.footer.addClass(this.footerCls + '-noborder'); } if(this.tbar){ this.tbar.addClass(this.tbarCls + '-noborder'); } if(this.bbar){ this.bbar.addClass(this.bbarCls + '-noborder'); } } if(this.bodyBorder === false){ this.body.addClass(this.bodyCls + '-noborder'); } if(this.bodyStyle){ this.body.applyStyles(this.bodyStyle); } this.bwrap.enableDisplayMode('block'); if(this.header){ this.header.unselectable(); if(this.headerAsText){ this.header.dom.innerHTML = '<span class="' + this.headerTextCls + '">'+this.header.dom.innerHTML+'</span>'; if(this.iconCls){ this.setIconClass(this.iconCls); } } } if(this.floating){ this.makeFloating(this.floating); } if(this.collapsible){ this.tools = this.tools ? this.tools.slice(0) : []; if(!this.hideCollapseTool){ this.tools[this.collapseFirst?'unshift':'push']({ id: 'toggle', handler : this.toggleCollapse, scope: this }); } if(this.titleCollapse && this.header){ this.header.on('click', this.toggleCollapse, this); this.header.setStyle('cursor', 'pointer'); } } if(this.tools){ var ts = this.tools; this.tools = {}; this.addTool.apply(this, ts); }else{ this.tools = {}; } if(this.buttons && this.buttons.length > 0){ var tb = this.footer.createChild({cls:'x-panel-btns-ct', cn: { cls:"x-panel-btns x-panel-btns-"+this.buttonAlign, html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>' }}, null, true); var tr = tb.getElementsByTagName('tr')[0]; for(var i = 0, len = this.buttons.length; i < len; i++) { var b = this.buttons[i]; var td = document.createElement('td'); td.className = 'x-panel-btn-td'; b.render(tr.appendChild(td)); } } if(this.tbar && this.topToolbar){ if(Ext.isArray(this.topToolbar)){ this.topToolbar = new Ext.Toolbar(this.topToolbar); } this.topToolbar.render(this.tbar); } if(this.bbar && this.bottomToolbar){ if(Ext.isArray(this.bottomToolbar)){ this.bottomToolbar = new Ext.Toolbar(this.bottomToolbar); } this.bottomToolbar.render(this.bbar); } }, setIconClass : function(cls){ var old = this.iconCls; this.iconCls = cls; if(this.rendered && this.header){ if(this.frame){ this.header.addClass('x-panel-icon'); this.header.replaceClass(old, this.iconCls); }else{ var hd = this.header.dom; var img = hd.firstChild && String(hd.firstChild.tagName).toLowerCase() == 'img' ? hd.firstChild : null; if(img){ Ext.fly(img).replaceClass(old, this.iconCls); }else{ Ext.DomHelper.insertBefore(hd.firstChild, { tag:'img', src: Ext.BLANK_IMAGE_URL, cls:'x-panel-inline-icon '+this.iconCls }); } } } }, makeFloating : function(cfg){ this.floating = true; this.el = new Ext.Layer( typeof cfg == 'object' ? cfg : { shadow: this.shadow !== undefined ? this.shadow : 'sides', shadowOffset: this.shadowOffset, constrain:false, shim: this.shim === false ? false : undefined }, this.el ); }, getTopToolbar : function(){ return this.topToolbar; }, getBottomToolbar : function(){ return this.bottomToolbar; }, addButton : function(config, handler, scope){ var bc = { handler: handler, scope: scope, minWidth: this.minButtonWidth, hideParent:true }; if(typeof config == "string"){ bc.text = config; }else{ Ext.apply(bc, config); } var btn = new Ext.Button(bc); btn.ownerCt = this; if(!this.buttons){ this.buttons = []; } this.buttons.push(btn); return btn; }, addTool : function(){ if(!this[this.toolTarget]) { return; } if(!this.toolTemplate){ var tt = new Ext.Template( '<div class="x-tool x-tool-{id}">&#160;</div>' ); tt.disableFormats = true; tt.compile(); Ext.Panel.prototype.toolTemplate = tt; } for(var i = 0, a = arguments, len = a.length; i < len; i++) { var tc = a[i], overCls = 'x-tool-'+tc.id+'-over'; var t = this.toolTemplate.insertFirst(this[this.toolTarget], tc, true); this.tools[tc.id] = t; t.enableDisplayMode('block'); t.on('click', this.createToolHandler(t, tc, overCls, this)); if(tc.on){ t.on(tc.on); } if(tc.hidden){ t.hide(); } if(tc.qtip){ if(typeof tc.qtip == 'object'){ Ext.QuickTips.register(Ext.apply({ target: t.id }, tc.qtip)); } else { t.dom.qtip = tc.qtip; } } t.addClassOnOver(overCls); } }, onShow : function(){ if(this.floating){ return this.el.show(); } Ext.Panel.superclass.onShow.call(this); }, onHide : function(){ if(this.floating){ return this.el.hide(); } Ext.Panel.superclass.onHide.call(this); }, createToolHandler : function(t, tc, overCls, panel){ return function(e){ t.removeClass(overCls); e.stopEvent(); if(tc.handler){ tc.handler.call(tc.scope || t, e, t, panel); } }; }, afterRender : function(){ if(this.fromMarkup && this.height === undefined && !this.autoHeight){ this.height = this.el.getHeight(); } if(this.floating && !this.hidden && !this.initHidden){ this.el.show(); } if(this.title){ this.setTitle(this.title); } this.setAutoScroll(); if(this.html){ this.body.update(typeof this.html == 'object' ? Ext.DomHelper.markup(this.html) : this.html); delete this.html; } if(this.contentEl){ var ce = Ext.getDom(this.contentEl); Ext.fly(ce).removeClass(['x-hidden', 'x-hide-display']); this.body.dom.appendChild(ce); } if(this.collapsed){ this.collapsed = false; this.collapse(false); } Ext.Panel.superclass.afterRender.call(this); this.initEvents(); }, setAutoScroll : function(){ if(this.rendered && this.autoScroll){ this.body.setOverflow('auto'); } }, getKeyMap : function(){ if(!this.keyMap){ this.keyMap = new Ext.KeyMap(this.el, this.keys); } return this.keyMap; }, initEvents : function(){ if(this.keys){ this.getKeyMap(); } if(this.draggable){ this.initDraggable(); } }, initDraggable : function(){ this.dd = new Ext.Panel.DD(this, typeof this.draggable == 'boolean' ? null : this.draggable); }, beforeEffect : function(){ if(this.floating){ this.el.beforeAction(); } this.el.addClass('x-panel-animated'); }, afterEffect : function(){ this.syncShadow(); this.el.removeClass('x-panel-animated'); }, createEffect : function(a, cb, scope){ var o = { scope:scope, block:true }; if(a === true){ o.callback = cb; return o; }else if(!a.callback){ o.callback = cb; }else { o.callback = function(){ cb.call(scope); Ext.callback(a.callback, a.scope); }; } return Ext.applyIf(o, a); }, collapse : function(animate){ if(this.collapsed || this.el.hasFxBlock() || this.fireEvent('beforecollapse', this, animate) === false){ return; } var doAnim = animate === true || (animate !== false && this.animCollapse); this.beforeEffect(); this.onCollapse(doAnim, animate); return this; }, onCollapse : function(doAnim, animArg){ if(doAnim){ this[this.collapseEl].slideOut(this.slideAnchor, Ext.apply(this.createEffect(animArg||true, this.afterCollapse, this), this.collapseDefaults)); }else{ this[this.collapseEl].hide(); this.afterCollapse(); } }, afterCollapse : function(){ this.collapsed = true; this.el.addClass(this.collapsedCls); this.afterEffect(); this.fireEvent('collapse', this); }, expand : function(animate){ if(!this.collapsed || this.el.hasFxBlock() || this.fireEvent('beforeexpand', this, animate) === false){ return; } var doAnim = animate === true || (animate !== false && this.animCollapse); this.el.removeClass(this.collapsedCls); this.beforeEffect(); this.onExpand(doAnim, animate); return this; }, onExpand : function(doAnim, animArg){ if(doAnim){ this[this.collapseEl].slideIn(this.slideAnchor, Ext.apply(this.createEffect(animArg||true, this.afterExpand, this), this.expandDefaults)); }else{ this[this.collapseEl].show(); this.afterExpand(); } }, afterExpand : function(){ this.collapsed = false; this.afterEffect(); this.fireEvent('expand', this); }, toggleCollapse : function(animate){ this[this.collapsed ? 'expand' : 'collapse'](animate); return this; }, onDisable : function(){ if(this.rendered && this.maskDisabled){ this.el.mask(); } Ext.Panel.superclass.onDisable.call(this); }, onEnable : function(){ if(this.rendered && this.maskDisabled){ this.el.unmask(); } Ext.Panel.superclass.onEnable.call(this); }, onResize : function(w, h){ if(w !== undefined || h !== undefined){ if(!this.collapsed){ if(typeof w == 'number'){ this.body.setWidth( this.adjustBodyWidth(w - this.getFrameWidth())); }else if(w == 'auto'){ this.body.setWidth(w); } if(typeof h == 'number'){ this.body.setHeight( this.adjustBodyHeight(h - this.getFrameHeight())); }else if(h == 'auto'){ this.body.setHeight(h); } }else{ this.queuedBodySize = {width: w, height: h}; if(!this.queuedExpand && this.allowQueuedExpand !== false){ this.queuedExpand = true; this.on('expand', function(){ delete this.queuedExpand; this.onResize(this.queuedBodySize.width, this.queuedBodySize.height); this.doLayout(); }, this, {single:true}); } } this.fireEvent('bodyresize', this, w, h); } this.syncShadow(); }, adjustBodyHeight : function(h){ return h; }, adjustBodyWidth : function(w){ return w; }, onPosition : function(){ this.syncShadow(); }, onDestroy : function(){ if(this.tools){ for(var k in this.tools){ Ext.destroy(this.tools[k]); } } if(this.buttons){ for(var b in this.buttons){ Ext.destroy(this.buttons[b]); } } Ext.destroy( this.topToolbar, this.bottomToolbar ); Ext.Panel.superclass.onDestroy.call(this); }, getFrameWidth : function(){ var w = this.el.getFrameWidth('lr'); if(this.frame){ var l = this.bwrap.dom.firstChild; w += (Ext.fly(l).getFrameWidth('l') + Ext.fly(l.firstChild).getFrameWidth('r')); var mc = this.bwrap.dom.firstChild.firstChild.firstChild; w += Ext.fly(mc).getFrameWidth('lr'); } return w; }, getFrameHeight : function(){ var h = this.el.getFrameWidth('tb'); h += (this.tbar ? this.tbar.getHeight() : 0) + (this.bbar ? this.bbar.getHeight() : 0); if(this.frame){ var hd = this.el.dom.firstChild; var ft = this.bwrap.dom.lastChild; h += (hd.offsetHeight + ft.offsetHeight); var mc = this.bwrap.dom.firstChild.firstChild.firstChild; h += Ext.fly(mc).getFrameWidth('tb'); }else{ h += (this.header ? this.header.getHeight() : 0) + (this.footer ? this.footer.getHeight() : 0); } return h; }, getInnerWidth : function(){ return this.getSize().width - this.getFrameWidth(); }, getInnerHeight : function(){ return this.getSize().height - this.getFrameHeight(); }, syncShadow : function(){ if(this.floating){ this.el.sync(true); } }, getLayoutTarget : function(){ return this.body; }, setTitle : function(title, iconCls){ this.title = title; if(this.header && this.headerAsText){ this.header.child('span').update(title); } if(iconCls){ this.setIconClass(iconCls); } this.fireEvent('titlechange', this, title); return this; }, getUpdater : function(){ return this.body.getUpdater(); }, load : function(){ var um = this.body.getUpdater(); um.update.apply(um, arguments); return this; }, beforeDestroy : function(){ Ext.Element.uncache( this.header, this.tbar, this.bbar, this.footer, this.body ); }, createClasses : function(){ this.headerCls = this.baseCls + '-header'; this.headerTextCls = this.baseCls + '-header-text'; this.bwrapCls = this.baseCls + '-bwrap'; this.tbarCls = this.baseCls + '-tbar'; this.bodyCls = this.baseCls + '-body'; this.bbarCls = this.baseCls + '-bbar'; this.footerCls = this.baseCls + '-footer'; }, createGhost : function(cls, useShim, appendTo){ var el = document.createElement('div'); el.className = 'x-panel-ghost ' + (cls ? cls : ''); if(this.header){ el.appendChild(this.el.dom.firstChild.cloneNode(true)); } Ext.fly(el.appendChild(document.createElement('ul'))).setHeight(this.bwrap.getHeight()); el.style.width = this.el.dom.offsetWidth + 'px';; if(!appendTo){ this.container.dom.appendChild(el); }else{ Ext.getDom(appendTo).appendChild(el); } if(useShim !== false && this.el.useShim !== false){ var layer = new Ext.Layer({shadow:false, useDisplay:true, constrain:false}, el); layer.show(); return layer; }else{ return new Ext.Element(el); } }, doAutoLoad : function(){ this.body.load( typeof this.autoLoad == 'object' ? this.autoLoad : {url: this.autoLoad}); } }); Ext.reg('panel', Ext.Panel); Ext.Window = Ext.extend(Ext.Panel, { baseCls : 'x-window', resizable:true, draggable:true, closable : true, constrain:false, constrainHeader:false, plain:false, minimizable : false, maximizable : false, minHeight: 100, minWidth: 200, expandOnShow: true, closeAction: 'close', collapsible:false, initHidden : true, monitorResize : true, elements: 'header,body', frame:true, floating:true, initComponent : function(){ Ext.Window.superclass.initComponent.call(this); this.addEvents( 'resize', 'maximize', 'minimize', 'restore' ); }, getState : function(){ return Ext.apply(Ext.Window.superclass.getState.call(this) || {}, this.getBox()); }, onRender : function(ct, position){ Ext.Window.superclass.onRender.call(this, ct, position); if(this.plain){ this.el.addClass('x-window-plain'); } this.focusEl = this.el.createChild({ tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1", html: "&#160;"}); this.focusEl.swallowEvent('click', true); this.proxy = this.el.createProxy("x-window-proxy"); this.proxy.enableDisplayMode('block'); if(this.modal){ this.mask = this.container.createChild({cls:"ext-el-mask"}, this.el.dom); this.mask.enableDisplayMode("block"); this.mask.hide(); } }, initEvents : function(){ Ext.Window.superclass.initEvents.call(this); if(this.animateTarget){ this.setAnimateTarget(this.animateTarget); } if(this.resizable){ this.resizer = new Ext.Resizable(this.el, { minWidth: this.minWidth, minHeight:this.minHeight, handles: this.resizeHandles || "all", pinned: true, resizeElement : this.resizerAction }); this.resizer.window = this; this.resizer.on("beforeresize", this.beforeResize, this); } if(this.draggable){ this.header.addClass("x-window-draggable"); } this.initTools(); this.el.on("mousedown", this.toFront, this); this.manager = this.manager || Ext.WindowMgr; this.manager.register(this); this.hidden = true; if(this.maximized){ this.maximized = false; this.maximize(); } if(this.closable){ var km = this.getKeyMap(); km.on(27, this.onEsc, this); km.disable(); } }, initDraggable : function(){ this.dd = new Ext.Window.DD(this); }, onEsc : function(){ this[this.closeAction](); }, beforeDestroy : function(){ Ext.destroy( this.resizer, this.dd, this.proxy, this.mask ); Ext.Window.superclass.beforeDestroy.call(this); }, onDestroy : function(){ if(this.manager){ this.manager.unregister(this); } Ext.Window.superclass.onDestroy.call(this); }, initTools : function(){ if(this.minimizable){ this.addTool({ id: 'minimize', handler: this.minimize.createDelegate(this, []) }); } if(this.maximizable){ this.addTool({ id: 'maximize', handler: this.maximize.createDelegate(this, []) }); this.addTool({ id: 'restore', handler: this.restore.createDelegate(this, []), hidden:true }); this.header.on('dblclick', this.toggleMaximize, this); } if(this.closable){ this.addTool({ id: 'close', handler: this[this.closeAction].createDelegate(this, []) }); } }, resizerAction : function(){ var box = this.proxy.getBox(); this.proxy.hide(); this.window.handleResize(box); return box; }, beforeResize : function(){ this.resizer.minHeight = Math.max(this.minHeight, this.getFrameHeight() + 40); this.resizer.minWidth = Math.max(this.minWidth, this.getFrameWidth() + 40); this.resizeBox = this.el.getBox(); }, updateHandles : function(){ if(Ext.isIE && this.resizer){ this.resizer.syncHandleHeight(); this.el.repaint(); } }, handleResize : function(box){ var rz = this.resizeBox; if(rz.x != box.x || rz.y != box.y){ this.updateBox(box); }else{ this.setSize(box); } this.focus(); this.updateHandles(); this.saveState(); this.fireEvent("resize", this, box.width, box.height); }, focus : function(){ var f = this.focusEl, db = this.defaultButton, t = typeof db; if(t != 'undefined'){ if(t == 'number'){ f = this.buttons[db]; }else if(t == 'string'){ f = Ext.getCmp(db); }else{ f = db; } } f.focus.defer(10, f); }, setAnimateTarget : function(el){ el = Ext.get(el); this.animateTarget = el; }, beforeShow : function(){ delete this.el.lastXY; delete this.el.lastLT; if(this.x === undefined || this.y === undefined){ var xy = this.el.getAlignToXY(this.container, 'c-c'); var pos = this.el.translatePoints(xy[0], xy[1]); this.x = this.x === undefined? pos.left : this.x; this.y = this.y === undefined? pos.top : this.y; } this.el.setLeftTop(this.x, this.y); if(this.expandOnShow){ this.expand(false); } if(this.modal){ Ext.getBody().addClass("x-body-masked"); this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true)); this.mask.show(); } }, show : function(animateTarget, cb, scope){ if(!this.rendered){ this.render(Ext.getBody()); } if(this.hidden === false){ this.toFront(); return; } if(this.fireEvent("beforeshow", this) === false){ return; } if(cb){ this.on('show', cb, scope, {single:true}); } this.hidden = false; if(animateTarget !== undefined){ this.setAnimateTarget(animateTarget); } this.beforeShow(); if(this.animateTarget){ this.animShow(); }else{ this.afterShow(); } }, afterShow : function(){ this.proxy.hide(); this.el.setStyle('display', 'block'); this.el.show(); if(this.maximized){ this.fitContainer(); } if(Ext.isMac && Ext.isGecko){ this.cascade(this.setAutoScroll); } if(this.monitorResize || this.modal || this.constrain || this.constrainHeader){ Ext.EventManager.onWindowResize(this.onWindowResize, this); } this.doConstrain(); if(this.layout){ this.doLayout(); } if(this.keyMap){ this.keyMap.enable(); } this.toFront(); this.updateHandles(); this.fireEvent("show", this); }, animShow : function(){ this.proxy.show(); this.proxy.setBox(this.animateTarget.getBox()); this.proxy.setOpacity(0); var b = this.getBox(false); b.callback = this.afterShow; b.scope = this; b.duration = .25; b.easing = 'easeNone'; b.opacity = .5; b.block = true; this.el.setStyle('display', 'none'); this.proxy.shift(b); }, hide : function(animateTarget, cb, scope){ if(this.hidden || this.fireEvent("beforehide", this) === false){ return; } if(cb){ this.on('hide', cb, scope, {single:true}); } this.hidden = true; if(animateTarget !== undefined){ this.setAnimateTarget(animateTarget); } if(this.animateTarget){ this.animHide(); }else{ this.el.hide(); this.afterHide(); } }, afterHide : function(){ this.proxy.hide(); if(this.monitorResize || this.modal || this.constrain || this.constrainHeader){ Ext.EventManager.removeResizeListener(this.onWindowResize, this); } if(this.modal){ this.mask.hide(); Ext.getBody().removeClass("x-body-masked"); } if(this.keyMap){ this.keyMap.disable(); } this.fireEvent("hide", this); }, animHide : function(){ this.proxy.setOpacity(.5); this.proxy.show(); var tb = this.getBox(false); this.proxy.setBox(tb); this.el.hide(); var b = this.animateTarget.getBox(); b.callback = this.afterHide; b.scope = this; b.duration = .25; b.easing = 'easeNone'; b.block = true; b.opacity = 0; this.proxy.shift(b); }, onWindowResize : function(){ if(this.maximized){ this.fitContainer(); } if(this.modal){ this.mask.setSize('100%', '100%'); var force = this.mask.dom.offsetHeight; this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true)); } this.doConstrain(); }, doConstrain : function(){ if(this.constrain || this.constrainHeader){ var offsets; if(this.constrain){ offsets = { right:this.el.shadowOffset, left:this.el.shadowOffset, bottom:this.el.shadowOffset }; }else { var s = this.getSize(); offsets = { right:-(s.width - 100), bottom:-(s.height - 25) }; } var xy = this.el.getConstrainToXY(this.container, true, offsets); if(xy){ this.setPosition(xy[0], xy[1]); } } }, ghost : function(cls){ var ghost = this.createGhost(cls); var box = this.getBox(true); ghost.setLeftTop(box.x, box.y); ghost.setWidth(box.width); this.el.hide(); this.activeGhost = ghost; return ghost; }, unghost : function(show, matchPosition){ if(show !== false){ this.el.show(); this.focus(); if(Ext.isMac && Ext.isGecko){ this.cascade(this.setAutoScroll); } } if(matchPosition !== false){ this.setPosition(this.activeGhost.getLeft(true), this.activeGhost.getTop(true)); } this.activeGhost.hide(); this.activeGhost.remove(); delete this.activeGhost; }, minimize : function(){ this.fireEvent('minimize', this); }, close : function(){ if(this.fireEvent("beforeclose", this) !== false){ this.hide(null, function(){ this.fireEvent('close', this); this.destroy(); }, this); } }, maximize : function(){ if(!this.maximized){ this.expand(false); this.restoreSize = this.getSize(); this.restorePos = this.getPosition(true); this.tools.maximize.hide(); this.tools.restore.show(); this.maximized = true; this.el.disableShadow(); if(this.dd){ this.dd.lock(); } if(this.collapsible){ this.tools.toggle.hide(); } this.el.addClass('x-window-maximized'); this.container.addClass('x-window-maximized-ct'); this.setPosition(0, 0); this.fitContainer(); this.fireEvent('maximize', this); } }, restore : function(){ if(this.maximized){ this.el.removeClass('x-window-maximized'); this.tools.restore.hide(); this.tools.maximize.show(); this.setPosition(this.restorePos[0], this.restorePos[1]); this.setSize(this.restoreSize.width, this.restoreSize.height); delete this.restorePos; delete this.restoreSize; this.maximized = false; this.el.enableShadow(true); if(this.dd){ this.dd.unlock(); } if(this.collapsible){ this.tools.toggle.show(); } this.container.removeClass('x-window-maximized-ct'); this.doConstrain(); this.fireEvent('restore', this); } }, toggleMaximize : function(){ this[this.maximized ? 'restore' : 'maximize'](); }, fitContainer : function(){ var vs = this.container.getViewSize(); this.setSize(vs.width, vs.height); }, setZIndex : function(index){ if(this.modal){ this.mask.setStyle("z-index", index); } this.el.setZIndex(++index); index += 5; if(this.resizer){ this.resizer.proxy.setStyle("z-index", ++index); } this.lastZIndex = index; }, alignTo : function(element, position, offsets){ var xy = this.el.getAlignToXY(element, position, offsets); this.setPagePosition(xy[0], xy[1]); return this; }, anchorTo : function(el, alignment, offsets, monitorScroll, _pname){ var action = function(){ this.alignTo(el, alignment, offsets); }; Ext.EventManager.onWindowResize(action, this); var tm = typeof monitorScroll; if(tm != 'undefined'){ Ext.EventManager.on(window, 'scroll', action, this, {buffer: tm == 'number' ? monitorScroll : 50}); } action.call(this); this[_pname] = action; return this; }, toFront : function(){ if(this.manager.bringToFront(this)){ this.focus(); } return this; }, setActive : function(active){ if(active){ if(!this.maximized){ this.el.enableShadow(true); } this.fireEvent('activate', this); }else{ this.el.disableShadow(); this.fireEvent('deactivate', this); } }, toBack : function(){ this.manager.sendToBack(this); return this; }, center : function(){ var xy = this.el.getAlignToXY(this.container, 'c-c'); this.setPagePosition(xy[0], xy[1]); return this; } }); Ext.reg('window', Ext.Window); Ext.Window.DD = function(win){ this.win = win; Ext.Window.DD.superclass.constructor.call(this, win.el.id, 'WindowDD-'+win.id); this.setHandleElId(win.header.id); this.scroll = false; }; Ext.extend(Ext.Window.DD, Ext.dd.DD, { moveOnly:true, headerOffsets:[100, 25], startDrag : function(){ var w = this.win; this.proxy = w.ghost(); if(w.constrain !== false){ var so = w.el.shadowOffset; this.constrainTo(w.container, {right: so, left: so, bottom: so}); }else if(w.constrainHeader !== false){ var s = this.proxy.getSize(); this.constrainTo(w.container, {right: -(s.width-this.headerOffsets[0]), bottom: -(s.height-this.headerOffsets[1])}); } }, b4Drag : Ext.emptyFn, onDrag : function(e){ this.alignElWithMouse(this.proxy, e.getPageX(), e.getPageY()); }, endDrag : function(e){ this.win.unghost(); this.win.saveState(); } }); Ext.WindowGroup = function(){ var list = {}; var accessList = []; var front = null; var sortWindows = function(d1, d2){ return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1; }; var orderWindows = function(){ var a = accessList, len = a.length; if(len > 0){ a.sort(sortWindows); var seed = a[0].manager.zseed; for(var i = 0; i < len; i++){ var win = a[i]; if(win && !win.hidden){ win.setZIndex(seed + (i*10)); } } } activateLast(); }; var setActiveWin = function(win){ if(win != front){ if(front){ front.setActive(false); } front = win; if(win){ win.setActive(true); } } }; var activateLast = function(){ for(var i = accessList.length-1; i >=0; --i) { if(!accessList[i].hidden){ setActiveWin(accessList[i]); return; } } setActiveWin(null); }; return { zseed : 9000, register : function(win){ list[win.id] = win; accessList.push(win); win.on('hide', activateLast); }, unregister : function(win){ delete list[win.id]; win.un('hide', activateLast); accessList.remove(win); }, get : function(id){ return typeof id == "object" ? id : list[id]; }, bringToFront : function(win){ win = this.get(win); if(win != front){ win._lastAccess = new Date().getTime(); orderWindows(); return true; } return false; }, sendToBack : function(win){ win = this.get(win); win._lastAccess = -(new Date().getTime()); orderWindows(); return win; }, hideAll : function(){ for(var id in list){ if(list[id] && typeof list[id] != "function" && list[id].isVisible()){ list[id].hide(); } } }, getActive : function(){ return front; }, getBy : function(fn, scope){ var r = []; for(var i = accessList.length-1; i >=0; --i) { var win = accessList[i]; if(fn.call(scope||win, win) !== false){ r.push(win); } } return r; }, each : function(fn, scope){ for(var id in list){ if(list[id] && typeof list[id] != "function"){ if(fn.call(scope || list[id], list[id]) === false){ return; } } } } }; }; Ext.WindowMgr = new Ext.WindowGroup(); Ext.dd.PanelProxy = function(panel, config){ this.panel = panel; this.id = this.panel.id +'-ddproxy'; Ext.apply(this, config); }; Ext.dd.PanelProxy.prototype = { insertProxy : true, setStatus : Ext.emptyFn, reset : Ext.emptyFn, update : Ext.emptyFn, stop : Ext.emptyFn, sync: Ext.emptyFn, getEl : function(){ return this.ghost; }, getGhost : function(){ return this.ghost; }, getProxy : function(){ return this.proxy; }, hide : function(){ if(this.ghost){ if(this.proxy){ this.proxy.remove(); delete this.proxy; } this.panel.el.dom.style.display = ''; this.ghost.remove(); delete this.ghost; } }, show : function(){ if(!this.ghost){ this.ghost = this.panel.createGhost(undefined, undefined, Ext.getBody()); this.ghost.setXY(this.panel.el.getXY()) if(this.insertProxy){ this.proxy = this.panel.el.insertSibling({cls:'x-panel-dd-spacer'}); this.proxy.setSize(this.panel.getSize()); } this.panel.el.dom.style.display = 'none'; } }, repair : function(xy, callback, scope){ this.hide(); if(typeof callback == "function"){ callback.call(scope || this); } }, moveProxy : function(parentNode, before){ if(this.proxy){ parentNode.insertBefore(this.proxy.dom, before); } } }; Ext.Panel.DD = function(panel, cfg){ this.panel = panel; this.dragData = {panel: panel}; this.proxy = new Ext.dd.PanelProxy(panel, cfg); Ext.Panel.DD.superclass.constructor.call(this, panel.el, cfg); this.setHandleElId(panel.header.id); panel.header.setStyle('cursor', 'move'); this.scroll = false; }; Ext.extend(Ext.Panel.DD, Ext.dd.DragSource, { showFrame: Ext.emptyFn, startDrag: Ext.emptyFn, b4StartDrag: function(x, y) { this.proxy.show(); }, b4MouseDown: function(e) { var x = e.getPageX(); var y = e.getPageY(); this.autoOffset(x, y); }, onInitDrag : function(x, y){ this.onStartDrag(x, y); return true; }, createFrame : Ext.emptyFn, getDragEl : function(e){ return this.proxy.ghost.dom; }, endDrag : function(e){ this.proxy.hide(); this.panel.saveState(); }, autoOffset : function(x, y) { x -= this.startPageX; y -= this.startPageY; this.setDelta(x, y); } }); Ext.state.Provider = function(){ this.addEvents("statechange"); this.state = {}; Ext.state.Provider.superclass.constructor.call(this); }; Ext.extend(Ext.state.Provider, Ext.util.Observable, { get : function(name, defaultValue){ return typeof this.state[name] == "undefined" ? defaultValue : this.state[name]; }, clear : function(name){ delete this.state[name]; this.fireEvent("statechange", this, name, null); }, set : function(name, value){ this.state[name] = value; this.fireEvent("statechange", this, name, value); }, decodeValue : function(cookie){ var re = /^(a|n|d|b|s|o)\:(.*)$/; var matches = re.exec(unescape(cookie)); if(!matches || !matches[1]) return; var type = matches[1]; var v = matches[2]; switch(type){ case "n": return parseFloat(v); case "d": return new Date(Date.parse(v)); case "b": return (v == "1"); case "a": var all = []; var values = v.split("^"); for(var i = 0, len = values.length; i < len; i++){ all.push(this.decodeValue(values[i])); } return all; case "o": var all = {}; var values = v.split("^"); for(var i = 0, len = values.length; i < len; i++){ var kv = values[i].split("="); all[kv[0]] = this.decodeValue(kv[1]); } return all; default: return v; } }, encodeValue : function(v){ var enc; if(typeof v == "number"){ enc = "n:" + v; }else if(typeof v == "boolean"){ enc = "b:" + (v ? "1" : "0"); }else if(Ext.isDate(v)){ enc = "d:" + v.toGMTString(); }else if(Ext.isArray(v)){ var flat = ""; for(var i = 0, len = v.length; i < len; i++){ flat += this.encodeValue(v[i]); if(i != len-1) flat += "^"; } enc = "a:" + flat; }else if(typeof v == "object"){ var flat = ""; for(var key in v){ if(typeof v[key] != "function" && v[key] !== undefined){ flat += key + "=" + this.encodeValue(v[key]) + "^"; } } enc = "o:" + flat.substring(0, flat.length-1); }else{ enc = "s:" + v; } return escape(enc); } }); Ext.state.Manager = function(){ var provider = new Ext.state.Provider(); return { setProvider : function(stateProvider){ provider = stateProvider; }, get : function(key, defaultValue){ return provider.get(key, defaultValue); }, set : function(key, value){ provider.set(key, value); }, clear : function(key){ provider.clear(key); }, getProvider : function(){ return provider; } }; }(); Ext.state.CookieProvider = function(config){ Ext.state.CookieProvider.superclass.constructor.call(this); this.path = "/"; this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); this.domain = null; this.secure = false; Ext.apply(this, config); this.state = this.readCookies(); }; Ext.extend(Ext.state.CookieProvider, Ext.state.Provider, { set : function(name, value){ if(typeof value == "undefined" || value === null){ this.clear(name); return; } this.setCookie(name, value); Ext.state.CookieProvider.superclass.set.call(this, name, value); }, clear : function(name){ this.clearCookie(name); Ext.state.CookieProvider.superclass.clear.call(this, name); }, readCookies : function(){ var cookies = {}; var c = document.cookie + ";"; var re = /\s?(.*?)=(.*?);/g; var matches; while((matches = re.exec(c)) != null){ var name = matches[1]; var value = matches[2]; if(name && name.substring(0,3) == "ys-"){ cookies[name.substr(3)] = this.decodeValue(value); } } return cookies; }, setCookie : function(name, value){ document.cookie = "ys-"+ name + "=" + this.encodeValue(value) + ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) + ((this.path == null) ? "" : ("; path=" + this.path)) + ((this.domain == null) ? "" : ("; domain=" + this.domain)) + ((this.secure == true) ? "; secure" : ""); }, clearCookie : function(name){ document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" + ((this.path == null) ? "" : ("; path=" + this.path)) + ((this.domain == null) ? "" : ("; domain=" + this.domain)) + ((this.secure == true) ? "; secure" : ""); } }); Ext.DataView = Ext.extend(Ext.BoxComponent, { selectedClass : "x-view-selected", emptyText : "", last: false, initComponent : function(){ Ext.DataView.superclass.initComponent.call(this); if(typeof this.tpl == "string"){ this.tpl = new Ext.XTemplate(this.tpl); } this.addEvents( "beforeclick", "click", "containerclick", "dblclick", "contextmenu", "selectionchange", "beforeselect" ); this.all = new Ext.CompositeElementLite(); this.selected = new Ext.CompositeElementLite(); }, onRender : function(){ if(!this.el){ this.el = document.createElement('div'); } Ext.DataView.superclass.onRender.apply(this, arguments); }, afterRender : function(){ Ext.DataView.superclass.afterRender.call(this); this.el.on({ "click": this.onClick, "dblclick": this.onDblClick, "contextmenu": this.onContextMenu, scope:this }); if(this.overClass){ this.el.on({ "mouseover": this.onMouseOver, "mouseout": this.onMouseOut, scope:this }); } if(this.store){ this.setStore(this.store, true); } }, refresh : function(){ this.clearSelections(false, true); this.el.update(""); var html = []; var records = this.store.getRange(); if(records.length < 1){ this.el.update(this.emptyText); this.all.clear(); return; } this.tpl.overwrite(this.el, this.collectData(records, 0)); this.all.fill(Ext.query(this.itemSelector, this.el.dom)); this.updateIndexes(0); }, prepareData : function(data){ return data; }, collectData : function(records, startIndex){ var r = []; for(var i = 0, len = records.length; i < len; i++){ r[r.length] = this.prepareData(records[i].data, startIndex+i, records[i]); } return r; }, bufferRender : function(records){ var div = document.createElement('div'); this.tpl.overwrite(div, this.collectData(records)); return Ext.query(this.itemSelector, div); }, onUpdate : function(ds, record){ var index = this.store.indexOf(record); var sel = this.isSelected(index); var original = this.all.elements[index]; var node = this.bufferRender([record], index)[0]; this.all.replaceElement(index, node, true); if(sel){ this.selected.replaceElement(original, node); this.all.item(index).addClass(this.selectedClass); } this.updateIndexes(index, index); }, onAdd : function(ds, records, index){ if(this.all.getCount() == 0){ this.refresh(); return; } var nodes = this.bufferRender(records, index), n; if(index < this.all.getCount()){ n = this.all.item(index).insertSibling(nodes, 'before', true); this.all.elements.splice(index, 0, n); }else{ n = this.all.last().insertSibling(nodes, 'after', true); this.all.elements.push(n); } this.updateIndexes(index); }, onRemove : function(ds, record, index){ this.deselect(index); this.all.removeElement(index, true); this.updateIndexes(index); }, refreshNode : function(index){ this.onUpdate(this.store, this.store.getAt(index)); }, updateIndexes : function(startIndex, endIndex){ var ns = this.all.elements; startIndex = startIndex || 0; endIndex = endIndex || ((endIndex === 0) ? 0 : (ns.length - 1)); for(var i = startIndex; i <= endIndex; i++){ ns[i].viewIndex = i; } }, setStore : function(store, initial){ if(!initial && this.store){ this.store.un("beforeload", this.onBeforeLoad, this); this.store.un("datachanged", this.refresh, this); this.store.un("add", this.onAdd, this); this.store.un("remove", this.onRemove, this); this.store.un("update", this.onUpdate, this); this.store.un("clear", this.refresh, this); } if(store){ store = Ext.StoreMgr.lookup(store); store.on("beforeload", this.onBeforeLoad, this); store.on("datachanged", this.refresh, this); store.on("add", this.onAdd, this); store.on("remove", this.onRemove, this); store.on("update", this.onUpdate, this); store.on("clear", this.refresh, this); } this.store = store; if(store){ this.refresh(); } }, findItemFromChild : function(node){ return Ext.fly(node).findParent(this.itemSelector, this.el); }, onClick : function(e){ var item = e.getTarget(this.itemSelector, this.el); if(item){ var index = this.indexOf(item); if(this.onItemClick(item, index, e) !== false){ this.fireEvent("click", this, index, item, e); } }else{ if(this.fireEvent("containerclick", this, e) !== false){ this.clearSelections(); } } }, onContextMenu : function(e){ var item = e.getTarget(this.itemSelector, this.el); if(item){ this.fireEvent("contextmenu", this, this.indexOf(item), item, e); } }, onDblClick : function(e){ var item = e.getTarget(this.itemSelector, this.el); if(item){ this.fireEvent("dblclick", this, this.indexOf(item), item, e); } }, onMouseOver : function(e){ var item = e.getTarget(this.itemSelector, this.el); if(item && item !== this.lastItem){ this.lastItem = item; Ext.fly(item).addClass(this.overClass); } }, onMouseOut : function(e){ if(this.lastItem){ if(!e.within(this.lastItem, true)){ Ext.fly(this.lastItem).removeClass(this.overClass); delete this.lastItem; } } }, onItemClick : function(item, index, e){ if(this.fireEvent("beforeclick", this, index, item, e) === false){ return false; } if(this.multiSelect){ this.doMultiSelection(item, index, e); e.preventDefault(); }else if(this.singleSelect){ this.doSingleSelection(item, index, e); e.preventDefault(); } return true; }, doSingleSelection : function(item, index, e){ if(e.ctrlKey && this.isSelected(index)){ this.deselect(index); }else{ this.select(index, false); } }, doMultiSelection : function(item, index, e){ if(e.shiftKey && this.last !== false){ var last = this.last; this.selectRange(last, index, e.ctrlKey); this.last = last; }else{ if((e.ctrlKey||this.simpleSelect) && this.isSelected(index)){ this.deselect(index); }else{ this.select(index, e.ctrlKey || e.shiftKey || this.simpleSelect); } } }, getSelectionCount : function(){ return this.selected.getCount() }, getSelectedNodes : function(){ return this.selected.elements; }, getSelectedIndexes : function(){ var indexes = [], s = this.selected.elements; for(var i = 0, len = s.length; i < len; i++){ indexes.push(s[i].viewIndex); } return indexes; }, getSelectedRecords : function(){ var r = [], s = this.selected.elements; for(var i = 0, len = s.length; i < len; i++){ r[r.length] = this.store.getAt(s[i].viewIndex); } return r; }, getRecords : function(nodes){ var r = [], s = nodes; for(var i = 0, len = s.length; i < len; i++){ r[r.length] = this.store.getAt(s[i].viewIndex); } return r; }, getRecord : function(node){ return this.store.getAt(node.viewIndex); }, clearSelections : function(suppressEvent, skipUpdate){ if(this.multiSelect || this.singleSelect){ if(!skipUpdate){ this.selected.removeClass(this.selectedClass); } this.selected.clear(); this.last = false; if(!suppressEvent){ this.fireEvent("selectionchange", this, this.selected.elements); } } }, isSelected : function(node){ return this.selected.contains(this.getNode(node)); }, deselect : function(node){ if(this.isSelected(node)){ var node = this.getNode(node); this.selected.removeElement(node); if(this.last == node.viewIndex){ this.last = false; } Ext.fly(node).removeClass(this.selectedClass); this.fireEvent("selectionchange", this, this.selected.elements); } }, select : function(nodeInfo, keepExisting, suppressEvent){ if(Ext.isArray(nodeInfo)){ if(!keepExisting){ this.clearSelections(true); } for(var i = 0, len = nodeInfo.length; i < len; i++){ this.select(nodeInfo[i], true, true); } } else{ var node = this.getNode(nodeInfo); if(!keepExisting){ this.clearSelections(true); } if(node && !this.isSelected(node)){ if(this.fireEvent("beforeselect", this, node, this.selected.elements) !== false){ Ext.fly(node).addClass(this.selectedClass); this.selected.add(node); this.last = node.viewIndex; if(!suppressEvent){ this.fireEvent("selectionchange", this, this.selected.elements); } } } } }, selectRange : function(start, end, keepExisting){ if(!keepExisting){ this.clearSelections(true); } this.select(this.getNodes(start, end), true); }, getNode : function(nodeInfo){ if(typeof nodeInfo == "string"){ return document.getElementById(nodeInfo); }else if(typeof nodeInfo == "number"){ return this.all.elements[nodeInfo]; } return nodeInfo; }, getNodes : function(start, end){ var ns = this.all.elements; start = start || 0; end = typeof end == "undefined" ? ns.length - 1 : end; var nodes = [], i; if(start <= end){ for(i = start; i <= end; i++){ nodes.push(ns[i]); } } else{ for(i = start; i >= end; i--){ nodes.push(ns[i]); } } return nodes; }, indexOf : function(node){ node = this.getNode(node); if(typeof node.viewIndex == "number"){ return node.viewIndex; } return this.all.indexOf(node); }, onBeforeLoad : function(){ if(this.loadingText){ this.clearSelections(false, true); this.el.update('<div class="loading-indicator">'+this.loadingText+'</div>'); this.all.clear(); } } }); Ext.reg('dataview', Ext.DataView); Ext.ColorPalette = function(config){ Ext.ColorPalette.superclass.constructor.call(this, config); this.addEvents( 'select' ); if(this.handler){ this.on("select", this.handler, this.scope, true); } }; Ext.extend(Ext.ColorPalette, Ext.Component, { itemCls : "x-color-palette", value : null, clickEvent:'click', ctype: "Ext.ColorPalette", allowReselect : false, colors : [ "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333", "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080", "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696", "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0", "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF" ], onRender : function(container, position){ var t = this.tpl || new Ext.XTemplate( '<tpl for="."><a href="#" class="color-{.}" hidefocus="on"><em><span style="background:#{.}" unselectable="on">&#160;</span></em></a></tpl>' ); var el = document.createElement("div"); el.className = this.itemCls; t.overwrite(el, this.colors); container.dom.insertBefore(el, position); this.el = Ext.get(el); this.el.on(this.clickEvent, this.handleClick, this, {delegate: "a"}); if(this.clickEvent != 'click'){ this.el.on('click', Ext.emptyFn, this, {delegate: "a", preventDefault:true}); } }, afterRender : function(){ Ext.ColorPalette.superclass.afterRender.call(this); if(this.value){ var s = this.value; this.value = null; this.select(s); } }, handleClick : function(e, t){ e.preventDefault(); if(!this.disabled){ var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1]; this.select(c.toUpperCase()); } }, select : function(color){ color = color.replace("#", ""); if(color != this.value || this.allowReselect){ var el = this.el; if(this.value){ el.child("a.color-"+this.value).removeClass("x-color-palette-sel"); } el.child("a.color-"+color).addClass("x-color-palette-sel"); this.value = color; this.fireEvent("select", this, color); } } }); Ext.reg('colorpalette', Ext.ColorPalette); Ext.DatePicker = Ext.extend(Ext.Component, { todayText : "Today", okText : "&#160;OK&#160;", cancelText : "Cancel", todayTip : "{0} (Spacebar)", minDate : null, maxDate : null, minText : "This date is before the minimum date", maxText : "This date is after the maximum date", format : "m/d/y", disabledDays : null, disabledDaysText : "", disabledDatesRE : null, disabledDatesText : "", constrainToViewport : true, monthNames : Date.monthNames, dayNames : Date.dayNames, nextText: 'Next Month (Control+Right)', prevText: 'Previous Month (Control+Left)', monthYearText: 'Choose a month (Control+Up/Down to move years)', startDay : 0, initComponent : function(){ Ext.DatePicker.superclass.initComponent.call(this); this.value = this.value ? this.value.clearTime() : new Date().clearTime(); this.addEvents( 'select' ); if(this.handler){ this.on("select", this.handler, this.scope || this); } this.initDisabledDays(); }, initDisabledDays : function(){ if(!this.disabledDatesRE && this.disabledDates){ var dd = this.disabledDates; var re = "(?:"; for(var i = 0; i < dd.length; i++){ re += dd[i]; if(i != dd.length-1) re += "|"; } this.disabledDatesRE = new RegExp(re + ")"); } }, setValue : function(value){ var old = this.value; this.value = value.clearTime(true); if(this.el){ this.update(this.value); } }, getValue : function(){ return this.value; }, focus : function(){ if(this.el){ this.update(this.activeDate); } }, onRender : function(container, position){ var m = [ '<table cellspacing="0">', '<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'">&#160;</a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'">&#160;</a></td></tr>', '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>']; var dn = this.dayNames; for(var i = 0; i < 7; i++){ var d = this.startDay+i; if(d > 6){ d = d-7; } m.push("<th><span>", dn[d].substr(0,1), "</span></th>"); } m[m.length] = "</tr></thead><tbody><tr>"; for(var i = 0; i < 42; i++) { if(i % 7 == 0 && i != 0){ m[m.length] = "</tr><tr>"; } m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>'; } m[m.length] = '</tr></tbody></table></td></tr><tr><td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>'; var el = document.createElement("div"); el.className = "x-date-picker"; el.innerHTML = m.join(""); container.dom.insertBefore(el, position); this.el = Ext.get(el); this.eventEl = Ext.get(el.firstChild); new Ext.util.ClickRepeater(this.el.child("td.x-date-left a"), { handler: this.showPrevMonth, scope: this, preventDefault:true, stopDefault:true }); new Ext.util.ClickRepeater(this.el.child("td.x-date-right a"), { handler: this.showNextMonth, scope: this, preventDefault:true, stopDefault:true }); this.eventEl.on("mousewheel", this.handleMouseWheel, this); this.monthPicker = this.el.down('div.x-date-mp'); this.monthPicker.enableDisplayMode('block'); var kn = new Ext.KeyNav(this.eventEl, { "left" : function(e){ e.ctrlKey ? this.showPrevMonth() : this.update(this.activeDate.add("d", -1)); }, "right" : function(e){ e.ctrlKey ? this.showNextMonth() : this.update(this.activeDate.add("d", 1)); }, "up" : function(e){ e.ctrlKey ? this.showNextYear() : this.update(this.activeDate.add("d", -7)); }, "down" : function(e){ e.ctrlKey ? this.showPrevYear() : this.update(this.activeDate.add("d", 7)); }, "pageUp" : function(e){ this.showNextMonth(); }, "pageDown" : function(e){ this.showPrevMonth(); }, "enter" : function(e){ e.stopPropagation(); return true; }, scope : this }); this.eventEl.on("click", this.handleDateClick, this, {delegate: "a.x-date-date"}); this.eventEl.addKeyListener(Ext.EventObject.SPACE, this.selectToday, this); this.el.unselectable(); this.cells = this.el.select("table.x-date-inner tbody td"); this.textNodes = this.el.query("table.x-date-inner tbody span"); this.mbtn = new Ext.Button({ text: "&#160;", tooltip: this.monthYearText, renderTo: this.el.child("td.x-date-middle", true) }); this.mbtn.on('click', this.showMonthPicker, this); this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu"); var today = (new Date()).dateFormat(this.format); this.todayBtn = new Ext.Button({ renderTo: this.el.child("td.x-date-bottom", true), text: String.format(this.todayText, today), tooltip: String.format(this.todayTip, today), handler: this.selectToday, scope: this }); if(Ext.isIE){ this.el.repaint(); } this.update(this.value); }, createMonthPicker : function(){ if(!this.monthPicker.dom.firstChild){ var buf = ['<table border="0" cellspacing="0">']; for(var i = 0; i < 6; i++){ buf.push( '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>', '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>', i == 0 ? '<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' : '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>' ); } buf.push( '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">', this.okText, '</button><button type="button" class="x-date-mp-cancel">', this.cancelText, '</button></td></tr>', '</table>' ); this.monthPicker.update(buf.join('')); this.monthPicker.on('click', this.onMonthClick, this); this.monthPicker.on('dblclick', this.onMonthDblClick, this); this.mpMonths = this.monthPicker.select('td.x-date-mp-month'); this.mpYears = this.monthPicker.select('td.x-date-mp-year'); this.mpMonths.each(function(m, a, i){ i += 1; if((i%2) == 0){ m.dom.xmonth = 5 + Math.round(i * .5); }else{ m.dom.xmonth = Math.round((i-1) * .5); } }); } }, showMonthPicker : function(){ this.createMonthPicker(); var size = this.el.getSize(); this.monthPicker.setSize(size); this.monthPicker.child('table').setSize(size); this.mpSelMonth = (this.activeDate || this.value).getMonth(); this.updateMPMonth(this.mpSelMonth); this.mpSelYear = (this.activeDate || this.value).getFullYear(); this.updateMPYear(this.mpSelYear); this.monthPicker.slideIn('t', {duration:.2}); }, updateMPYear : function(y){ this.mpyear = y; var ys = this.mpYears.elements; for(var i = 1; i <= 10; i++){ var td = ys[i-1], y2; if((i%2) == 0){ y2 = y + Math.round(i * .5); td.firstChild.innerHTML = y2; td.xyear = y2; }else{ y2 = y - (5-Math.round(i * .5)); td.firstChild.innerHTML = y2; td.xyear = y2; } this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel'); } }, updateMPMonth : function(sm){ this.mpMonths.each(function(m, a, i){ m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel'); }); }, selectMPMonth: function(m){ }, onMonthClick : function(e, t){ e.stopEvent(); var el = new Ext.Element(t), pn; if(el.is('button.x-date-mp-cancel')){ this.hideMonthPicker(); } else if(el.is('button.x-date-mp-ok')){ this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate())); this.hideMonthPicker(); } else if(pn = el.up('td.x-date-mp-month', 2)){ this.mpMonths.removeClass('x-date-mp-sel'); pn.addClass('x-date-mp-sel'); this.mpSelMonth = pn.dom.xmonth; } else if(pn = el.up('td.x-date-mp-year', 2)){ this.mpYears.removeClass('x-date-mp-sel'); pn.addClass('x-date-mp-sel'); this.mpSelYear = pn.dom.xyear; } else if(el.is('a.x-date-mp-prev')){ this.updateMPYear(this.mpyear-10); } else if(el.is('a.x-date-mp-next')){ this.updateMPYear(this.mpyear+10); } }, onMonthDblClick : function(e, t){ e.stopEvent(); var el = new Ext.Element(t), pn; if(pn = el.up('td.x-date-mp-month', 2)){ this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate())); this.hideMonthPicker(); } else if(pn = el.up('td.x-date-mp-year', 2)){ this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate())); this.hideMonthPicker(); } }, hideMonthPicker : function(disableAnim){ if(this.monthPicker){ if(disableAnim === true){ this.monthPicker.hide(); }else{ this.monthPicker.slideOut('t', {duration:.2}); } } }, showPrevMonth : function(e){ this.update(this.activeDate.add("mo", -1)); }, showNextMonth : function(e){ this.update(this.activeDate.add("mo", 1)); }, showPrevYear : function(){ this.update(this.activeDate.add("y", -1)); }, showNextYear : function(){ this.update(this.activeDate.add("y", 1)); }, handleMouseWheel : function(e){ var delta = e.getWheelDelta(); if(delta > 0){ this.showPrevMonth(); e.stopEvent(); } else if(delta < 0){ this.showNextMonth(); e.stopEvent(); } }, handleDateClick : function(e, t){ e.stopEvent(); if(t.dateValue && !Ext.fly(t.parentNode).hasClass("x-date-disabled")){ this.setValue(new Date(t.dateValue)); this.fireEvent("select", this, this.value); } }, selectToday : function(){ this.setValue(new Date().clearTime()); this.fireEvent("select", this, this.value); }, update : function(date){ var vd = this.activeDate; this.activeDate = date; if(vd && this.el){ var t = date.getTime(); if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){ this.cells.removeClass("x-date-selected"); this.cells.each(function(c){ if(c.dom.firstChild.dateValue == t){ c.addClass("x-date-selected"); setTimeout(function(){ try{c.dom.firstChild.focus();}catch(e){} }, 50); return false; } }); return; } } var days = date.getDaysInMonth(); var firstOfMonth = date.getFirstDateOfMonth(); var startingPos = firstOfMonth.getDay()-this.startDay; if(startingPos <= this.startDay){ startingPos += 7; } var pm = date.add("mo", -1); var prevStart = pm.getDaysInMonth()-startingPos; var cells = this.cells.elements; var textEls = this.textNodes; days += startingPos; var day = 86400000; var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime(); var today = new Date().clearTime().getTime(); var sel = date.clearTime().getTime(); var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY; var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY; var ddMatch = this.disabledDatesRE; var ddText = this.disabledDatesText; var ddays = this.disabledDays ? this.disabledDays.join("") : false; var ddaysText = this.disabledDaysText; var format = this.format; var setCellClass = function(cal, cell){ cell.title = ""; var t = d.getTime(); cell.firstChild.dateValue = t; if(t == today){ cell.className += " x-date-today"; cell.title = cal.todayText; } if(t == sel){ cell.className += " x-date-selected"; setTimeout(function(){ try{cell.firstChild.focus();}catch(e){} }, 50); } if(t < min) { cell.className = " x-date-disabled"; cell.title = cal.minText; return; } if(t > max) { cell.className = " x-date-disabled"; cell.title = cal.maxText; return; } if(ddays){ if(ddays.indexOf(d.getDay()) != -1){ cell.title = ddaysText; cell.className = " x-date-disabled"; } } if(ddMatch && format){ var fvalue = d.dateFormat(format); if(ddMatch.test(fvalue)){ cell.title = ddText.replace("%0", fvalue); cell.className = " x-date-disabled"; } } }; var i = 0; for(; i < startingPos; i++) { textEls[i].innerHTML = (++prevStart); d.setDate(d.getDate()+1); cells[i].className = "x-date-prevday"; setCellClass(this, cells[i]); } for(; i < days; i++){ intDay = i - startingPos + 1; textEls[i].innerHTML = (intDay); d.setDate(d.getDate()+1); cells[i].className = "x-date-active"; setCellClass(this, cells[i]); } var extraDays = 0; for(; i < 42; i++) { textEls[i].innerHTML = (++extraDays); d.setDate(d.getDate()+1); cells[i].className = "x-date-nextday"; setCellClass(this, cells[i]); } this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear()); if(!this.internalRender){ var main = this.el.dom.firstChild; var w = main.offsetWidth; this.el.setWidth(w + this.el.getBorderWidth("lr")); Ext.fly(main).setWidth(w); this.internalRender = true; if(Ext.isOpera && !this.secondPass){ main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px"; this.secondPass = true; this.update.defer(10, this, [date]); } } }, beforeDestroy : function() { this.mbtn.destroy(); this.todayBtn.destroy(); } }); Ext.reg('datepicker', Ext.DatePicker); Ext.TabPanel = Ext.extend(Ext.Panel, { monitorResize : true, deferredRender : true, tabWidth: 120, minTabWidth: 30, resizeTabs:false, enableTabScroll: false, scrollIncrement : 0, scrollRepeatInterval : 400, scrollDuration : .35, animScroll : true, tabPosition: 'top', baseCls: 'x-tab-panel', autoTabs : false, autoTabSelector:'div.x-tab', activeTab : null, tabMargin : 2, plain: false, wheelIncrement : 20, idDelimiter : '__', itemCls : 'x-tab-item', elements: 'body', headerAsText: false, frame: false, hideBorders:true, initComponent : function(){ this.frame = false; Ext.TabPanel.superclass.initComponent.call(this); this.addEvents( 'beforetabchange', 'tabchange', 'contextmenu' ); this.setLayout(new Ext.layout.CardLayout({ deferredRender: this.deferredRender })); if(this.tabPosition == 'top'){ this.elements += ',header'; this.stripTarget = 'header'; }else { this.elements += ',footer'; this.stripTarget = 'footer'; } if(!this.stack){ this.stack = Ext.TabPanel.AccessStack(); } this.initItems(); }, render : function(){ Ext.TabPanel.superclass.render.apply(this, arguments); if(this.activeTab !== undefined){ var item = this.activeTab; delete this.activeTab; this.setActiveTab(item); } }, onRender : function(ct, position){ Ext.TabPanel.superclass.onRender.call(this, ct, position); if(this.plain){ var pos = this.tabPosition == 'top' ? 'header' : 'footer'; this[pos].addClass('x-tab-panel-'+pos+'-plain'); } var st = this[this.stripTarget]; this.stripWrap = st.createChild({cls:'x-tab-strip-wrap', cn:{ tag:'ul', cls:'x-tab-strip x-tab-strip-'+this.tabPosition}}); this.stripSpacer = st.createChild({cls:'x-tab-strip-spacer'}); this.strip = new Ext.Element(this.stripWrap.dom.firstChild); this.edge = this.strip.createChild({tag:'li', cls:'x-tab-edge'}); this.strip.createChild({cls:'x-clear'}); this.body.addClass('x-tab-panel-body-'+this.tabPosition); if(!this.itemTpl){ var tt = new Ext.Template( '<li class="{cls}" id="{id}"><a class="x-tab-strip-close" onclick="return false;"></a>', '<a class="x-tab-right" href="#" onclick="return false;"><em class="x-tab-left">', '<span class="x-tab-strip-inner"><span class="x-tab-strip-text {iconCls}">{text}</span></span>', '</em></a></li>' ); tt.disableFormats = true; tt.compile(); Ext.TabPanel.prototype.itemTpl = tt; } this.items.each(this.initTab, this); }, afterRender : function(){ Ext.TabPanel.superclass.afterRender.call(this); if(this.autoTabs){ this.readTabs(false); } }, initEvents : function(){ Ext.TabPanel.superclass.initEvents.call(this); this.on('add', this.onAdd, this); this.on('remove', this.onRemove, this); this.strip.on('mousedown', this.onStripMouseDown, this); this.strip.on('click', this.onStripClick, this); this.strip.on('contextmenu', this.onStripContextMenu, this); if(this.enableTabScroll){ this.strip.on('mousewheel', this.onWheel, this); } }, findTargets : function(e){ var item = null; var itemEl = e.getTarget('li', this.strip); if(itemEl){ item = this.getComponent(itemEl.id.split(this.idDelimiter)[1]); if(item.disabled){ return { close : null, item : null, el : null }; } } return { close : e.getTarget('.x-tab-strip-close', this.strip), item : item, el : itemEl }; }, onStripMouseDown : function(e){ e.preventDefault(); if(e.button != 0){ return; } var t = this.findTargets(e); if(t.close){ this.remove(t.item); return; } if(t.item && t.item != this.activeTab){ this.setActiveTab(t.item); } }, onStripClick : function(e){ var t = this.findTargets(e); if(!t.close && t.item && t.item != this.activeTab){ this.setActiveTab(t.item); } }, onStripContextMenu : function(e){ e.preventDefault(); var t = this.findTargets(e); if(t.item){ this.fireEvent('contextmenu', this, t.item, e); } }, readTabs : function(removeExisting){ if(removeExisting === true){ this.items.each(function(item){ this.remove(item); }, this); } var tabs = this.el.query(this.autoTabSelector); for(var i = 0, len = tabs.length; i < len; i++){ var tab = tabs[i]; var title = tab.getAttribute('title'); tab.removeAttribute('title'); this.add({ title: title, el: tab }); } }, initTab : function(item, index){ var before = this.strip.dom.childNodes[index]; var cls = item.closable ? 'x-tab-strip-closable' : ''; if(item.disabled){ cls += ' x-item-disabled'; } if(item.iconCls){ cls += ' x-tab-with-icon'; } if(item.tabCls){ cls += ' ' + item.tabCls; } var p = { id: this.id + this.idDelimiter + item.getItemId(), text: item.title, cls: cls, iconCls: item.iconCls || '' }; var el = before ? this.itemTpl.insertBefore(before, p) : this.itemTpl.append(this.strip, p); Ext.fly(el).addClassOnOver('x-tab-strip-over'); if(item.tabTip){ Ext.fly(el).child('span.x-tab-strip-text', true).qtip = item.tabTip; } item.on('disable', this.onItemDisabled, this); item.on('enable', this.onItemEnabled, this); item.on('titlechange', this.onItemTitleChanged, this); item.on('beforeshow', this.onBeforeShowItem, this); }, onAdd : function(tp, item, index){ this.initTab(item, index); if(this.items.getCount() == 1){ this.syncSize(); } this.delegateUpdates(); }, onBeforeAdd : function(item){ var existing = item.events ? (this.items.containsKey(item.getItemId()) ? item : null) : this.items.get(item); if(existing){ this.setActiveTab(item); return false; } Ext.TabPanel.superclass.onBeforeAdd.apply(this, arguments); var es = item.elements; item.elements = es ? es.replace(',header', '') : es; item.border = (item.border === true); }, onRemove : function(tp, item){ Ext.removeNode(this.getTabEl(item)); this.stack.remove(item); if(item == this.activeTab){ var next = this.stack.next(); if(next){ this.setActiveTab(next); }else{ this.setActiveTab(0); } } this.delegateUpdates(); }, onBeforeShowItem : function(item){ if(item != this.activeTab){ this.setActiveTab(item); return false; } }, onItemDisabled : function(item){ var el = this.getTabEl(item); if(el){ Ext.fly(el).addClass('x-item-disabled'); } this.stack.remove(item); }, onItemEnabled : function(item){ var el = this.getTabEl(item); if(el){ Ext.fly(el).removeClass('x-item-disabled'); } }, onItemTitleChanged : function(item){ var el = this.getTabEl(item); if(el){ Ext.fly(el).child('span.x-tab-strip-text', true).innerHTML = item.title; } }, getTabEl : function(item){ var itemId = (typeof item === 'number')?this.items.items[item].getItemId() : item.getItemId(); return document.getElementById(this.id+this.idDelimiter+itemId); }, onResize : function(){ Ext.TabPanel.superclass.onResize.apply(this, arguments); this.delegateUpdates(); }, beginUpdate : function(){ this.suspendUpdates = true; }, endUpdate : function(){ this.suspendUpdates = false; this.delegateUpdates(); }, hideTabStripItem : function(item){ item = this.getComponent(item); var el = this.getTabEl(item); if(el){ el.style.display = 'none'; this.delegateUpdates(); } }, unhideTabStripItem : function(item){ item = this.getComponent(item); var el = this.getTabEl(item); if(el){ el.style.display = ''; this.delegateUpdates(); } }, delegateUpdates : function(){ if(this.suspendUpdates){ return; } if(this.resizeTabs && this.rendered){ this.autoSizeTabs(); } if(this.enableTabScroll && this.rendered){ this.autoScrollTabs(); } }, autoSizeTabs : function(){ var count = this.items.length; var ce = this.tabPosition != 'bottom' ? 'header' : 'footer'; var ow = this[ce].dom.offsetWidth; var aw = this[ce].dom.clientWidth; if(!this.resizeTabs || count < 1 || !aw){ return; } var each = Math.max(Math.min(Math.floor((aw-4) / count) - this.tabMargin, this.tabWidth), this.minTabWidth); this.lastTabWidth = each; var lis = this.stripWrap.dom.getElementsByTagName('li'); for(var i = 0, len = lis.length-1; i < len; i++) { var li = lis[i]; var inner = li.childNodes[1].firstChild.firstChild; var tw = li.offsetWidth; var iw = inner.offsetWidth; inner.style.width = (each - (tw-iw)) + 'px'; } }, adjustBodyWidth : function(w){ if(this.header){ this.header.setWidth(w); } if(this.footer){ this.footer.setWidth(w); } return w; }, setActiveTab : function(item){ item = this.getComponent(item); if(!item || this.fireEvent('beforetabchange', this, item, this.activeTab) === false){ return; } if(!this.rendered){ this.activeTab = item; return; } if(this.activeTab != item){ if(this.activeTab){ var oldEl = this.getTabEl(this.activeTab); if(oldEl){ Ext.fly(oldEl).removeClass('x-tab-strip-active'); } this.activeTab.fireEvent('deactivate', this.activeTab); } var el = this.getTabEl(item); Ext.fly(el).addClass('x-tab-strip-active'); this.activeTab = item; this.stack.add(item); this.layout.setActiveItem(item); if(this.layoutOnTabChange && item.doLayout){ item.doLayout(); } if(this.scrolling){ this.scrollToTab(item, this.animScroll); } item.fireEvent('activate', item); this.fireEvent('tabchange', this, item); } }, getActiveTab : function(){ return this.activeTab || null; }, getItem : function(item){ return this.getComponent(item); }, autoScrollTabs : function(){ var count = this.items.length; var ow = this.header.dom.offsetWidth; var tw = this.header.dom.clientWidth; var wrap = this.stripWrap; var wd = wrap.dom; var cw = wd.offsetWidth; var pos = this.getScrollPos(); var l = this.edge.getOffsetsTo(this.stripWrap)[0] + pos; if(!this.enableTabScroll || count < 1 || cw < 20){ return; } if(l <= tw){ wd.scrollLeft = 0; wrap.setWidth(tw); if(this.scrolling){ this.scrolling = false; this.header.removeClass('x-tab-scrolling'); this.scrollLeft.hide(); this.scrollRight.hide(); if(Ext.isAir){ wd.style.marginLeft = ''; wd.style.marginRight = ''; } } }else{ if(!this.scrolling){ this.header.addClass('x-tab-scrolling'); if(Ext.isAir){ wd.style.marginLeft = '18px'; wd.style.marginRight = '18px'; } } tw -= wrap.getMargins('lr'); wrap.setWidth(tw > 20 ? tw : 20); if(!this.scrolling){ if(!this.scrollLeft){ this.createScrollers(); }else{ this.scrollLeft.show(); this.scrollRight.show(); } } this.scrolling = true; if(pos > (l-tw)){ wd.scrollLeft = l-tw; }else{ this.scrollToTab(this.activeTab, false); } this.updateScrollButtons(); } }, createScrollers : function(){ var h = this.stripWrap.dom.offsetHeight; var sl = this.header.insertFirst({ cls:'x-tab-scroller-left' }); sl.setHeight(h); sl.addClassOnOver('x-tab-scroller-left-over'); this.leftRepeater = new Ext.util.ClickRepeater(sl, { interval : this.scrollRepeatInterval, handler: this.onScrollLeft, scope: this }); this.scrollLeft = sl; var sr = this.header.insertFirst({ cls:'x-tab-scroller-right' }); sr.setHeight(h); sr.addClassOnOver('x-tab-scroller-right-over'); this.rightRepeater = new Ext.util.ClickRepeater(sr, { interval : this.scrollRepeatInterval, handler: this.onScrollRight, scope: this }); this.scrollRight = sr; }, getScrollWidth : function(){ return this.edge.getOffsetsTo(this.stripWrap)[0] + this.getScrollPos(); }, getScrollPos : function(){ return parseInt(this.stripWrap.dom.scrollLeft, 10) || 0; }, getScrollArea : function(){ return parseInt(this.stripWrap.dom.clientWidth, 10) || 0; }, getScrollAnim : function(){ return {duration:this.scrollDuration, callback: this.updateScrollButtons, scope: this}; }, getScrollIncrement : function(){ return this.scrollIncrement || (this.resizeTabs ? this.lastTabWidth+2 : 100); }, scrollToTab : function(item, animate){ if(!item){ return; } var el = this.getTabEl(item); var pos = this.getScrollPos(), area = this.getScrollArea(); var left = Ext.fly(el).getOffsetsTo(this.stripWrap)[0] + pos; var right = left + el.offsetWidth; if(left < pos){ this.scrollTo(left, animate); }else if(right > (pos + area)){ this.scrollTo(right - area, animate); } }, scrollTo : function(pos, animate){ this.stripWrap.scrollTo('left', pos, animate ? this.getScrollAnim() : false); if(!animate){ this.updateScrollButtons(); } }, onWheel : function(e){ var d = e.getWheelDelta()*this.wheelIncrement*-1; e.stopEvent(); var pos = this.getScrollPos(); var newpos = pos + d; var sw = this.getScrollWidth()-this.getScrollArea(); var s = Math.max(0, Math.min(sw, newpos)); if(s != pos){ this.scrollTo(s, false); } }, onScrollRight : function(){ var sw = this.getScrollWidth()-this.getScrollArea(); var pos = this.getScrollPos(); var s = Math.min(sw, pos + this.getScrollIncrement()); if(s != pos){ this.scrollTo(s, this.animScroll); } }, onScrollLeft : function(){ var pos = this.getScrollPos(); var s = Math.max(0, pos - this.getScrollIncrement()); if(s != pos){ this.scrollTo(s, this.animScroll); } }, updateScrollButtons : function(){ var pos = this.getScrollPos(); this.scrollLeft[pos == 0 ? 'addClass' : 'removeClass']('x-tab-scroller-left-disabled'); this.scrollRight[pos >= (this.getScrollWidth()-this.getScrollArea()) ? 'addClass' : 'removeClass']('x-tab-scroller-right-disabled'); } }); Ext.reg('tabpanel', Ext.TabPanel); Ext.TabPanel.prototype.activate = Ext.TabPanel.prototype.setActiveTab; Ext.TabPanel.AccessStack = function(){ var items = []; return { add : function(item){ items.push(item); if(items.length > 10){ items.shift(); } }, remove : function(item){ var s = []; for(var i = 0, len = items.length; i < len; i++) { if(items[i] != item){ s.push(items[i]); } } items = s; }, next : function(){ return items.pop(); } }; }; Ext.Button = Ext.extend(Ext.Component, { hidden : false, disabled : false, pressed : false, enableToggle: false, menuAlign : "tl-bl?", type : 'button', menuClassTarget: 'tr', clickEvent : 'click', handleMouseEvents : true, tooltipType : 'qtip', buttonSelector : "button:first", initComponent : function(){ Ext.Button.superclass.initComponent.call(this); this.addEvents( "click", "toggle", 'mouseover', 'mouseout', 'menushow', 'menuhide', 'menutriggerover', 'menutriggerout' ); if(this.menu){ this.menu = Ext.menu.MenuMgr.get(this.menu); } if(typeof this.toggleGroup === 'string'){ this.enableToggle = true; } }, onRender : function(ct, position){ if(!this.template){ if(!Ext.Button.buttonTemplate){ Ext.Button.buttonTemplate = new Ext.Template( '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>', '<td class="x-btn-left"><i>&#160;</i></td><td class="x-btn-center"><em unselectable="on"><button class="x-btn-text" type="{1}">{0}</button></em></td><td class="x-btn-right"><i>&#160;</i></td>', "</tr></tbody></table>"); } this.template = Ext.Button.buttonTemplate; } var btn, targs = [this.text || '&#160;', this.type]; if(position){ btn = this.template.insertBefore(position, targs, true); }else{ btn = this.template.append(ct, targs, true); } var btnEl = btn.child(this.buttonSelector); btnEl.on('focus', this.onFocus, this); btnEl.on('blur', this.onBlur, this); this.initButtonEl(btn, btnEl); if(this.menu){ this.el.child(this.menuClassTarget).addClass("x-btn-with-menu"); } Ext.ButtonToggleMgr.register(this); }, initButtonEl : function(btn, btnEl){ this.el = btn; btn.addClass("x-btn"); if(this.icon){ btnEl.setStyle('background-image', 'url(' +this.icon +')'); } if(this.iconCls){ btnEl.addClass(this.iconCls); if(!this.cls){ btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon'); } } if(this.tabIndex !== undefined){ btnEl.dom.tabIndex = this.tabIndex; } if(this.tooltip){ if(typeof this.tooltip == 'object'){ Ext.QuickTips.register(Ext.apply({ target: btnEl.id }, this.tooltip)); } else { btnEl.dom[this.tooltipType] = this.tooltip; } } if(this.pressed){ this.el.addClass("x-btn-pressed"); } if(this.handleMouseEvents){ btn.on("mouseover", this.onMouseOver, this); btn.on("mousedown", this.onMouseDown, this); } if(this.menu){ this.menu.on("show", this.onMenuShow, this); this.menu.on("hide", this.onMenuHide, this); } if(this.id){ this.el.dom.id = this.el.id = this.id; } if(this.repeat){ var repeater = new Ext.util.ClickRepeater(btn, typeof this.repeat == "object" ? this.repeat : {} ); repeater.on("click", this.onClick, this); } btn.on(this.clickEvent, this.onClick, this); }, afterRender : function(){ Ext.Button.superclass.afterRender.call(this); if(Ext.isIE6){ this.autoWidth.defer(1, this); }else{ this.autoWidth(); } }, setIconClass : function(cls){ if(this.el){ this.el.child(this.buttonSelector).replaceClass(this.iconCls, cls); } this.iconCls = cls; }, beforeDestroy: function(){ if(this.rendered){ var btn = this.el.child(this.buttonSelector); if(btn){ btn.removeAllListeners(); } } if(this.menu){ Ext.destroy(this.menu); } }, onDestroy : function(){ if(this.rendered){ Ext.ButtonToggleMgr.unregister(this); } }, autoWidth : function(){ if(this.el){ this.el.setWidth("auto"); if(Ext.isIE7 && Ext.isStrict){ var ib = this.el.child(this.buttonSelector); if(ib && ib.getWidth() > 20){ ib.clip(); ib.setWidth(Ext.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr')); } } if(this.minWidth){ if(this.el.getWidth() < this.minWidth){ this.el.setWidth(this.minWidth); } } } }, setHandler : function(handler, scope){ this.handler = handler; this.scope = scope; }, setText : function(text){ this.text = text; if(this.el){ this.el.child("td.x-btn-center " + this.buttonSelector).update(text); } this.autoWidth(); }, getText : function(){ return this.text; }, toggle : function(state){ state = state === undefined ? !this.pressed : state; if(state != this.pressed){ if(state){ this.el.addClass("x-btn-pressed"); this.pressed = true; this.fireEvent("toggle", this, true); }else{ this.el.removeClass("x-btn-pressed"); this.pressed = false; this.fireEvent("toggle", this, false); } if(this.toggleHandler){ this.toggleHandler.call(this.scope || this, this, state); } } }, focus : function(){ this.el.child(this.buttonSelector).focus(); }, onDisable : function(){ if(this.el){ if(!Ext.isIE6 || !this.text){ this.el.addClass(this.disabledClass); } this.el.dom.disabled = true; } this.disabled = true; }, onEnable : function(){ if(this.el){ if(!Ext.isIE6 || !this.text){ this.el.removeClass(this.disabledClass); } this.el.dom.disabled = false; } this.disabled = false; }, showMenu : function(){ if(this.menu){ this.menu.show(this.el, this.menuAlign); } return this; }, hideMenu : function(){ if(this.menu){ this.menu.hide(); } return this; }, hasVisibleMenu : function(){ return this.menu && this.menu.isVisible(); }, onClick : function(e){ if(e){ e.preventDefault(); } if(e.button != 0){ return; } if(!this.disabled){ if(this.enableToggle && (this.allowDepress !== false || !this.pressed)){ this.toggle(); } if(this.menu && !this.menu.isVisible() && !this.ignoreNextClick){ this.showMenu(); } this.fireEvent("click", this, e); if(this.handler){ this.handler.call(this.scope || this, this, e); } } }, isMenuTriggerOver : function(e, internal){ return this.menu && !internal; }, isMenuTriggerOut : function(e, internal){ return this.menu && !internal; }, onMouseOver : function(e){ if(!this.disabled){ var internal = e.within(this.el, true); if(!internal){ this.el.addClass("x-btn-over"); Ext.getDoc().on('mouseover', this.monitorMouseOver, this); this.fireEvent('mouseover', this, e); } if(this.isMenuTriggerOver(e, internal)){ this.fireEvent('menutriggerover', this, this.menu, e); } } }, monitorMouseOver : function(e){ if(e.target != this.el.dom && !e.within(this.el)){ Ext.getDoc().un('mouseover', this.monitorMouseOver, this); this.onMouseOut(e); } }, onMouseOut : function(e){ var internal = e.within(this.el) && e.target != this.el.dom; this.el.removeClass("x-btn-over"); this.fireEvent('mouseout', this, e); if(this.isMenuTriggerOut(e, internal)){ this.fireEvent('menutriggerout', this, this.menu, e); } }, onFocus : function(e){ if(!this.disabled){ this.el.addClass("x-btn-focus"); } }, onBlur : function(e){ this.el.removeClass("x-btn-focus"); }, getClickEl : function(e, isUp){ return this.el; }, onMouseDown : function(e){ if(!this.disabled && e.button == 0){ this.getClickEl(e).addClass("x-btn-click"); Ext.getDoc().on('mouseup', this.onMouseUp, this); } }, onMouseUp : function(e){ if(e.button == 0){ this.getClickEl(e, true).removeClass("x-btn-click"); Ext.getDoc().un('mouseup', this.onMouseUp, this); } }, onMenuShow : function(e){ this.ignoreNextClick = 0; this.el.addClass("x-btn-menu-active"); this.fireEvent('menushow', this, this.menu); }, onMenuHide : function(e){ this.el.removeClass("x-btn-menu-active"); this.ignoreNextClick = this.restoreClick.defer(250, this); this.fireEvent('menuhide', this, this.menu); }, restoreClick : function(){ this.ignoreNextClick = 0; } }); Ext.reg('button', Ext.Button); Ext.ButtonToggleMgr = function(){ var groups = {}; function toggleGroup(btn, state){ if(state){ var g = groups[btn.toggleGroup]; for(var i = 0, l = g.length; i < l; i++){ if(g[i] != btn){ g[i].toggle(false); } } } } return { register : function(btn){ if(!btn.toggleGroup){ return; } var g = groups[btn.toggleGroup]; if(!g){ g = groups[btn.toggleGroup] = []; } g.push(btn); btn.on("toggle", toggleGroup); }, unregister : function(btn){ if(!btn.toggleGroup){ return; } var g = groups[btn.toggleGroup]; if(g){ g.remove(btn); btn.un("toggle", toggleGroup); } } }; }(); Ext.SplitButton = Ext.extend(Ext.Button, { arrowSelector : 'button:last', initComponent : function(){ Ext.SplitButton.superclass.initComponent.call(this); this.addEvents("arrowclick"); }, onRender : function(ct, position){ var tpl = new Ext.Template( '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>', '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>', '<tr><td class="x-btn-left"><i>&#160;</i></td><td class="x-btn-center"><button class="x-btn-text" type="{1}">{0}</button></td></tr>', "</tbody></table></td><td>", '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>', '<tr><td class="x-btn-center"><button class="x-btn-menu-arrow-el" type="button">&#160;</button></td><td class="x-btn-right"><i>&#160;</i></td></tr>', "</tbody></table></td></tr></table>" ); var btn, targs = [this.text || '&#160;', this.type]; if(position){ btn = tpl.insertBefore(position, targs, true); }else{ btn = tpl.append(ct, targs, true); } var btnEl = btn.child(this.buttonSelector); this.initButtonEl(btn, btnEl); this.arrowBtnTable = btn.child("table:last"); if(this.arrowTooltip){ btn.child(this.arrowSelector).dom[this.tooltipType] = this.arrowTooltip; } }, autoWidth : function(){ if(this.el){ var tbl = this.el.child("table:first"); var tbl2 = this.el.child("table:last"); this.el.setWidth("auto"); tbl.setWidth("auto"); if(Ext.isIE7 && Ext.isStrict){ var ib = this.el.child(this.buttonSelector); if(ib && ib.getWidth() > 20){ ib.clip(); ib.setWidth(Ext.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr')); } } if(this.minWidth){ if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){ tbl.setWidth(this.minWidth-tbl2.getWidth()); } } this.el.setWidth(tbl.getWidth()+tbl2.getWidth()); } }, setArrowHandler : function(handler, scope){ this.arrowHandler = handler; this.scope = scope; }, onClick : function(e){ e.preventDefault(); if(!this.disabled){ if(e.getTarget(".x-btn-menu-arrow-wrap")){ if(this.menu && !this.menu.isVisible() && !this.ignoreNextClick){ this.showMenu(); } this.fireEvent("arrowclick", this, e); if(this.arrowHandler){ this.arrowHandler.call(this.scope || this, this, e); } }else{ if(this.enableToggle){ this.toggle(); } this.fireEvent("click", this, e); if(this.handler){ this.handler.call(this.scope || this, this, e); } } } }, getClickEl : function(e, isUp){ if(!isUp){ return (this.lastClickEl = e.getTarget("table", 10, true)); } return this.lastClickEl; }, onDisable : function(){ if(this.el){ if(!Ext.isIE6){ this.el.addClass("x-item-disabled"); } this.el.child(this.buttonSelector).dom.disabled = true; this.el.child(this.arrowSelector).dom.disabled = true; } this.disabled = true; }, onEnable : function(){ if(this.el){ if(!Ext.isIE6){ this.el.removeClass("x-item-disabled"); } this.el.child(this.buttonSelector).dom.disabled = false; this.el.child(this.arrowSelector).dom.disabled = false; } this.disabled = false; }, isMenuTriggerOver : function(e){ return this.menu && e.within(this.arrowBtnTable) && !e.within(this.arrowBtnTable, true); }, isMenuTriggerOut : function(e, internal){ return this.menu && !e.within(this.arrowBtnTable); }, onDestroy : function(){ Ext.destroy(this.arrowBtnTable); Ext.SplitButton.superclass.onDestroy.call(this); } }); Ext.MenuButton = Ext.SplitButton; Ext.reg('splitbutton', Ext.SplitButton); Ext.CycleButton = Ext.extend(Ext.SplitButton, { getItemText : function(item){ if(item && this.showText === true){ var text = ''; if(this.prependText){ text += this.prependText; } text += item.text; return text; } return undefined; }, setActiveItem : function(item, suppressEvent){ if(typeof item != 'object'){ item = this.menu.items.get(item); } if(item){ if(!this.rendered){ this.text = this.getItemText(item); this.iconCls = item.iconCls; }else{ var t = this.getItemText(item); if(t){ this.setText(t); } this.setIconClass(item.iconCls); } this.activeItem = item; if(!item.checked){ item.setChecked(true, true); } if(this.forceIcon){ this.setIconClass(this.forceIcon); } if(!suppressEvent){ this.fireEvent('change', this, item); } } }, getActiveItem : function(){ return this.activeItem; }, initComponent : function(){ this.addEvents( "change" ); if(this.changeHandler){ this.on('change', this.changeHandler, this.scope||this); delete this.changeHandler; } this.itemCount = this.items.length; this.menu = {cls:'x-cycle-menu', items:[]}; var checked; for(var i = 0, len = this.itemCount; i < len; i++){ var item = this.items[i]; item.group = item.group || this.id; item.itemIndex = i; item.checkHandler = this.checkHandler; item.scope = this; item.checked = item.checked || false; this.menu.items.push(item); if(item.checked){ checked = item; } } this.setActiveItem(checked, true); Ext.CycleButton.superclass.initComponent.call(this); this.on('click', this.toggleSelected, this); }, checkHandler : function(item, pressed){ if(pressed){ this.setActiveItem(item); } }, toggleSelected : function(){ this.menu.render(); var nextIdx, checkItem; for (var i = 1; i < this.itemCount; i++) { nextIdx = (this.activeItem.itemIndex + i) % this.itemCount; checkItem = this.menu.items.itemAt(nextIdx); if (!checkItem.disabled) { checkItem.setChecked(true); break; } } } }); Ext.reg('cycle', Ext.CycleButton); Ext.Toolbar = function(config){ if(Ext.isArray(config)){ config = {buttons:config}; } Ext.Toolbar.superclass.constructor.call(this, config); }; (function(){ var T = Ext.Toolbar; Ext.extend(T, Ext.BoxComponent, { trackMenus : true, initComponent : function(){ T.superclass.initComponent.call(this); if(this.items){ this.buttons = this.items; } this.items = new Ext.util.MixedCollection(false, function(o){ return o.itemId || o.id || Ext.id(); }); }, autoCreate: { cls:'x-toolbar x-small-editor', html:'<table cellspacing="0"><tr></tr></table>' }, onRender : function(ct, position){ this.el = ct.createChild(Ext.apply({ id: this.id },this.autoCreate), position); this.tr = this.el.child("tr", true); }, afterRender : function(){ T.superclass.afterRender.call(this); if(this.buttons){ this.add.apply(this, this.buttons); delete this.buttons; } }, add : function(){ var a = arguments, l = a.length; for(var i = 0; i < l; i++){ var el = a[i]; if(el.isFormField){ this.addField(el); }else if(el.render){ this.addItem(el); }else if(typeof el == "string"){ if(el == "separator" || el == "-"){ this.addSeparator(); }else if(el == " "){ this.addSpacer(); }else if(el == "->"){ this.addFill(); }else{ this.addText(el); } }else if(el.tagName){ this.addElement(el); }else if(typeof el == "object"){ if(el.xtype){ this.addField(Ext.ComponentMgr.create(el, 'button')); }else{ this.addButton(el); } } } }, addSeparator : function(){ return this.addItem(new T.Separator()); }, addSpacer : function(){ return this.addItem(new T.Spacer()); }, addFill : function(){ return this.addItem(new T.Fill()); }, addElement : function(el){ return this.addItem(new T.Item(el)); }, addItem : function(item){ var td = this.nextBlock(); this.initMenuTracking(item); item.render(td); this.items.add(item); return item; }, addButton : function(config){ if(Ext.isArray(config)){ var buttons = []; for(var i = 0, len = config.length; i < len; i++) { buttons.push(this.addButton(config[i])); } return buttons; } var b = config; if(!(config instanceof T.Button)){ b = config.split ? new T.SplitButton(config) : new T.Button(config); } var td = this.nextBlock(); this.initMenuTracking(b); b.render(td); this.items.add(b); return b; }, initMenuTracking : function(item){ if(this.trackMenus && item.menu){ item.on({ 'menutriggerover' : this.onButtonTriggerOver, 'menushow' : this.onButtonMenuShow, 'menuhide' : this.onButtonMenuHide, scope: this }) } }, addText : function(text){ return this.addItem(new T.TextItem(text)); }, insertButton : function(index, item){ if(Ext.isArray(item)){ var buttons = []; for(var i = 0, len = item.length; i < len; i++) { buttons.push(this.insertButton(index + i, item[i])); } return buttons; } if (!(item instanceof T.Button)){ item = new T.Button(item); } var td = document.createElement("td"); this.tr.insertBefore(td, this.tr.childNodes[index]); this.initMenuTracking(item); item.render(td); this.items.insert(index, item); return item; }, addDom : function(config, returnEl){ var td = this.nextBlock(); Ext.DomHelper.overwrite(td, config); var ti = new T.Item(td.firstChild); ti.render(td); this.items.add(ti); return ti; }, addField : function(field){ var td = this.nextBlock(); field.render(td); var ti = new T.Item(td.firstChild); ti.render(td); this.items.add(ti); return ti; }, nextBlock : function(){ var td = document.createElement("td"); this.tr.appendChild(td); return td; }, onDestroy : function(){ Ext.Toolbar.superclass.onDestroy.call(this); if(this.rendered){ if(this.items){ Ext.destroy.apply(Ext, this.items.items); } Ext.Element.uncache(this.tr); } }, onDisable : function(){ this.items.each(function(item){ if(item.disable){ item.disable(); } }); }, onEnable : function(){ this.items.each(function(item){ if(item.enable){ item.enable(); } }); }, onButtonTriggerOver : function(btn){ if(this.activeMenuBtn && this.activeMenuBtn != btn){ this.activeMenuBtn.hideMenu(); btn.showMenu(); this.activeMenuBtn = btn; } }, onButtonMenuShow : function(btn){ this.activeMenuBtn = btn; }, onButtonMenuHide : function(btn){ delete this.activeMenuBtn; } }); Ext.reg('toolbar', Ext.Toolbar); T.Item = function(el){ this.el = Ext.getDom(el); this.id = Ext.id(this.el); this.hidden = false; }; T.Item.prototype = { getEl : function(){ return this.el; }, render : function(td){ this.td = td; td.appendChild(this.el); }, destroy : function(){ if(this.td && this.td.parentNode){ this.td.parentNode.removeChild(this.td); } }, show: function(){ this.hidden = false; this.td.style.display = ""; }, hide: function(){ this.hidden = true; this.td.style.display = "none"; }, setVisible: function(visible){ if(visible) { this.show(); }else{ this.hide(); } }, focus : function(){ Ext.fly(this.el).focus(); }, disable : function(){ Ext.fly(this.td).addClass("x-item-disabled"); this.disabled = true; this.el.disabled = true; }, enable : function(){ Ext.fly(this.td).removeClass("x-item-disabled"); this.disabled = false; this.el.disabled = false; } }; Ext.reg('tbitem', T.Item); T.Separator = function(){ var s = document.createElement("span"); s.className = "ytb-sep"; T.Separator.superclass.constructor.call(this, s); }; Ext.extend(T.Separator, T.Item, { enable:Ext.emptyFn, disable:Ext.emptyFn, focus:Ext.emptyFn }); Ext.reg('tbseparator', T.Separator); T.Spacer = function(){ var s = document.createElement("div"); s.className = "ytb-spacer"; T.Spacer.superclass.constructor.call(this, s); }; Ext.extend(T.Spacer, T.Item, { enable:Ext.emptyFn, disable:Ext.emptyFn, focus:Ext.emptyFn }); Ext.reg('tbspacer', T.Spacer); T.Fill = Ext.extend(T.Spacer, { render : function(td){ td.style.width = '100%'; T.Fill.superclass.render.call(this, td); } }); Ext.reg('tbfill', T.Fill); T.TextItem = function(t){ var s = document.createElement("span"); s.className = "ytb-text"; s.innerHTML = t.text ? t.text : t; T.TextItem.superclass.constructor.call(this, s); }; Ext.extend(T.TextItem, T.Item, { enable:Ext.emptyFn, disable:Ext.emptyFn, focus:Ext.emptyFn }); Ext.reg('tbtext', T.TextItem); T.Button = Ext.extend(Ext.Button, { hideParent : true, onDestroy : function(){ T.Button.superclass.onDestroy.call(this); if(this.container){ this.container.remove(); } } }); Ext.reg('tbbutton', T.Button); T.SplitButton = Ext.extend(Ext.SplitButton, { hideParent : true, onDestroy : function(){ T.SplitButton.superclass.onDestroy.call(this); if(this.container){ this.container.remove(); } } }); Ext.reg('tbsplit', T.SplitButton); T.MenuButton = T.SplitButton; })(); Ext.PagingToolbar = Ext.extend(Ext.Toolbar, { pageSize: 20, displayMsg : 'Displaying {0} - {1} of {2}', emptyMsg : 'No data to display', beforePageText : "Page", afterPageText : "of {0}", firstText : "First Page", prevText : "Previous Page", nextText : "Next Page", lastText : "Last Page", refreshText : "Refresh", paramNames : {start: 'start', limit: 'limit'}, initComponent : function(){ Ext.PagingToolbar.superclass.initComponent.call(this); this.cursor = 0; this.bind(this.store); }, onRender : function(ct, position){ Ext.PagingToolbar.superclass.onRender.call(this, ct, position); this.first = this.addButton({ tooltip: this.firstText, iconCls: "x-tbar-page-first", disabled: true, handler: this.onClick.createDelegate(this, ["first"]) }); this.prev = this.addButton({ tooltip: this.prevText, iconCls: "x-tbar-page-prev", disabled: true, handler: this.onClick.createDelegate(this, ["prev"]) }); this.addSeparator(); this.add(this.beforePageText); this.field = Ext.get(this.addDom({ tag: "input", type: "text", size: "3", value: "1", cls: "x-tbar-page-number" }).el); this.field.on("keydown", this.onPagingKeydown, this); this.field.on("focus", function(){this.dom.select();}); this.afterTextEl = this.addText(String.format(this.afterPageText, 1)); this.field.setHeight(18); this.addSeparator(); this.next = this.addButton({ tooltip: this.nextText, iconCls: "x-tbar-page-next", disabled: true, handler: this.onClick.createDelegate(this, ["next"]) }); this.last = this.addButton({ tooltip: this.lastText, iconCls: "x-tbar-page-last", disabled: true, handler: this.onClick.createDelegate(this, ["last"]) }); this.addSeparator(); this.loading = this.addButton({ tooltip: this.refreshText, iconCls: "x-tbar-loading", handler: this.onClick.createDelegate(this, ["refresh"]) }); if(this.displayInfo){ this.displayEl = Ext.fly(this.el.dom).createChild({cls:'x-paging-info'}); } if(this.dsLoaded){ this.onLoad.apply(this, this.dsLoaded); } }, updateInfo : function(){ if(this.displayEl){ var count = this.store.getCount(); var msg = count == 0 ? this.emptyMsg : String.format( this.displayMsg, this.cursor+1, this.cursor+count, this.store.getTotalCount() ); this.displayEl.update(msg); } }, onLoad : function(store, r, o){ if(!this.rendered){ this.dsLoaded = [store, r, o]; return; } this.cursor = o.params ? o.params[this.paramNames.start] : 0; var d = this.getPageData(), ap = d.activePage, ps = d.pages; this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages); this.field.dom.value = ap; this.first.setDisabled(ap == 1); this.prev.setDisabled(ap == 1); this.next.setDisabled(ap == ps); this.last.setDisabled(ap == ps); this.loading.enable(); this.updateInfo(); }, getPageData : function(){ var total = this.store.getTotalCount(); return { total : total, activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize), pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize) }; }, onLoadError : function(){ if(!this.rendered){ return; } this.loading.enable(); }, readPage : function(d){ var v = this.field.dom.value, pageNum; if (!v || isNaN(pageNum = parseInt(v, 10))) { this.field.dom.value = d.activePage; return false; } return pageNum; }, onPagingKeydown : function(e){ var k = e.getKey(), d = this.getPageData(), pageNum; if (k == e.RETURN) { e.stopEvent(); if(pageNum = this.readPage(d)){ pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1; this.doLoad(pageNum * this.pageSize); } }else if (k == e.HOME || k == e.END){ e.stopEvent(); pageNum = k == e.HOME ? 1 : d.pages; this.field.dom.value = pageNum; }else if (k == e.UP || k == e.PAGEUP || k == e.DOWN || k == e.PAGEDOWN){ e.stopEvent(); if(pageNum = this.readPage(d)){ var increment = e.shiftKey ? 10 : 1; if(k == e.DOWN || k == e.PAGEDOWN){ increment *= -1; } pageNum += increment; if(pageNum >= 1 & pageNum <= d.pages){ this.field.dom.value = pageNum; } } } }, beforeLoad : function(){ if(this.rendered && this.loading){ this.loading.disable(); } }, doLoad : function(start){ var o = {}, pn = this.paramNames; o[pn.start] = start; o[pn.limit] = this.pageSize; this.store.load({params:o}); }, onClick : function(which){ var store = this.store; switch(which){ case "first": this.doLoad(0); break; case "prev": this.doLoad(Math.max(0, this.cursor-this.pageSize)); break; case "next": this.doLoad(this.cursor+this.pageSize); break; case "last": var total = store.getTotalCount(); var extra = total % this.pageSize; var lastStart = extra ? (total - extra) : total-this.pageSize; this.doLoad(lastStart); break; case "refresh": this.doLoad(this.cursor); break; } }, unbind : function(store){ store = Ext.StoreMgr.lookup(store); store.un("beforeload", this.beforeLoad, this); store.un("load", this.onLoad, this); store.un("loadexception", this.onLoadError, this); this.store = undefined; }, bind : function(store){ store = Ext.StoreMgr.lookup(store); store.on("beforeload", this.beforeLoad, this); store.on("load", this.onLoad, this); store.on("loadexception", this.onLoadError, this); this.store = store; } }); Ext.reg('paging', Ext.PagingToolbar); Ext.Resizable = function(el, config){ this.el = Ext.get(el); if(config && config.wrap){ config.resizeChild = this.el; this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"}); this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap"; this.el.setStyle("overflow", "hidden"); this.el.setPositioning(config.resizeChild.getPositioning()); config.resizeChild.clearPositioning(); if(!config.width || !config.height){ var csize = config.resizeChild.getSize(); this.el.setSize(csize.width, csize.height); } if(config.pinned && !config.adjustments){ config.adjustments = "auto"; } } this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"}); this.proxy.unselectable(); this.proxy.enableDisplayMode('block'); Ext.apply(this, config); if(this.pinned){ this.disableTrackOver = true; this.el.addClass("x-resizable-pinned"); } var position = this.el.getStyle("position"); if(position != "absolute" && position != "fixed"){ this.el.setStyle("position", "relative"); } if(!this.handles){ this.handles = 's,e,se'; if(this.multiDirectional){ this.handles += ',n,w'; } } if(this.handles == "all"){ this.handles = "n s e w ne nw se sw"; } var hs = this.handles.split(/\s*?[,;]\s*?| /); var ps = Ext.Resizable.positions; for(var i = 0, len = hs.length; i < len; i++){ if(hs[i] && ps[hs[i]]){ var pos = ps[hs[i]]; this[pos] = new Ext.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent); } } this.corner = this.southeast; if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1){ this.updateBox = true; } this.activeHandle = null; if(this.resizeChild){ if(typeof this.resizeChild == "boolean"){ this.resizeChild = Ext.get(this.el.dom.firstChild, true); }else{ this.resizeChild = Ext.get(this.resizeChild, true); } } if(this.adjustments == "auto"){ var rc = this.resizeChild; var hw = this.west, he = this.east, hn = this.north, hs = this.south; if(rc && (hw || hn)){ rc.position("relative"); rc.setLeft(hw ? hw.el.getWidth() : 0); rc.setTop(hn ? hn.el.getHeight() : 0); } this.adjustments = [ (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0), (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1 ]; } if(this.draggable){ this.dd = this.dynamic ? this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id}); this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id); } this.addEvents( "beforeresize", "resize" ); if(this.width !== null && this.height !== null){ this.resizeTo(this.width, this.height); }else{ this.updateChildSize(); } if(Ext.isIE){ this.el.dom.style.zoom = 1; } Ext.Resizable.superclass.constructor.call(this); }; Ext.extend(Ext.Resizable, Ext.util.Observable, { resizeChild : false, adjustments : [0, 0], minWidth : 5, minHeight : 5, maxWidth : 10000, maxHeight : 10000, enabled : true, animate : false, duration : .35, dynamic : false, handles : false, multiDirectional : false, disableTrackOver : false, easing : 'easeOutStrong', widthIncrement : 0, heightIncrement : 0, pinned : false, width : null, height : null, preserveRatio : false, transparent: false, minX: 0, minY: 0, draggable: false, resizeTo : function(width, height){ this.el.setSize(width, height); this.updateChildSize(); this.fireEvent("resize", this, width, height, null); }, startSizing : function(e, handle){ this.fireEvent("beforeresize", this, e); if(this.enabled){ if(!this.overlay){ this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: "&#160;"}, Ext.getBody()); this.overlay.unselectable(); this.overlay.enableDisplayMode("block"); this.overlay.on("mousemove", this.onMouseMove, this); this.overlay.on("mouseup", this.onMouseUp, this); } this.overlay.setStyle("cursor", handle.el.getStyle("cursor")); this.resizing = true; this.startBox = this.el.getBox(); this.startPoint = e.getXY(); this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0], (this.startBox.y + this.startBox.height) - this.startPoint[1]]; this.overlay.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true)); this.overlay.show(); if(this.constrainTo) { var ct = Ext.get(this.constrainTo); this.resizeRegion = ct.getRegion().adjust( ct.getFrameWidth('t'), ct.getFrameWidth('l'), -ct.getFrameWidth('b'), -ct.getFrameWidth('r') ); } this.proxy.setStyle('visibility', 'hidden'); this.proxy.show(); this.proxy.setBox(this.startBox); if(!this.dynamic){ this.proxy.setStyle('visibility', 'visible'); } } }, onMouseDown : function(handle, e){ if(this.enabled){ e.stopEvent(); this.activeHandle = handle; this.startSizing(e, handle); } }, onMouseUp : function(e){ var size = this.resizeElement(); this.resizing = false; this.handleOut(); this.overlay.hide(); this.proxy.hide(); this.fireEvent("resize", this, size.width, size.height, e); }, updateChildSize : function(){ if(this.resizeChild){ var el = this.el; var child = this.resizeChild; var adj = this.adjustments; if(el.dom.offsetWidth){ var b = el.getSize(true); child.setSize(b.width+adj[0], b.height+adj[1]); } if(Ext.isIE){ setTimeout(function(){ if(el.dom.offsetWidth){ var b = el.getSize(true); child.setSize(b.width+adj[0], b.height+adj[1]); } }, 10); } } }, snap : function(value, inc, min){ if(!inc || !value) return value; var newValue = value; var m = value % inc; if(m > 0){ if(m > (inc/2)){ newValue = value + (inc-m); }else{ newValue = value - m; } } return Math.max(min, newValue); }, resizeElement : function(){ var box = this.proxy.getBox(); if(this.updateBox){ this.el.setBox(box, false, this.animate, this.duration, null, this.easing); }else{ this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing); } this.updateChildSize(); if(!this.dynamic){ this.proxy.hide(); } return box; }, constrain : function(v, diff, m, mx){ if(v - diff < m){ diff = v - m; }else if(v - diff > mx){ diff = mx - v; } return diff; }, onMouseMove : function(e){ if(this.enabled){ try{ if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) { return; } var curSize = this.curSize || this.startBox; var x = this.startBox.x, y = this.startBox.y; var ox = x, oy = y; var w = curSize.width, h = curSize.height; var ow = w, oh = h; var mw = this.minWidth, mh = this.minHeight; var mxw = this.maxWidth, mxh = this.maxHeight; var wi = this.widthIncrement; var hi = this.heightIncrement; var eventXY = e.getXY(); var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0])); var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1])); var pos = this.activeHandle.position; switch(pos){ case "east": w += diffX; w = Math.min(Math.max(mw, w), mxw); break; case "south": h += diffY; h = Math.min(Math.max(mh, h), mxh); break; case "southeast": w += diffX; h += diffY; w = Math.min(Math.max(mw, w), mxw); h = Math.min(Math.max(mh, h), mxh); break; case "north": diffY = this.constrain(h, diffY, mh, mxh); y += diffY; h -= diffY; break; case "west": diffX = this.constrain(w, diffX, mw, mxw); x += diffX; w -= diffX; break; case "northeast": w += diffX; w = Math.min(Math.max(mw, w), mxw); diffY = this.constrain(h, diffY, mh, mxh); y += diffY; h -= diffY; break; case "northwest": diffX = this.constrain(w, diffX, mw, mxw); diffY = this.constrain(h, diffY, mh, mxh); y += diffY; h -= diffY; x += diffX; w -= diffX; break; case "southwest": diffX = this.constrain(w, diffX, mw, mxw); h += diffY; h = Math.min(Math.max(mh, h), mxh); x += diffX; w -= diffX; break; } var sw = this.snap(w, wi, mw); var sh = this.snap(h, hi, mh); if(sw != w || sh != h){ switch(pos){ case "northeast": y -= sh - h; break; case "north": y -= sh - h; break; case "southwest": x -= sw - w; break; case "west": x -= sw - w; break; case "northwest": x -= sw - w; y -= sh - h; break; } w = sw; h = sh; } if(this.preserveRatio){ switch(pos){ case "southeast": case "east": h = oh * (w/ow); h = Math.min(Math.max(mh, h), mxh); w = ow * (h/oh); break; case "south": w = ow * (h/oh); w = Math.min(Math.max(mw, w), mxw); h = oh * (w/ow); break; case "northeast": w = ow * (h/oh); w = Math.min(Math.max(mw, w), mxw); h = oh * (w/ow); break; case "north": var tw = w; w = ow * (h/oh); w = Math.min(Math.max(mw, w), mxw); h = oh * (w/ow); x += (tw - w) / 2; break; case "southwest": h = oh * (w/ow); h = Math.min(Math.max(mh, h), mxh); var tw = w; w = ow * (h/oh); x += tw - w; break; case "west": var th = h; h = oh * (w/ow); h = Math.min(Math.max(mh, h), mxh); y += (th - h) / 2; var tw = w; w = ow * (h/oh); x += tw - w; break; case "northwest": var tw = w; var th = h; h = oh * (w/ow); h = Math.min(Math.max(mh, h), mxh); w = ow * (h/oh); y += th - h; x += tw - w; break; } } this.proxy.setBounds(x, y, w, h); if(this.dynamic){ this.resizeElement(); } }catch(e){} } }, handleOver : function(){ if(this.enabled){ this.el.addClass("x-resizable-over"); } }, handleOut : function(){ if(!this.resizing){ this.el.removeClass("x-resizable-over"); } }, getEl : function(){ return this.el; }, getResizeChild : function(){ return this.resizeChild; }, destroy : function(removeEl){ this.proxy.remove(); if(this.overlay){ this.overlay.removeAllListeners(); this.overlay.remove(); } var ps = Ext.Resizable.positions; for(var k in ps){ if(typeof ps[k] != "function" && this[ps[k]]){ var h = this[ps[k]]; h.el.removeAllListeners(); h.el.remove(); } } if(removeEl){ this.el.update(""); this.el.remove(); } }, syncHandleHeight : function(){ var h = this.el.getHeight(true); if(this.west){ this.west.el.setHeight(h); } if(this.east){ this.east.el.setHeight(h); } } }); Ext.Resizable.positions = { n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast" }; Ext.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){ if(!this.tpl){ var tpl = Ext.DomHelper.createTemplate( {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"} ); tpl.compile(); Ext.Resizable.Handle.prototype.tpl = tpl; } this.position = pos; this.rz = rz; this.el = this.tpl.append(rz.el.dom, [this.position], true); this.el.unselectable(); if(transparent){ this.el.setOpacity(0); } this.el.on("mousedown", this.onMouseDown, this); if(!disableTrackOver){ this.el.on("mouseover", this.onMouseOver, this); this.el.on("mouseout", this.onMouseOut, this); } }; Ext.Resizable.Handle.prototype = { afterResize : function(rz){ }, onMouseDown : function(e){ this.rz.onMouseDown(this, e); }, onMouseOver : function(e){ this.rz.handleOver(this, e); }, onMouseOut : function(e){ this.rz.handleOut(this, e); } }; Ext.Editor = function(field, config){ this.field = field; Ext.Editor.superclass.constructor.call(this, config); }; Ext.extend(Ext.Editor, Ext.Component, { value : "", alignment: "c-c?", shadow : "frame", constrain : false, swallowKeys : true, completeOnEnter : false, cancelOnEsc : false, updateEl : false, initComponent : function(){ Ext.Editor.superclass.initComponent.call(this); this.addEvents( "beforestartedit", "startedit", "beforecomplete", "complete", "specialkey" ); }, onRender : function(ct, position){ this.el = new Ext.Layer({ shadow: this.shadow, cls: "x-editor", parentEl : ct, shim : this.shim, shadowOffset:4, id: this.id, constrain: this.constrain }); this.el.setStyle("overflow", Ext.isGecko ? "auto" : "hidden"); if(this.field.msgTarget != 'title'){ this.field.msgTarget = 'qtip'; } this.field.inEditor = true; this.field.render(this.el); if(Ext.isGecko){ this.field.el.dom.setAttribute('autocomplete', 'off'); } this.field.on("specialkey", this.onSpecialKey, this); if(this.swallowKeys){ this.field.el.swallowEvent(['keydown','keypress']); } this.field.show(); this.field.on("blur", this.onBlur, this); if(this.field.grow){ this.field.on("autosize", this.el.sync, this.el, {delay:1}); } }, onSpecialKey : function(field, e){ if(this.completeOnEnter && e.getKey() == e.ENTER){ e.stopEvent(); this.completeEdit(); }else if(this.cancelOnEsc && e.getKey() == e.ESC){ this.cancelEdit(); }else{ this.fireEvent('specialkey', field, e); } }, startEdit : function(el, value){ if(this.editing){ this.completeEdit(); } this.boundEl = Ext.get(el); var v = value !== undefined ? value : this.boundEl.dom.innerHTML; if(!this.rendered){ this.render(this.parentEl || document.body); } if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){ return; } this.startValue = v; this.field.setValue(v); this.doAutoSize(); this.el.alignTo(this.boundEl, this.alignment); this.editing = true; this.show(); }, doAutoSize : function(){ if(this.autoSize){ var sz = this.boundEl.getSize(); switch(this.autoSize){ case "width": this.setSize(sz.width, ""); break; case "height": this.setSize("", sz.height); break; default: this.setSize(sz.width, sz.height); } } }, setSize : function(w, h){ delete this.field.lastSize; this.field.setSize(w, h); if(this.el){ this.el.sync(); } }, realign : function(){ this.el.alignTo(this.boundEl, this.alignment); }, completeEdit : function(remainVisible){ if(!this.editing){ return; } var v = this.getValue(); if(this.revertInvalid !== false && !this.field.isValid()){ v = this.startValue; this.cancelEdit(true); } if(String(v) === String(this.startValue) && this.ignoreNoChange){ this.editing = false; this.hide(); return; } if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){ this.editing = false; if(this.updateEl && this.boundEl){ this.boundEl.update(v); } if(remainVisible !== true){ this.hide(); } this.fireEvent("complete", this, v, this.startValue); } }, onShow : function(){ this.el.show(); if(this.hideEl !== false){ this.boundEl.hide(); } this.field.show(); if(Ext.isIE && !this.fixIEFocus){ this.fixIEFocus = true; this.deferredFocus.defer(50, this); }else{ this.field.focus(); } this.fireEvent("startedit", this.boundEl, this.startValue); }, deferredFocus : function(){ if(this.editing){ this.field.focus(); } }, cancelEdit : function(remainVisible){ if(this.editing){ this.setValue(this.startValue); if(remainVisible !== true){ this.hide(); } } }, onBlur : function(){ if(this.allowBlur !== true && this.editing){ this.completeEdit(); } }, onHide : function(){ if(this.editing){ this.completeEdit(); return; } this.field.blur(); if(this.field.collapse){ this.field.collapse(); } this.el.hide(); if(this.hideEl !== false){ this.boundEl.show(); } }, setValue : function(v){ this.field.setValue(v); }, getValue : function(){ return this.field.getValue(); }, beforeDestroy : function(){ this.field.destroy(); this.field = null; } }); Ext.reg('editor', Ext.Editor); Ext.MessageBox = function(){ var dlg, opt, mask, waitTimer; var bodyEl, msgEl, textboxEl, textareaEl, progressBar, pp, iconEl, spacerEl; var buttons, activeTextEl, bwidth, iconCls = ''; var handleButton = function(button){ dlg.hide(); Ext.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1); }; var handleHide = function(){ if(opt && opt.cls){ dlg.el.removeClass(opt.cls); } progressBar.reset(); }; var handleEsc = function(d, k, e){ if(opt && opt.closable !== false){ dlg.hide(); } if(e){ e.stopEvent(); } }; var updateButtons = function(b){ var width = 0; if(!b){ buttons["ok"].hide(); buttons["cancel"].hide(); buttons["yes"].hide(); buttons["no"].hide(); return width; } dlg.footer.dom.style.display = ''; for(var k in buttons){ if(typeof buttons[k] != "function"){ if(b[k]){ buttons[k].show(); buttons[k].setText(typeof b[k] == "string" ? b[k] : Ext.MessageBox.buttonText[k]); width += buttons[k].el.getWidth()+15; }else{ buttons[k].hide(); } } } return width; }; return { getDialog : function(titleText){ if(!dlg){ dlg = new Ext.Window({ autoCreate : true, title:titleText, resizable:false, constrain:true, constrainHeader:true, minimizable : false, maximizable : false, stateful: false, modal: true, shim:true, buttonAlign:"center", width:400, height:100, minHeight: 80, plain:true, footer:true, closable:true, close : function(){ if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){ handleButton("no"); }else{ handleButton("cancel"); } } }); buttons = {}; var bt = this.buttonText; buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok")); buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes")); buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no")); buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel")); buttons["ok"].hideMode = buttons["yes"].hideMode = buttons["no"].hideMode = buttons["cancel"].hideMode = 'offsets'; dlg.render(document.body); dlg.getEl().addClass('x-window-dlg'); mask = dlg.mask; bodyEl = dlg.body.createChild({ html:'<div class="ext-mb-icon"></div><div class="ext-mb-content"><span class="ext-mb-text"></span><br /><input type="text" class="ext-mb-input" /><textarea class="ext-mb-textarea"></textarea></div>' }); iconEl = Ext.get(bodyEl.dom.firstChild); var contentEl = bodyEl.dom.childNodes[1]; msgEl = Ext.get(contentEl.firstChild); textboxEl = Ext.get(contentEl.childNodes[2]); textboxEl.enableDisplayMode(); textboxEl.addKeyListener([10,13], function(){ if(dlg.isVisible() && opt && opt.buttons){ if(opt.buttons.ok){ handleButton("ok"); }else if(opt.buttons.yes){ handleButton("yes"); } } }); textareaEl = Ext.get(contentEl.childNodes[3]); textareaEl.enableDisplayMode(); progressBar = new Ext.ProgressBar({ renderTo:bodyEl }); bodyEl.createChild({cls:'x-clear'}); } return dlg; }, updateText : function(text){ if(!dlg.isVisible() && !opt.width){ dlg.setSize(this.maxWidth, 100); } msgEl.update(text || '&#160;'); var iw = iconCls != '' ? (iconEl.getWidth() + iconEl.getMargins('lr')) : 0; var mw = msgEl.getWidth() + msgEl.getMargins('lr'); var fw = dlg.getFrameWidth('lr'); var bw = dlg.body.getFrameWidth('lr'); if (Ext.isIE && iw > 0){ iw += 3; } var w = Math.max(Math.min(opt.width || iw+mw+fw+bw, this.maxWidth), Math.max(opt.minWidth || this.minWidth, bwidth || 0)); if(opt.prompt === true){ activeTextEl.setWidth(w-iw-fw-bw); } if(opt.progress === true || opt.wait === true){ progressBar.setSize(w-iw-fw-bw); } dlg.setSize(w, 'auto').center(); return this; }, updateProgress : function(value, progressText, msg){ progressBar.updateProgress(value, progressText); if(msg){ this.updateText(msg); } return this; }, isVisible : function(){ return dlg && dlg.isVisible(); }, hide : function(){ if(this.isVisible()){ dlg.hide(); handleHide(); } return this; }, show : function(options){ if(this.isVisible()){ this.hide(); } opt = options; var d = this.getDialog(opt.title || "&#160;"); d.setTitle(opt.title || "&#160;"); var allowClose = (opt.closable !== false && opt.progress !== true && opt.wait !== true); d.tools.close.setDisplayed(allowClose); activeTextEl = textboxEl; opt.prompt = opt.prompt || (opt.multiline ? true : false); if(opt.prompt){ if(opt.multiline){ textboxEl.hide(); textareaEl.show(); textareaEl.setHeight(typeof opt.multiline == "number" ? opt.multiline : this.defaultTextHeight); activeTextEl = textareaEl; }else{ textboxEl.show(); textareaEl.hide(); } }else{ textboxEl.hide(); textareaEl.hide(); } activeTextEl.dom.value = opt.value || ""; if(opt.prompt){ d.focusEl = activeTextEl; }else{ var bs = opt.buttons; var db = null; if(bs && bs.ok){ db = buttons["ok"]; }else if(bs && bs.yes){ db = buttons["yes"]; } if (db){ d.focusEl = db; } } this.setIcon(opt.icon); bwidth = updateButtons(opt.buttons); progressBar.setVisible(opt.progress === true || opt.wait === true); this.updateProgress(0, opt.progressText); this.updateText(opt.msg); if(opt.cls){ d.el.addClass(opt.cls); } d.proxyDrag = opt.proxyDrag === true; d.modal = opt.modal !== false; d.mask = opt.modal !== false ? mask : false; if(!d.isVisible()){ document.body.appendChild(dlg.el.dom); d.setAnimateTarget(opt.animEl); d.show(opt.animEl); } d.on('show', function(){ if(allowClose === true){ d.keyMap.enable(); }else{ d.keyMap.disable(); } }, this, {single:true}); if(opt.wait === true){ progressBar.wait(opt.waitConfig); } return this; }, setIcon : function(icon){ if(icon && icon != ''){ iconEl.removeClass('x-hidden'); iconEl.replaceClass(iconCls, icon); iconCls = icon; }else{ iconEl.replaceClass(iconCls, 'x-hidden'); iconCls = ''; } return this; }, progress : function(title, msg, progressText){ this.show({ title : title, msg : msg, buttons: false, progress:true, closable:false, minWidth: this.minProgressWidth, progressText: progressText }); return this; }, wait : function(msg, title, config){ this.show({ title : title, msg : msg, buttons: false, closable:false, wait:true, modal:true, minWidth: this.minProgressWidth, waitConfig: config }); return this; }, alert : function(title, msg, fn, scope){ this.show({ title : title, msg : msg, buttons: this.OK, fn: fn, scope : scope }); return this; }, confirm : function(title, msg, fn, scope){ this.show({ title : title, msg : msg, buttons: this.YESNO, fn: fn, scope : scope, icon: this.QUESTION }); return this; }, prompt : function(title, msg, fn, scope, multiline){ this.show({ title : title, msg : msg, buttons: this.OKCANCEL, fn: fn, minWidth:250, scope : scope, prompt:true, multiline: multiline }); return this; }, OK : {ok:true}, CANCEL : {cancel:true}, OKCANCEL : {ok:true, cancel:true}, YESNO : {yes:true, no:true}, YESNOCANCEL : {yes:true, no:true, cancel:true}, INFO : 'ext-mb-info', WARNING : 'ext-mb-warning', QUESTION : 'ext-mb-question', ERROR : 'ext-mb-error', defaultTextHeight : 75, maxWidth : 600, minWidth : 100, minProgressWidth : 250, buttonText : { ok : "OK", cancel : "Cancel", yes : "Yes", no : "No" } }; }(); Ext.Msg = Ext.MessageBox; Ext.Tip = Ext.extend(Ext.Panel, { minWidth : 40, maxWidth : 300, shadow : "sides", defaultAlign : "tl-bl?", autoRender: true, quickShowInterval : 250, frame:true, hidden:true, baseCls: 'x-tip', floating:{shadow:true,shim:true,useDisplay:true,constrain:false}, autoHeight:true, initComponent : function(){ Ext.Tip.superclass.initComponent.call(this); if(this.closable && !this.title){ this.elements += ',header'; } }, afterRender : function(){ Ext.Tip.superclass.afterRender.call(this); if(this.closable){ this.addTool({ id: 'close', handler: this.hide, scope: this }); } }, showAt : function(xy){ Ext.Tip.superclass.show.call(this); if(this.measureWidth !== false && (!this.initialConfig || typeof this.initialConfig.width != 'number')){ var bw = this.body.getTextWidth(); if(this.title){ bw = Math.max(bw, this.header.child('span').getTextWidth(this.title)); } bw += this.getFrameWidth() + (this.closable ? 20 : 0) + this.body.getPadding("lr"); this.setWidth(bw.constrain(this.minWidth, this.maxWidth)); } if(this.constrainPosition){ xy = this.el.adjustForConstraints(xy); } this.setPagePosition(xy[0], xy[1]); }, showBy : function(el, pos){ if(!this.rendered){ this.render(Ext.getBody()); } this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign)); }, initDraggable : function(){ this.dd = new Ext.Tip.DD(this, typeof this.draggable == 'boolean' ? null : this.draggable); this.header.addClass('x-tip-draggable'); } }); Ext.Tip.DD = function(tip, config){ Ext.apply(this, config); this.tip = tip; Ext.Tip.DD.superclass.constructor.call(this, tip.el.id, 'WindowDD-'+tip.id); this.setHandleElId(tip.header.id); this.scroll = false; }; Ext.extend(Ext.Tip.DD, Ext.dd.DD, { moveOnly:true, scroll:false, headerOffsets:[100, 25], startDrag : function(){ this.tip.el.disableShadow(); }, endDrag : function(e){ this.tip.el.enableShadow(true); } }); Ext.ToolTip = Ext.extend(Ext.Tip, { showDelay: 500, hideDelay: 200, dismissDelay: 5000, mouseOffset: [15,18], trackMouse : false, constrainPosition: true, initComponent: function(){ Ext.ToolTip.superclass.initComponent.call(this); this.lastActive = new Date(); this.initTarget(); }, initTarget : function(){ if(this.target){ this.target = Ext.get(this.target); this.target.on('mouseover', this.onTargetOver, this); this.target.on('mouseout', this.onTargetOut, this); this.target.on('mousemove', this.onMouseMove, this); } }, onMouseMove : function(e){ this.targetXY = e.getXY(); if(!this.hidden && this.trackMouse){ this.setPagePosition(this.getTargetXY()); } }, getTargetXY : function(){ return [this.targetXY[0]+this.mouseOffset[0], this.targetXY[1]+this.mouseOffset[1]]; }, onTargetOver : function(e){ if(this.disabled || e.within(this.target.dom, true)){ return; } this.clearTimer('hide'); this.targetXY = e.getXY(); this.delayShow(); }, delayShow : function(){ if(this.hidden && !this.showTimer){ if(this.lastActive.getElapsed() < this.quickShowInterval){ this.show(); }else{ this.showTimer = this.show.defer(this.showDelay, this); } }else if(!this.hidden && this.autoHide !== false){ this.show(); } }, onTargetOut : function(e){ if(this.disabled || e.within(this.target.dom, true)){ return; } this.clearTimer('show'); if(this.autoHide !== false){ this.delayHide(); } }, delayHide : function(){ if(!this.hidden && !this.hideTimer){ this.hideTimer = this.hide.defer(this.hideDelay, this); } }, hide: function(){ this.clearTimer('dismiss'); this.lastActive = new Date(); Ext.ToolTip.superclass.hide.call(this); }, show : function(){ this.showAt(this.getTargetXY()); }, showAt : function(xy){ this.lastActive = new Date(); this.clearTimers(); Ext.ToolTip.superclass.showAt.call(this, xy); if(this.dismissDelay && this.autoHide !== false){ this.dismissTimer = this.hide.defer(this.dismissDelay, this); } }, clearTimer : function(name){ name = name + 'Timer'; clearTimeout(this[name]); delete this[name]; }, clearTimers : function(){ this.clearTimer('show'); this.clearTimer('dismiss'); this.clearTimer('hide'); }, onShow : function(){ Ext.ToolTip.superclass.onShow.call(this); Ext.getDoc().on('mousedown', this.onDocMouseDown, this); }, onHide : function(){ Ext.ToolTip.superclass.onHide.call(this); Ext.getDoc().un('mousedown', this.onDocMouseDown, this); }, onDocMouseDown : function(e){ if(this.autoHide !== false && !e.within(this.el.dom)){ this.disable(); this.enable.defer(100, this); } }, onDisable : function(){ this.clearTimers(); this.hide(); }, adjustPosition : function(x, y){ var ay = this.targetXY[1], h = this.getSize().height; if(this.constrainPosition && y <= ay && (y+h) >= ay){ y = ay-h-5; } return {x : x, y: y}; }, onDestroy : function(){ Ext.ToolTip.superclass.onDestroy.call(this); if(this.target){ this.target.un('mouseover', this.onTargetOver, this); this.target.un('mouseout', this.onTargetOut, this); this.target.un('mousemove', this.onMouseMove, this); } } }); Ext.QuickTip = Ext.extend(Ext.ToolTip, { interceptTitles : false, tagConfig : { namespace : "ext", attribute : "qtip", width : "qwidth", target : "target", title : "qtitle", hide : "hide", cls : "qclass", align : "qalign" }, initComponent : function(){ this.target = this.target || Ext.getDoc(); this.targets = this.targets || {}; Ext.QuickTip.superclass.initComponent.call(this); }, register : function(config){ var cs = Ext.isArray(config) ? config : arguments; for(var i = 0, len = cs.length; i < len; i++){ var c = cs[i]; var target = c.target; if(target){ if(Ext.isArray(target)){ for(var j = 0, jlen = target.length; j < jlen; j++){ this.targets[Ext.id(target[j])] = c; } } else{ this.targets[Ext.id(target)] = c; } } } }, unregister : function(el){ delete this.targets[Ext.id(el)]; }, onTargetOver : function(e){ if(this.disabled){ return; } this.targetXY = e.getXY(); var t = e.getTarget(); if(!t || t.nodeType !== 1 || t == document || t == document.body){ return; } if(this.activeTarget && t == this.activeTarget.el){ this.clearTimer('hide'); this.show(); return; } if(t && this.targets[t.id]){ this.activeTarget = this.targets[t.id]; this.activeTarget.el = t; this.delayShow(); return; } var ttp, et = Ext.fly(t), cfg = this.tagConfig; var ns = cfg.namespace; if(this.interceptTitles && t.title){ ttp = t.title; t.qtip = ttp; t.removeAttribute("title"); e.preventDefault(); } else{ ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute); } if(ttp){ var autoHide = et.getAttributeNS(ns, cfg.hide); this.activeTarget = { el: t, text: ttp, width: et.getAttributeNS(ns, cfg.width), autoHide: autoHide != "user" && autoHide !== 'false', title: et.getAttributeNS(ns, cfg.title), cls: et.getAttributeNS(ns, cfg.cls), align: et.getAttributeNS(ns, cfg.align) }; this.delayShow(); } }, onTargetOut : function(e){ this.clearTimer('show'); if(this.autoHide !== false){ this.delayHide(); } }, showAt : function(xy){ var t = this.activeTarget; if(t){ if(!this.rendered){ this.render(Ext.getBody()); this.activeTarget = t; } if(t.width){ this.setWidth(t.width); this.body.setWidth(this.adjustBodyWidth(t.width - this.getFrameWidth())); this.measureWidth = false; } else{ this.measureWidth = true; } this.setTitle(t.title || ''); this.body.update(t.text); this.autoHide = t.autoHide; this.dismissDelay = t.dismissDelay || this.dismissDelay; if(this.lastCls){ this.el.removeClass(this.lastCls); delete this.lastCls; } if(t.cls){ this.el.addClass(t.cls); this.lastCls = t.cls; } if(t.align){ xy = this.el.getAlignToXY(t.el, t.align); this.constrainPosition = false; } else{ this.constrainPosition = true; } } Ext.QuickTip.superclass.showAt.call(this, xy); }, hide: function(){ delete this.activeTarget; Ext.QuickTip.superclass.hide.call(this); } }); Ext.QuickTips = function(){ var tip, locks = []; return { init : function(){ if(!tip){ tip = new Ext.QuickTip({elements:'header,body'}); } }, enable : function(){ if(tip){ locks.pop(); if(locks.length < 1){ tip.enable(); } } }, disable : function(){ if(tip){ tip.disable(); } locks.push(1); }, isEnabled : function(){ return tip && !tip.disabled; }, getQuickTip : function(){ return tip; }, register : function(){ tip.register.apply(tip, arguments); }, unregister : function(){ tip.unregister.apply(tip, arguments); }, tips :function(){ tip.register.apply(tip, arguments); } } }(); Ext.tree.TreePanel = Ext.extend(Ext.Panel, { rootVisible : true, animate: Ext.enableFx, lines : true, enableDD : false, hlDrop : Ext.enableFx, pathSeparator: "/", initComponent : function(){ Ext.tree.TreePanel.superclass.initComponent.call(this); if(!this.eventModel){ this.eventModel = new Ext.tree.TreeEventModel(this); } this.nodeHash = {}; if(this.root){ this.setRootNode(this.root); } this.addEvents( "append", "remove", "movenode", "insert", "beforeappend", "beforeremove", "beforemovenode", "beforeinsert", "beforeload", "load", "textchange", "beforeexpandnode", "beforecollapsenode", "expandnode", "disabledchange", "collapsenode", "beforeclick", "click", "checkchange", "dblclick", "contextmenu", "beforechildrenrendered", "startdrag", "enddrag", "dragdrop", "beforenodedrop", "nodedrop", "nodedragover" ); if(this.singleExpand){ this.on("beforeexpandnode", this.restrictExpand, this); } }, proxyNodeEvent : function(ename, a1, a2, a3, a4, a5, a6){ if(ename == 'collapse' || ename == 'expand' || ename == 'beforecollapse' || ename == 'beforeexpand' || ename == 'move' || ename == 'beforemove'){ ename = ename+'node'; } return this.fireEvent(ename, a1, a2, a3, a4, a5, a6); }, getRootNode : function(){ return this.root; }, setRootNode : function(node){ this.root = node; node.ownerTree = this; node.isRoot = true; this.registerNode(node); if(!this.rootVisible){ var uiP = node.attributes.uiProvider; node.ui = uiP ? new uiP(node) : new Ext.tree.RootTreeNodeUI(node); } return node; }, getNodeById : function(id){ return this.nodeHash[id]; }, registerNode : function(node){ this.nodeHash[node.id] = node; }, unregisterNode : function(node){ delete this.nodeHash[node.id]; }, toString : function(){ return "[Tree"+(this.id?" "+this.id:"")+"]"; }, restrictExpand : function(node){ var p = node.parentNode; if(p){ if(p.expandedChild && p.expandedChild.parentNode == p){ p.expandedChild.collapse(); } p.expandedChild = node; } }, getChecked : function(a, startNode){ startNode = startNode || this.root; var r = []; var f = function(){ if(this.attributes.checked){ r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a])); } } startNode.cascade(f); return r; }, getEl : function(){ return this.el; }, getLoader : function(){ return this.loader; }, expandAll : function(){ this.root.expand(true); }, collapseAll : function(){ this.root.collapse(true); }, getSelectionModel : function(){ if(!this.selModel){ this.selModel = new Ext.tree.DefaultSelectionModel(); } return this.selModel; }, expandPath : function(path, attr, callback){ attr = attr || "id"; var keys = path.split(this.pathSeparator); var curNode = this.root; if(curNode.attributes[attr] != keys[1]){ if(callback){ callback(false, null); } return; } var index = 1; var f = function(){ if(++index == keys.length){ if(callback){ callback(true, curNode); } return; } var c = curNode.findChild(attr, keys[index]); if(!c){ if(callback){ callback(false, curNode); } return; } curNode = c; c.expand(false, false, f); }; curNode.expand(false, false, f); }, selectPath : function(path, attr, callback){ attr = attr || "id"; var keys = path.split(this.pathSeparator); var v = keys.pop(); if(keys.length > 0){ var f = function(success, node){ if(success && node){ var n = node.findChild(attr, v); if(n){ n.select(); if(callback){ callback(true, n); } }else if(callback){ callback(false, n); } }else{ if(callback){ callback(false, n); } } }; this.expandPath(keys.join(this.pathSeparator), attr, f); }else{ this.root.select(); if(callback){ callback(true, this.root); } } }, getTreeEl : function(){ return this.body; }, onRender : function(ct, position){ Ext.tree.TreePanel.superclass.onRender.call(this, ct, position); this.el.addClass('x-tree'); this.innerCt = this.body.createChild({tag:"ul", cls:"x-tree-root-ct " + (this.useArrows ? 'x-tree-arrows' : this.lines ? "x-tree-lines" : "x-tree-no-lines")}); }, initEvents : function(){ Ext.tree.TreePanel.superclass.initEvents.call(this); if(this.containerScroll){ Ext.dd.ScrollManager.register(this.body); } if((this.enableDD || this.enableDrop) && !this.dropZone){ this.dropZone = new Ext.tree.TreeDropZone(this, this.dropConfig || { ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true }); } if((this.enableDD || this.enableDrag) && !this.dragZone){ this.dragZone = new Ext.tree.TreeDragZone(this, this.dragConfig || { ddGroup: this.ddGroup || "TreeDD", scroll: this.ddScroll }); } this.getSelectionModel().init(this); }, afterRender : function(){ Ext.tree.TreePanel.superclass.afterRender.call(this); this.root.render(); if(!this.rootVisible){ this.root.renderChildren(); } }, onDestroy : function(){ if(this.rendered){ this.body.removeAllListeners(); Ext.dd.ScrollManager.unregister(this.body); if(this.dropZone){ this.dropZone.unreg(); } if(this.dragZone){ this.dragZone.unreg(); } } this.root.destroy(); this.nodeHash = null; Ext.tree.TreePanel.superclass.onDestroy.call(this); } }); Ext.reg('treepanel', Ext.tree.TreePanel); Ext.tree.TreeEventModel = function(tree){ this.tree = tree; this.tree.on('render', this.initEvents, this); } Ext.tree.TreeEventModel.prototype = { initEvents : function(){ var el = this.tree.getTreeEl(); el.on('click', this.delegateClick, this); if(this.tree.trackMouseOver !== false){ el.on('mouseover', this.delegateOver, this); el.on('mouseout', this.delegateOut, this); } el.on('dblclick', this.delegateDblClick, this); el.on('contextmenu', this.delegateContextMenu, this); }, getNode : function(e){ var t; if(t = e.getTarget('.x-tree-node-el', 10)){ var id = Ext.fly(t, '_treeEvents').getAttributeNS('ext', 'tree-node-id'); if(id){ return this.tree.getNodeById(id); } } return null; }, getNodeTarget : function(e){ var t = e.getTarget('.x-tree-node-icon', 1); if(!t){ t = e.getTarget('.x-tree-node-el', 6); } return t; }, delegateOut : function(e, t){ if(!this.beforeEvent(e)){ return; } if(e.getTarget('.x-tree-ec-icon', 1)){ var n = this.getNode(e); this.onIconOut(e, n); if(n == this.lastEcOver){ delete this.lastEcOver; } } if((t = this.getNodeTarget(e)) && !e.within(t, true)){ this.onNodeOut(e, this.getNode(e)); } }, delegateOver : function(e, t){ if(!this.beforeEvent(e)){ return; } if(this.lastEcOver){ this.onIconOut(e, this.lastEcOver); delete this.lastEcOver; } if(e.getTarget('.x-tree-ec-icon', 1)){ this.lastEcOver = this.getNode(e); this.onIconOver(e, this.lastEcOver); } if(t = this.getNodeTarget(e)){ this.onNodeOver(e, this.getNode(e)); } }, delegateClick : function(e, t){ if(!this.beforeEvent(e)){ return; } if(e.getTarget('input[type=checkbox]', 1)){ this.onCheckboxClick(e, this.getNode(e)); } else if(e.getTarget('.x-tree-ec-icon', 1)){ this.onIconClick(e, this.getNode(e)); } else if(this.getNodeTarget(e)){ this.onNodeClick(e, this.getNode(e)); } }, delegateDblClick : function(e, t){ if(this.beforeEvent(e) && this.getNodeTarget(e)){ this.onNodeDblClick(e, this.getNode(e)); } }, delegateContextMenu : function(e, t){ if(this.beforeEvent(e) && this.getNodeTarget(e)){ this.onNodeContextMenu(e, this.getNode(e)); } }, onNodeClick : function(e, node){ node.ui.onClick(e); }, onNodeOver : function(e, node){ node.ui.onOver(e); }, onNodeOut : function(e, node){ node.ui.onOut(e); }, onIconOver : function(e, node){ node.ui.addClass('x-tree-ec-over'); }, onIconOut : function(e, node){ node.ui.removeClass('x-tree-ec-over'); }, onIconClick : function(e, node){ node.ui.ecClick(e); }, onCheckboxClick : function(e, node){ node.ui.onCheckChange(e); }, onNodeDblClick : function(e, node){ node.ui.onDblClick(e); }, onNodeContextMenu : function(e, node){ node.ui.onContextMenu(e); }, beforeEvent : function(e){ if(this.disabled){ e.stopEvent(); return false; } return true; }, disable: function(){ this.disabled = true; }, enable: function(){ this.disabled = false; } }; Ext.tree.DefaultSelectionModel = function(config){ this.selNode = null; this.addEvents( "selectionchange", "beforeselect" ); Ext.apply(this, config); Ext.tree.DefaultSelectionModel.superclass.constructor.call(this); }; Ext.extend(Ext.tree.DefaultSelectionModel, Ext.util.Observable, { init : function(tree){ this.tree = tree; tree.getTreeEl().on("keydown", this.onKeyDown, this); tree.on("click", this.onNodeClick, this); }, onNodeClick : function(node, e){ this.select(node); }, select : function(node){ var last = this.selNode; if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){ if(last){ last.ui.onSelectedChange(false); } this.selNode = node; node.ui.onSelectedChange(true); this.fireEvent("selectionchange", this, node, last); } return node; }, unselect : function(node){ if(this.selNode == node){ this.clearSelections(); } }, clearSelections : function(){ var n = this.selNode; if(n){ n.ui.onSelectedChange(false); this.selNode = null; this.fireEvent("selectionchange", this, null); } return n; }, getSelectedNode : function(){ return this.selNode; }, isSelected : function(node){ return this.selNode == node; }, selectPrevious : function(){ var s = this.selNode || this.lastSelNode; if(!s){ return null; } var ps = s.previousSibling; if(ps){ if(!ps.isExpanded() || ps.childNodes.length < 1){ return this.select(ps); } else{ var lc = ps.lastChild; while(lc && lc.isExpanded() && lc.childNodes.length > 0){ lc = lc.lastChild; } return this.select(lc); } } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){ return this.select(s.parentNode); } return null; }, selectNext : function(){ var s = this.selNode || this.lastSelNode; if(!s){ return null; } if(s.firstChild && s.isExpanded()){ return this.select(s.firstChild); }else if(s.nextSibling){ return this.select(s.nextSibling); }else if(s.parentNode){ var newS = null; s.parentNode.bubble(function(){ if(this.nextSibling){ newS = this.getOwnerTree().selModel.select(this.nextSibling); return false; } }); return newS; } return null; }, onKeyDown : function(e){ var s = this.selNode || this.lastSelNode; var sm = this; if(!s){ return; } var k = e.getKey(); switch(k){ case e.DOWN: e.stopEvent(); this.selectNext(); break; case e.UP: e.stopEvent(); this.selectPrevious(); break; case e.RIGHT: e.preventDefault(); if(s.hasChildNodes()){ if(!s.isExpanded()){ s.expand(); }else if(s.firstChild){ this.select(s.firstChild, e); } } break; case e.LEFT: e.preventDefault(); if(s.hasChildNodes() && s.isExpanded()){ s.collapse(); }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){ this.select(s.parentNode, e); } break; }; } }); Ext.tree.MultiSelectionModel = function(config){ this.selNodes = []; this.selMap = {}; this.addEvents( "selectionchange" ); Ext.apply(this, config); Ext.tree.MultiSelectionModel.superclass.constructor.call(this); }; Ext.extend(Ext.tree.MultiSelectionModel, Ext.util.Observable, { init : function(tree){ this.tree = tree; tree.getTreeEl().on("keydown", this.onKeyDown, this); tree.on("click", this.onNodeClick, this); }, onNodeClick : function(node, e){ this.select(node, e, e.ctrlKey); }, select : function(node, e, keepExisting){ if(keepExisting !== true){ this.clearSelections(true); } if(this.isSelected(node)){ this.lastSelNode = node; return node; } this.selNodes.push(node); this.selMap[node.id] = node; this.lastSelNode = node; node.ui.onSelectedChange(true); this.fireEvent("selectionchange", this, this.selNodes); return node; }, unselect : function(node){ if(this.selMap[node.id]){ node.ui.onSelectedChange(false); var sn = this.selNodes; var index = sn.indexOf(node); if(index != -1){ this.selNodes.splice(index, 1); } delete this.selMap[node.id]; this.fireEvent("selectionchange", this, this.selNodes); } }, clearSelections : function(suppressEvent){ var sn = this.selNodes; if(sn.length > 0){ for(var i = 0, len = sn.length; i < len; i++){ sn[i].ui.onSelectedChange(false); } this.selNodes = []; this.selMap = {}; if(suppressEvent !== true){ this.fireEvent("selectionchange", this, this.selNodes); } } }, isSelected : function(node){ return this.selMap[node.id] ? true : false; }, getSelectedNodes : function(){ return this.selNodes; }, onKeyDown : Ext.tree.DefaultSelectionModel.prototype.onKeyDown, selectNext : Ext.tree.DefaultSelectionModel.prototype.selectNext, selectPrevious : Ext.tree.DefaultSelectionModel.prototype.selectPrevious }); Ext.tree.TreeNode = function(attributes){ attributes = attributes || {}; if(typeof attributes == "string"){ attributes = {text: attributes}; } this.childrenRendered = false; this.rendered = false; Ext.tree.TreeNode.superclass.constructor.call(this, attributes); this.expanded = attributes.expanded === true; this.isTarget = attributes.isTarget !== false; this.draggable = attributes.draggable !== false && attributes.allowDrag !== false; this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false; this.text = attributes.text; this.disabled = attributes.disabled === true; this.addEvents( "textchange", "beforeexpand", "beforecollapse", "expand", "disabledchange", "collapse", "beforeclick", "click", "checkchange", "dblclick", "contextmenu", "beforechildrenrendered" ); var uiClass = this.attributes.uiProvider || this.defaultUI || Ext.tree.TreeNodeUI; this.ui = new uiClass(this); }; Ext.extend(Ext.tree.TreeNode, Ext.data.Node, { preventHScroll: true, isExpanded : function(){ return this.expanded; }, getUI : function(){ return this.ui; }, setFirstChild : function(node){ var of = this.firstChild; Ext.tree.TreeNode.superclass.setFirstChild.call(this, node); if(this.childrenRendered && of && node != of){ of.renderIndent(true, true); } if(this.rendered){ this.renderIndent(true, true); } }, setLastChild : function(node){ var ol = this.lastChild; Ext.tree.TreeNode.superclass.setLastChild.call(this, node); if(this.childrenRendered && ol && node != ol){ ol.renderIndent(true, true); } if(this.rendered){ this.renderIndent(true, true); } }, appendChild : function(){ var node = Ext.tree.TreeNode.superclass.appendChild.apply(this, arguments); if(node && this.childrenRendered){ node.render(); } this.ui.updateExpandIcon(); return node; }, removeChild : function(node){ this.ownerTree.getSelectionModel().unselect(node); Ext.tree.TreeNode.superclass.removeChild.apply(this, arguments); if(this.childrenRendered){ node.ui.remove(); } if(this.childNodes.length < 1){ this.collapse(false, false); }else{ this.ui.updateExpandIcon(); } if(!this.firstChild && !this.isHiddenRoot()) { this.childrenRendered = false; } return node; }, insertBefore : function(node, refNode){ var newNode = Ext.tree.TreeNode.superclass.insertBefore.apply(this, arguments); if(newNode && refNode && this.childrenRendered){ node.render(); } this.ui.updateExpandIcon(); return newNode; }, setText : function(text){ var oldText = this.text; this.text = text; this.attributes.text = text; if(this.rendered){ this.ui.onTextChange(this, text, oldText); } this.fireEvent("textchange", this, text, oldText); }, select : function(){ this.getOwnerTree().getSelectionModel().select(this); }, unselect : function(){ this.getOwnerTree().getSelectionModel().unselect(this); }, isSelected : function(){ return this.getOwnerTree().getSelectionModel().isSelected(this); }, expand : function(deep, anim, callback){ if(!this.expanded){ if(this.fireEvent("beforeexpand", this, deep, anim) === false){ return; } if(!this.childrenRendered){ this.renderChildren(); } this.expanded = true; if(!this.isHiddenRoot() && (this.getOwnerTree().animate && anim !== false) || anim){ this.ui.animExpand(function(){ this.fireEvent("expand", this); if(typeof callback == "function"){ callback(this); } if(deep === true){ this.expandChildNodes(true); } }.createDelegate(this)); return; }else{ this.ui.expand(); this.fireEvent("expand", this); if(typeof callback == "function"){ callback(this); } } }else{ if(typeof callback == "function"){ callback(this); } } if(deep === true){ this.expandChildNodes(true); } }, isHiddenRoot : function(){ return this.isRoot && !this.getOwnerTree().rootVisible; }, collapse : function(deep, anim){ if(this.expanded && !this.isHiddenRoot()){ if(this.fireEvent("beforecollapse", this, deep, anim) === false){ return; } this.expanded = false; if((this.getOwnerTree().animate && anim !== false) || anim){ this.ui.animCollapse(function(){ this.fireEvent("collapse", this); if(deep === true){ this.collapseChildNodes(true); } }.createDelegate(this)); return; }else{ this.ui.collapse(); this.fireEvent("collapse", this); } } if(deep === true){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { cs[i].collapse(true, false); } } }, delayedExpand : function(delay){ if(!this.expandProcId){ this.expandProcId = this.expand.defer(delay, this); } }, cancelExpand : function(){ if(this.expandProcId){ clearTimeout(this.expandProcId); } this.expandProcId = false; }, toggle : function(){ if(this.expanded){ this.collapse(); }else{ this.expand(); } }, ensureVisible : function(callback){ var tree = this.getOwnerTree(); tree.expandPath(this.parentNode.getPath(), false, function(){ var node = tree.getNodeById(this.id); tree.getTreeEl().scrollChildIntoView(node.ui.anchor); Ext.callback(callback); }.createDelegate(this)); }, expandChildNodes : function(deep){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { cs[i].expand(deep); } }, collapseChildNodes : function(deep){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { cs[i].collapse(deep); } }, disable : function(){ this.disabled = true; this.unselect(); if(this.rendered && this.ui.onDisableChange){ this.ui.onDisableChange(this, true); } this.fireEvent("disabledchange", this, true); }, enable : function(){ this.disabled = false; if(this.rendered && this.ui.onDisableChange){ this.ui.onDisableChange(this, false); } this.fireEvent("disabledchange", this, false); }, renderChildren : function(suppressEvent){ if(suppressEvent !== false){ this.fireEvent("beforechildrenrendered", this); } var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++){ cs[i].render(true); } this.childrenRendered = true; }, sort : function(fn, scope){ Ext.tree.TreeNode.superclass.sort.apply(this, arguments); if(this.childrenRendered){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++){ cs[i].render(true); } } }, render : function(bulkRender){ this.ui.render(bulkRender); if(!this.rendered){ this.getOwnerTree().registerNode(this); this.rendered = true; if(this.expanded){ this.expanded = false; this.expand(false, false); } } }, renderIndent : function(deep, refresh){ if(refresh){ this.ui.childIndent = null; } this.ui.renderIndent(); if(deep === true && this.childrenRendered){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++){ cs[i].renderIndent(true, refresh); } } }, beginUpdate : function(){ this.childrenRendered = false; }, endUpdate : function(){ if(this.expanded){ this.renderChildren(); } }, destroy : function(){ for(var i = 0,l = this.childNodes.length; i < l; i++){ this.childNodes[i].destroy(); } this.childNodes = null; if(this.ui.destroy){ this.ui.destroy(); } } }); Ext.tree.AsyncTreeNode = function(config){ this.loaded = false; this.loading = false; Ext.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments); this.addEvents('beforeload', 'load'); }; Ext.extend(Ext.tree.AsyncTreeNode, Ext.tree.TreeNode, { expand : function(deep, anim, callback){ if(this.loading){ var timer; var f = function(){ if(!this.loading){ clearInterval(timer); this.expand(deep, anim, callback); } }.createDelegate(this); timer = setInterval(f, 200); return; } if(!this.loaded){ if(this.fireEvent("beforeload", this) === false){ return; } this.loading = true; this.ui.beforeLoad(this); var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader(); if(loader){ loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback])); return; } } Ext.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback); }, isLoading : function(){ return this.loading; }, loadComplete : function(deep, anim, callback){ this.loading = false; this.loaded = true; this.ui.afterLoad(this); this.fireEvent("load", this); this.expand(deep, anim, callback); }, isLoaded : function(){ return this.loaded; }, hasChildNodes : function(){ if(!this.isLeaf() && !this.loaded){ return true; }else{ return Ext.tree.AsyncTreeNode.superclass.hasChildNodes.call(this); } }, reload : function(callback){ this.collapse(false, false); while(this.firstChild){ this.removeChild(this.firstChild); } this.childrenRendered = false; this.loaded = false; if(this.isHiddenRoot()){ this.expanded = false; } this.expand(false, false, callback); } }); Ext.tree.TreeNodeUI = function(node){ this.node = node; this.rendered = false; this.animating = false; this.wasLeaf = true; this.ecc = 'x-tree-ec-icon x-tree-elbow'; this.emptyIcon = Ext.BLANK_IMAGE_URL; }; Ext.tree.TreeNodeUI.prototype = { removeChild : function(node){ if(this.rendered){ this.ctNode.removeChild(node.ui.getEl()); } }, beforeLoad : function(){ this.addClass("x-tree-node-loading"); }, afterLoad : function(){ this.removeClass("x-tree-node-loading"); }, onTextChange : function(node, text, oldText){ if(this.rendered){ this.textNode.innerHTML = text; } }, onDisableChange : function(node, state){ this.disabled = state; if (this.checkbox) { this.checkbox.disabled = state; } if(state){ this.addClass("x-tree-node-disabled"); }else{ this.removeClass("x-tree-node-disabled"); } }, onSelectedChange : function(state){ if(state){ this.focus(); this.addClass("x-tree-selected"); }else{ this.removeClass("x-tree-selected"); } }, onMove : function(tree, node, oldParent, newParent, index, refNode){ this.childIndent = null; if(this.rendered){ var targetNode = newParent.ui.getContainer(); if(!targetNode){ this.holder = document.createElement("div"); this.holder.appendChild(this.wrap); return; } var insertBefore = refNode ? refNode.ui.getEl() : null; if(insertBefore){ targetNode.insertBefore(this.wrap, insertBefore); }else{ targetNode.appendChild(this.wrap); } this.node.renderIndent(true); } }, addClass : function(cls){ if(this.elNode){ Ext.fly(this.elNode).addClass(cls); } }, removeClass : function(cls){ if(this.elNode){ Ext.fly(this.elNode).removeClass(cls); } }, remove : function(){ if(this.rendered){ this.holder = document.createElement("div"); this.holder.appendChild(this.wrap); } }, fireEvent : function(){ return this.node.fireEvent.apply(this.node, arguments); }, initEvents : function(){ this.node.on("move", this.onMove, this); if(this.node.disabled){ this.addClass("x-tree-node-disabled"); if (this.checkbox) { this.checkbox.disabled = true; } } if(this.node.hidden){ this.hide(); } var ot = this.node.getOwnerTree(); var dd = ot.enableDD || ot.enableDrag || ot.enableDrop; if(dd && (!this.node.isRoot || ot.rootVisible)){ Ext.dd.Registry.register(this.elNode, { node: this.node, handles: this.getDDHandles(), isHandle: false }); } }, getDDHandles : function(){ return [this.iconNode, this.textNode, this.elNode]; }, hide : function(){ this.node.hidden = true; if(this.wrap){ this.wrap.style.display = "none"; } }, show : function(){ this.node.hidden = false; if(this.wrap){ this.wrap.style.display = ""; } }, onContextMenu : function(e){ if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) { e.preventDefault(); this.focus(); this.fireEvent("contextmenu", this.node, e); } }, onClick : function(e){ if(this.dropping){ e.stopEvent(); return; } if(this.fireEvent("beforeclick", this.node, e) !== false){ var a = e.getTarget('a'); if(!this.disabled && this.node.attributes.href && a){ this.fireEvent("click", this.node, e); return; }else if(a && e.ctrlKey){ e.stopEvent(); } e.preventDefault(); if(this.disabled){ return; } if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){ this.node.toggle(); } this.fireEvent("click", this.node, e); }else{ e.stopEvent(); } }, onDblClick : function(e){ e.preventDefault(); if(this.disabled){ return; } if(this.checkbox){ this.toggleCheck(); } if(!this.animating && this.node.hasChildNodes()){ this.node.toggle(); } this.fireEvent("dblclick", this.node, e); }, onOver : function(e){ this.addClass('x-tree-node-over'); }, onOut : function(e){ this.removeClass('x-tree-node-over'); }, onCheckChange : function(){ var checked = this.checkbox.checked; this.node.attributes.checked = checked; this.fireEvent('checkchange', this.node, checked); }, ecClick : function(e){ if(!this.animating && (this.node.hasChildNodes() || this.node.attributes.expandable)){ this.node.toggle(); } }, startDrop : function(){ this.dropping = true; }, endDrop : function(){ setTimeout(function(){ this.dropping = false; }.createDelegate(this), 50); }, expand : function(){ this.updateExpandIcon(); this.ctNode.style.display = ""; }, focus : function(){ if(!this.node.preventHScroll){ try{this.anchor.focus(); }catch(e){} }else if(!Ext.isIE){ try{ var noscroll = this.node.getOwnerTree().getTreeEl().dom; var l = noscroll.scrollLeft; this.anchor.focus(); noscroll.scrollLeft = l; }catch(e){} } }, toggleCheck : function(value){ var cb = this.checkbox; if(cb){ cb.checked = (value === undefined ? !cb.checked : value); } }, blur : function(){ try{ this.anchor.blur(); }catch(e){} }, animExpand : function(callback){ var ct = Ext.get(this.ctNode); ct.stopFx(); if(!this.node.hasChildNodes()){ this.updateExpandIcon(); this.ctNode.style.display = ""; Ext.callback(callback); return; } this.animating = true; this.updateExpandIcon(); ct.slideIn('t', { callback : function(){ this.animating = false; Ext.callback(callback); }, scope: this, duration: this.node.ownerTree.duration || .25 }); }, highlight : function(){ var tree = this.node.getOwnerTree(); Ext.fly(this.wrap).highlight( tree.hlColor || "C3DAF9", {endColor: tree.hlBaseColor} ); }, collapse : function(){ this.updateExpandIcon(); this.ctNode.style.display = "none"; }, animCollapse : function(callback){ var ct = Ext.get(this.ctNode); ct.enableDisplayMode('block'); ct.stopFx(); this.animating = true; this.updateExpandIcon(); ct.slideOut('t', { callback : function(){ this.animating = false; Ext.callback(callback); }, scope: this, duration: this.node.ownerTree.duration || .25 }); }, getContainer : function(){ return this.ctNode; }, getEl : function(){ return this.wrap; }, appendDDGhost : function(ghostNode){ ghostNode.appendChild(this.elNode.cloneNode(true)); }, getDDRepairXY : function(){ return Ext.lib.Dom.getXY(this.iconNode); }, onRender : function(){ this.render(); }, render : function(bulkRender){ var n = this.node, a = n.attributes; var targetNode = n.parentNode ? n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom; if(!this.rendered){ this.rendered = true; this.renderElements(n, a, targetNode, bulkRender); if(a.qtip){ if(this.textNode.setAttributeNS){ this.textNode.setAttributeNS("ext", "qtip", a.qtip); if(a.qtipTitle){ this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle); } }else{ this.textNode.setAttribute("ext:qtip", a.qtip); if(a.qtipTitle){ this.textNode.setAttribute("ext:qtitle", a.qtipTitle); } } }else if(a.qtipCfg){ a.qtipCfg.target = Ext.id(this.textNode); Ext.QuickTips.register(a.qtipCfg); } this.initEvents(); if(!this.node.expanded){ this.updateExpandIcon(true); } }else{ if(bulkRender === true) { targetNode.appendChild(this.wrap); } } }, renderElements : function(n, a, targetNode, bulkRender){ this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : ''; var cb = typeof a.checked == 'boolean'; var href = a.href ? a.href : Ext.isGecko ? "" : "#"; var buf = ['<li class="x-tree-node"><div ext:tree-node-id="',n.id,'" class="x-tree-node-el x-tree-node-leaf x-unselectable ', a.cls,'" unselectable="on">', '<span class="x-tree-node-indent">',this.indentMarkup,"</span>", '<img src="', this.emptyIcon, '" class="x-tree-ec-icon x-tree-elbow" />', '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />', cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : '/>')) : '', '<a hidefocus="on" class="x-tree-node-anchor" href="',href,'" tabIndex="1" ', a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", '><span unselectable="on">',n.text,"</span></a></div>", '<ul class="x-tree-node-ct" style="display:none;"></ul>', "</li>"].join(''); var nel; if(bulkRender !== true && n.nextSibling && (nel = n.nextSibling.ui.getEl())){ this.wrap = Ext.DomHelper.insertHtml("beforeBegin", nel, buf); }else{ this.wrap = Ext.DomHelper.insertHtml("beforeEnd", targetNode, buf); } this.elNode = this.wrap.childNodes[0]; this.ctNode = this.wrap.childNodes[1]; var cs = this.elNode.childNodes; this.indentNode = cs[0]; this.ecNode = cs[1]; this.iconNode = cs[2]; var index = 3; if(cb){ this.checkbox = cs[3]; index++; } this.anchor = cs[index]; this.textNode = cs[index].firstChild; }, getAnchor : function(){ return this.anchor; }, getTextEl : function(){ return this.textNode; }, getIconEl : function(){ return this.iconNode; }, isChecked : function(){ return this.checkbox ? this.checkbox.checked : false; }, updateExpandIcon : function(){ if(this.rendered){ var n = this.node, c1, c2; var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow"; var hasChild = n.hasChildNodes(); if(hasChild || n.attributes.expandable){ if(n.expanded){ cls += "-minus"; c1 = "x-tree-node-collapsed"; c2 = "x-tree-node-expanded"; }else{ cls += "-plus"; c1 = "x-tree-node-expanded"; c2 = "x-tree-node-collapsed"; } if(this.wasLeaf){ this.removeClass("x-tree-node-leaf"); this.wasLeaf = false; } if(this.c1 != c1 || this.c2 != c2){ Ext.fly(this.elNode).replaceClass(c1, c2); this.c1 = c1; this.c2 = c2; } }else{ if(!this.wasLeaf){ Ext.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf"); delete this.c1; delete this.c2; this.wasLeaf = true; } } var ecc = "x-tree-ec-icon "+cls; if(this.ecc != ecc){ this.ecNode.className = ecc; this.ecc = ecc; } } }, getChildIndent : function(){ if(!this.childIndent){ var buf = []; var p = this.node; while(p){ if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){ if(!p.isLast()) { buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />'); } else { buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />'); } } p = p.parentNode; } this.childIndent = buf.join(""); } return this.childIndent; }, renderIndent : function(){ if(this.rendered){ var indent = ""; var p = this.node.parentNode; if(p){ indent = p.ui.getChildIndent(); } if(this.indentMarkup != indent){ this.indentNode.innerHTML = indent; this.indentMarkup = indent; } this.updateExpandIcon(); } }, destroy : function(){ if(this.elNode){ Ext.dd.Registry.unregister(this.elNode.id); } delete this.elNode; delete this.ctNode; delete this.indentNode; delete this.ecNode; delete this.iconNode; delete this.checkbox; delete this.anchor; delete this.textNode; Ext.removeNode(this.ctNode); } }; Ext.tree.RootTreeNodeUI = Ext.extend(Ext.tree.TreeNodeUI, { render : function(){ if(!this.rendered){ var targetNode = this.node.ownerTree.innerCt.dom; this.node.expanded = true; targetNode.innerHTML = '<div class="x-tree-root-node"></div>'; this.wrap = this.ctNode = targetNode.firstChild; } }, collapse : Ext.emptyFn, expand : Ext.emptyFn }); Ext.tree.TreeLoader = function(config){ this.baseParams = {}; this.requestMethod = "POST"; Ext.apply(this, config); this.addEvents( "beforeload", "load", "loadexception" ); Ext.tree.TreeLoader.superclass.constructor.call(this); }; Ext.extend(Ext.tree.TreeLoader, Ext.util.Observable, { uiProviders : {}, clearOnLoad : true, load : function(node, callback){ if(this.clearOnLoad){ while(node.firstChild){ node.removeChild(node.firstChild); } } if(this.doPreload(node)){ if(typeof callback == "function"){ callback(); } }else if(this.dataUrl||this.url){ this.requestData(node, callback); } }, doPreload : function(node){ if(node.attributes.children){ if(node.childNodes.length < 1){ var cs = node.attributes.children; node.beginUpdate(); for(var i = 0, len = cs.length; i < len; i++){ var cn = node.appendChild(this.createNode(cs[i])); if(this.preloadChildren){ this.doPreload(cn); } } node.endUpdate(); } return true; }else { return false; } }, getParams: function(node){ var buf = [], bp = this.baseParams; for(var key in bp){ if(typeof bp[key] != "function"){ buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&"); } } buf.push("node=", encodeURIComponent(node.id)); return buf.join(""); }, requestData : function(node, callback){ if(this.fireEvent("beforeload", this, node, callback) !== false){ this.transId = Ext.Ajax.request({ method:this.requestMethod, url: this.dataUrl||this.url, success: this.handleResponse, failure: this.handleFailure, scope: this, argument: {callback: callback, node: node}, params: this.getParams(node) }); }else{ if(typeof callback == "function"){ callback(); } } }, isLoading : function(){ return this.transId ? true : false; }, abort : function(){ if(this.isLoading()){ Ext.Ajax.abort(this.transId); } }, createNode : function(attr){ if(this.baseAttrs){ Ext.applyIf(attr, this.baseAttrs); } if(this.applyLoader !== false){ attr.loader = this; } if(typeof attr.uiProvider == 'string'){ attr.uiProvider = this.uiProviders[attr.uiProvider] || eval(attr.uiProvider); } return(attr.leaf ? new Ext.tree.TreeNode(attr) : new Ext.tree.AsyncTreeNode(attr)); }, processResponse : function(response, node, callback){ var json = response.responseText; try { var o = eval("("+json+")"); node.beginUpdate(); for(var i = 0, len = o.length; i < len; i++){ var n = this.createNode(o[i]); if(n){ node.appendChild(n); } } node.endUpdate(); if(typeof callback == "function"){ callback(this, node); } }catch(e){ this.handleFailure(response); } }, handleResponse : function(response){ this.transId = false; var a = response.argument; this.processResponse(response, a.node, a.callback); this.fireEvent("load", this, a.node, response); }, handleFailure : function(response){ this.transId = false; var a = response.argument; this.fireEvent("loadexception", this, a.node, response); if(typeof a.callback == "function"){ a.callback(this, a.node); } } }); Ext.tree.TreeFilter = function(tree, config){ this.tree = tree; this.filtered = {}; Ext.apply(this, config); }; Ext.tree.TreeFilter.prototype = { clearBlank:false, reverse:false, autoClear:false, remove:false, filter : function(value, attr, startNode){ attr = attr || "text"; var f; if(typeof value == "string"){ var vlen = value.length; if(vlen == 0 && this.clearBlank){ this.clear(); return; } value = value.toLowerCase(); f = function(n){ return n.attributes[attr].substr(0, vlen).toLowerCase() == value; }; }else if(value.exec){ f = function(n){ return value.test(n.attributes[attr]); }; }else{ throw 'Illegal filter type, must be string or regex'; } this.filterBy(f, null, startNode); }, filterBy : function(fn, scope, startNode){ startNode = startNode || this.tree.root; if(this.autoClear){ this.clear(); } var af = this.filtered, rv = this.reverse; var f = function(n){ if(n == startNode){ return true; } if(af[n.id]){ return false; } var m = fn.call(scope || n, n); if(!m || rv){ af[n.id] = n; n.ui.hide(); return false; } return true; }; startNode.cascade(f); if(this.remove){ for(var id in af){ if(typeof id != "function"){ var n = af[id]; if(n && n.parentNode){ n.parentNode.removeChild(n); } } } } }, clear : function(){ var t = this.tree; var af = this.filtered; for(var id in af){ if(typeof id != "function"){ var n = af[id]; if(n){ n.ui.show(); } } } this.filtered = {}; } }; Ext.tree.TreeSorter = function(tree, config){ Ext.apply(this, config); tree.on("beforechildrenrendered", this.doSort, this); tree.on("append", this.updateSort, this); tree.on("insert", this.updateSort, this); tree.on("textchange", this.updateSortParent, this); var dsc = this.dir && this.dir.toLowerCase() == "desc"; var p = this.property || "text"; var sortType = this.sortType; var fs = this.folderSort; var cs = this.caseSensitive === true; var leafAttr = this.leafAttr || 'leaf'; this.sortFn = function(n1, n2){ if(fs){ if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){ return 1; } if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){ return -1; } } var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase()); var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase()); if(v1 < v2){ return dsc ? +1 : -1; }else if(v1 > v2){ return dsc ? -1 : +1; }else{ return 0; } }; }; Ext.tree.TreeSorter.prototype = { doSort : function(node){ node.sort(this.sortFn); }, compareNodes : function(n1, n2){ return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1); }, updateSort : function(tree, node){ if(node.childrenRendered){ this.doSort.defer(1, this, [node]); } }, updateSortParent : function(node){ var p = node.parentNode; if(p && p.childrenRendered){ this.doSort.defer(1, this, [p]); } } }; if(Ext.dd.DropZone){ Ext.tree.TreeDropZone = function(tree, config){ this.allowParentInsert = false; this.allowContainerDrop = false; this.appendOnly = false; Ext.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config); this.tree = tree; this.dragOverData = {}; this.lastInsertClass = "x-tree-no-status"; }; Ext.extend(Ext.tree.TreeDropZone, Ext.dd.DropZone, { ddGroup : "TreeDD", expandDelay : 1000, expandNode : function(node){ if(node.hasChildNodes() && !node.isExpanded()){ node.expand(false, null, this.triggerCacheRefresh.createDelegate(this)); } }, queueExpand : function(node){ this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]); }, cancelExpand : function(){ if(this.expandProcId){ clearTimeout(this.expandProcId); this.expandProcId = false; } }, isValidDropPoint : function(n, pt, dd, e, data){ if(!n || !data){ return false; } var targetNode = n.node; var dropNode = data.node; if(!(targetNode && targetNode.isTarget && pt)){ return false; } if(pt == "append" && targetNode.allowChildren === false){ return false; } if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){ return false; } if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){ return false; } var overEvent = this.dragOverData; overEvent.tree = this.tree; overEvent.target = targetNode; overEvent.data = data; overEvent.point = pt; overEvent.source = dd; overEvent.rawEvent = e; overEvent.dropNode = dropNode; overEvent.cancel = false; var result = this.tree.fireEvent("nodedragover", overEvent); return overEvent.cancel === false && result !== false; }, getDropPoint : function(e, n, dd){ var tn = n.node; if(tn.isRoot){ return tn.allowChildren !== false ? "append" : false; } var dragEl = n.ddel; var t = Ext.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight; var y = Ext.lib.Event.getPageY(e); var noAppend = tn.allowChildren === false || tn.isLeaf(); if(this.appendOnly || tn.parentNode.allowChildren === false){ return noAppend ? false : "append"; } var noBelow = false; if(!this.allowParentInsert){ noBelow = tn.hasChildNodes() && tn.isExpanded(); } var q = (b - t) / (noAppend ? 2 : 3); if(y >= t && y < (t + q)){ return "above"; }else if(!noBelow && (noAppend || y >= b-q && y <= b)){ return "below"; }else{ return "append"; } }, onNodeEnter : function(n, dd, e, data){ this.cancelExpand(); }, onNodeOver : function(n, dd, e, data){ var pt = this.getDropPoint(e, n, dd); var node = n.node; if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){ this.queueExpand(node); }else if(pt != "append"){ this.cancelExpand(); } var returnCls = this.dropNotAllowed; if(this.isValidDropPoint(n, pt, dd, e, data)){ if(pt){ var el = n.ddel; var cls; if(pt == "above"){ returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between"; cls = "x-tree-drag-insert-above"; }else if(pt == "below"){ returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between"; cls = "x-tree-drag-insert-below"; }else{ returnCls = "x-tree-drop-ok-append"; cls = "x-tree-drag-append"; } if(this.lastInsertClass != cls){ Ext.fly(el).replaceClass(this.lastInsertClass, cls); this.lastInsertClass = cls; } } } return returnCls; }, onNodeOut : function(n, dd, e, data){ this.cancelExpand(); this.removeDropIndicators(n); }, onNodeDrop : function(n, dd, e, data){ var point = this.getDropPoint(e, n, dd); var targetNode = n.node; targetNode.ui.startDrop(); if(!this.isValidDropPoint(n, point, dd, e, data)){ targetNode.ui.endDrop(); return false; } var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null); var dropEvent = { tree : this.tree, target: targetNode, data: data, point: point, source: dd, rawEvent: e, dropNode: dropNode, cancel: !dropNode, dropStatus: false }; var retval = this.tree.fireEvent("beforenodedrop", dropEvent); if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){ targetNode.ui.endDrop(); return dropEvent.dropStatus; } targetNode = dropEvent.target; if(point == "append" && !targetNode.isExpanded()){ targetNode.expand(false, null, function(){ this.completeDrop(dropEvent); }.createDelegate(this)); }else{ this.completeDrop(dropEvent); } return true; }, completeDrop : function(de){ var ns = de.dropNode, p = de.point, t = de.target; if(!Ext.isArray(ns)){ ns = [ns]; } var n; for(var i = 0, len = ns.length; i < len; i++){ n = ns[i]; if(p == "above"){ t.parentNode.insertBefore(n, t); }else if(p == "below"){ t.parentNode.insertBefore(n, t.nextSibling); }else{ t.appendChild(n); } } n.ui.focus(); if(this.tree.hlDrop){ n.ui.highlight(); } t.ui.endDrop(); this.tree.fireEvent("nodedrop", de); }, afterNodeMoved : function(dd, data, e, targetNode, dropNode){ if(this.tree.hlDrop){ dropNode.ui.focus(); dropNode.ui.highlight(); } this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e); }, getTree : function(){ return this.tree; }, removeDropIndicators : function(n){ if(n && n.ddel){ var el = n.ddel; Ext.fly(el).removeClass([ "x-tree-drag-insert-above", "x-tree-drag-insert-below", "x-tree-drag-append"]); this.lastInsertClass = "_noclass"; } }, beforeDragDrop : function(target, e, id){ this.cancelExpand(); return true; }, afterRepair : function(data){ if(data && Ext.enableFx){ data.node.ui.highlight(); } this.hideProxy(); } }); } if(Ext.dd.DragZone){ Ext.tree.TreeDragZone = function(tree, config){ Ext.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config); this.tree = tree; }; Ext.extend(Ext.tree.TreeDragZone, Ext.dd.DragZone, { ddGroup : "TreeDD", onBeforeDrag : function(data, e){ var n = data.node; return n && n.draggable && !n.disabled; }, onInitDrag : function(e){ var data = this.dragData; this.tree.getSelectionModel().select(data.node); this.tree.eventModel.disable(); this.proxy.update(""); data.node.ui.appendDDGhost(this.proxy.ghost.dom); this.tree.fireEvent("startdrag", this.tree, data.node, e); }, getRepairXY : function(e, data){ return data.node.ui.getDDRepairXY(); }, onEndDrag : function(data, e){ this.tree.eventModel.enable.defer(100, this.tree.eventModel); this.tree.fireEvent("enddrag", this.tree, data.node, e); }, onValidDrop : function(dd, e, id){ this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e); this.hideProxy(); }, beforeInvalidDrop : function(e, id){ var sm = this.tree.getSelectionModel(); sm.clearSelections(); sm.select(this.dragData.node); } }); } Ext.tree.TreeEditor = function(tree, config){ config = config || {}; var field = config.events ? config : new Ext.form.TextField(config); Ext.tree.TreeEditor.superclass.constructor.call(this, field); this.tree = tree; if(!tree.rendered){ tree.on('render', this.initEditor, this); }else{ this.initEditor(tree); } }; Ext.extend(Ext.tree.TreeEditor, Ext.Editor, { alignment: "l-l", autoSize: false, hideEl : false, cls: "x-small-editor x-tree-editor", shim:false, shadow:"frame", maxWidth: 250, editDelay : 350, initEditor : function(tree){ tree.on('beforeclick', this.beforeNodeClick, this); tree.on('dblclick', this.onNodeDblClick, this); this.on('complete', this.updateNode, this); this.on('beforestartedit', this.fitToTree, this); this.on('startedit', this.bindScroll, this, {delay:10}); this.on('specialkey', this.onSpecialKey, this); }, fitToTree : function(ed, el){ var td = this.tree.getTreeEl().dom, nd = el.dom; if(td.scrollLeft > nd.offsetLeft){ td.scrollLeft = nd.offsetLeft; } var w = Math.min( this.maxWidth, (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - 5); this.setSize(w, ''); }, triggerEdit : function(node, defer){ this.completeEdit(); if(node.attributes.editable !== false){ this.editNode = node; this.autoEditTimer = this.startEdit.defer(this.editDelay, this, [node.ui.textNode, node.text]); return false; } }, bindScroll : function(){ this.tree.getTreeEl().on('scroll', this.cancelEdit, this); }, beforeNodeClick : function(node, e){ clearTimeout(this.autoEditTimer); if(this.tree.getSelectionModel().isSelected(node)){ e.stopEvent(); return this.triggerEdit(node); } }, onNodeDblClick : function(node, e){ clearTimeout(this.autoEditTimer); }, updateNode : function(ed, value){ this.tree.getTreeEl().un('scroll', this.cancelEdit, this); this.editNode.setText(value); }, onHide : function(){ Ext.tree.TreeEditor.superclass.onHide.call(this); if(this.editNode){ this.editNode.ui.focus.defer(50, this.editNode.ui); } }, onSpecialKey : function(field, e){ var k = e.getKey(); if(k == e.ESC){ e.stopEvent(); this.cancelEdit(); }else if(k == e.ENTER && !e.hasModifier()){ e.stopEvent(); this.completeEdit(); } } }); Ext.menu.Menu = function(config){ if(Ext.isArray(config)){ config = {items:config}; } Ext.apply(this, config); this.id = this.id || Ext.id(); this.addEvents( 'beforeshow', 'beforehide', 'show', 'hide', 'click', 'mouseover', 'mouseout', 'itemclick' ); Ext.menu.MenuMgr.register(this); Ext.menu.Menu.superclass.constructor.call(this); var mis = this.items; this.items = new Ext.util.MixedCollection(); if(mis){ this.add.apply(this, mis); } }; Ext.extend(Ext.menu.Menu, Ext.util.Observable, { minWidth : 120, shadow : "sides", subMenuAlign : "tl-tr?", defaultAlign : "tl-bl?", allowOtherMenus : false, hidden:true, createEl : function(){ return new Ext.Layer({ cls: "x-menu", shadow:this.shadow, constrain: false, parentEl: this.parentEl || document.body, zindex:15000 }); }, render : function(){ if(this.el){ return; } var el = this.el = this.createEl(); if(!this.keyNav){ this.keyNav = new Ext.menu.MenuNav(this); } if(this.plain){ el.addClass("x-menu-plain"); } if(this.cls){ el.addClass(this.cls); } this.focusEl = el.createChild({ tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1" }); var ul = el.createChild({tag: "ul", cls: "x-menu-list"}); ul.on("click", this.onClick, this); ul.on("mouseover", this.onMouseOver, this); ul.on("mouseout", this.onMouseOut, this); this.items.each(function(item){ var li = document.createElement("li"); li.className = "x-menu-list-item"; ul.dom.appendChild(li); item.render(li, this); }, this); this.ul = ul; this.autoWidth(); }, autoWidth : function(){ var el = this.el, ul = this.ul; if(!el){ return; } var w = this.width; if(w){ el.setWidth(w); }else if(Ext.isIE){ el.setWidth(this.minWidth); var t = el.dom.offsetWidth; el.setWidth(ul.getWidth()+el.getFrameWidth("lr")); } }, delayAutoWidth : function(){ if(this.el){ if(!this.awTask){ this.awTask = new Ext.util.DelayedTask(this.autoWidth, this); } this.awTask.delay(20); } }, findTargetItem : function(e){ var t = e.getTarget(".x-menu-list-item", this.ul, true); if(t && t.menuItemId){ return this.items.get(t.menuItemId); } }, onClick : function(e){ var t; if(t = this.findTargetItem(e)){ t.onClick(e); this.fireEvent("click", this, t, e); } }, setActiveItem : function(item, autoExpand){ if(item != this.activeItem){ if(this.activeItem){ this.activeItem.deactivate(); } this.activeItem = item; item.activate(autoExpand); }else if(autoExpand){ item.expandMenu(); } }, tryActivate : function(start, step){ var items = this.items; for(var i = start, len = items.length; i >= 0 && i < len; i+= step){ var item = items.get(i); if(!item.disabled && item.canActivate){ this.setActiveItem(item, false); return item; } } return false; }, onMouseOver : function(e){ var t; if(t = this.findTargetItem(e)){ if(t.canActivate && !t.disabled){ this.setActiveItem(t, true); } } this.fireEvent("mouseover", this, e, t); }, onMouseOut : function(e){ var t; if(t = this.findTargetItem(e)){ if(t == this.activeItem && t.shouldDeactivate(e)){ this.activeItem.deactivate(); delete this.activeItem; } } this.fireEvent("mouseout", this, e, t); }, isVisible : function(){ return this.el && !this.hidden; }, show : function(el, pos, parentMenu){ this.parentMenu = parentMenu; if(!this.el){ this.render(); } this.fireEvent("beforeshow", this); this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false); }, showAt : function(xy, parentMenu, _e){ this.parentMenu = parentMenu; if(!this.el){ this.render(); } if(_e !== false){ this.fireEvent("beforeshow", this); xy = this.el.adjustForConstraints(xy); } this.el.setXY(xy); this.el.show(); this.hidden = false; this.focus(); this.fireEvent("show", this); }, focus : function(){ if(!this.hidden){ this.doFocus.defer(50, this); } }, doFocus : function(){ if(!this.hidden){ this.focusEl.focus(); } }, hide : function(deep){ if(this.el && this.isVisible()){ this.fireEvent("beforehide", this); if(this.activeItem){ this.activeItem.deactivate(); this.activeItem = null; } this.el.hide(); this.hidden = true; this.fireEvent("hide", this); } if(deep === true && this.parentMenu){ this.parentMenu.hide(true); } }, add : function(){ var a = arguments, l = a.length, item; for(var i = 0; i < l; i++){ var el = a[i]; if(el.render){ item = this.addItem(el); }else if(typeof el == "string"){ if(el == "separator" || el == "-"){ item = this.addSeparator(); }else{ item = this.addText(el); } }else if(el.tagName || el.el){ item = this.addElement(el); }else if(typeof el == "object"){ Ext.applyIf(el, this.defaults); item = this.addMenuItem(el); } } return item; }, getEl : function(){ if(!this.el){ this.render(); } return this.el; }, addSeparator : function(){ return this.addItem(new Ext.menu.Separator()); }, addElement : function(el){ return this.addItem(new Ext.menu.BaseItem(el)); }, addItem : function(item){ this.items.add(item); if(this.ul){ var li = document.createElement("li"); li.className = "x-menu-list-item"; this.ul.dom.appendChild(li); item.render(li, this); this.delayAutoWidth(); } return item; }, addMenuItem : function(config){ if(!(config instanceof Ext.menu.Item)){ if(typeof config.checked == "boolean"){ config = new Ext.menu.CheckItem(config); }else{ config = new Ext.menu.Item(config); } } return this.addItem(config); }, addText : function(text){ return this.addItem(new Ext.menu.TextItem(text)); }, insert : function(index, item){ this.items.insert(index, item); if(this.ul){ var li = document.createElement("li"); li.className = "x-menu-list-item"; this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]); item.render(li, this); this.delayAutoWidth(); } return item; }, remove : function(item){ this.items.removeKey(item.id); item.destroy(); }, removeAll : function(){ var f; while(f = this.items.first()){ this.remove(f); } }, destroy : function(){ this.beforeDestroy(); Ext.menu.MenuMgr.unregister(this); if (this.keyNav) { this.keyNav.disable(); } this.removeAll(); if (this.ul) { this.ul.removeAllListeners(); } if (this.el) { this.el.destroy(); } }, beforeDestroy : Ext.emptyFn }); Ext.menu.MenuNav = function(menu){ Ext.menu.MenuNav.superclass.constructor.call(this, menu.el); this.scope = this.menu = menu; }; Ext.extend(Ext.menu.MenuNav, Ext.KeyNav, { doRelay : function(e, h){ var k = e.getKey(); if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){ this.menu.tryActivate(0, 1); return false; } return h.call(this.scope || this, e, this.menu); }, up : function(e, m){ if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){ m.tryActivate(m.items.length-1, -1); } }, down : function(e, m){ if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){ m.tryActivate(0, 1); } }, right : function(e, m){ if(m.activeItem){ m.activeItem.expandMenu(true); } }, left : function(e, m){ m.hide(); if(m.parentMenu && m.parentMenu.activeItem){ m.parentMenu.activeItem.activate(); } }, enter : function(e, m){ if(m.activeItem){ e.stopPropagation(); m.activeItem.onClick(e); m.fireEvent("click", this, m.activeItem); return true; } } }); Ext.menu.MenuMgr = function(){ var menus, active, groups = {}, attached = false, lastShow = new Date(); function init(){ menus = {}; active = new Ext.util.MixedCollection(); Ext.getDoc().addKeyListener(27, function(){ if(active.length > 0){ hideAll(); } }); } function hideAll(){ if(active && active.length > 0){ var c = active.clone(); c.each(function(m){ m.hide(); }); } } function onHide(m){ active.remove(m); if(active.length < 1){ Ext.getDoc().un("mousedown", onMouseDown); attached = false; } } function onShow(m){ var last = active.last(); lastShow = new Date(); active.add(m); if(!attached){ Ext.getDoc().on("mousedown", onMouseDown); attached = true; } if(m.parentMenu){ m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3); m.parentMenu.activeChild = m; }else if(last && last.isVisible()){ m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3); } } function onBeforeHide(m){ if(m.activeChild){ m.activeChild.hide(); } if(m.autoHideTimer){ clearTimeout(m.autoHideTimer); delete m.autoHideTimer; } } function onBeforeShow(m){ var pm = m.parentMenu; if(!pm && !m.allowOtherMenus){ hideAll(); }else if(pm && pm.activeChild){ pm.activeChild.hide(); } } function onMouseDown(e){ if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){ hideAll(); } } function onBeforeCheck(mi, state){ if(state){ var g = groups[mi.group]; for(var i = 0, l = g.length; i < l; i++){ if(g[i] != mi){ g[i].setChecked(false); } } } } return { hideAll : function(){ hideAll(); }, register : function(menu){ if(!menus){ init(); } menus[menu.id] = menu; menu.on("beforehide", onBeforeHide); menu.on("hide", onHide); menu.on("beforeshow", onBeforeShow); menu.on("show", onShow); var g = menu.group; if(g && menu.events["checkchange"]){ if(!groups[g]){ groups[g] = []; } groups[g].push(menu); menu.on("checkchange", onCheck); } }, get : function(menu){ if(typeof menu == "string"){ if(!menus){ return null; } return menus[menu]; }else if(menu.events){ return menu; }else if(typeof menu.length == 'number'){ return new Ext.menu.Menu({items:menu}); }else{ return new Ext.menu.Menu(menu); } }, unregister : function(menu){ delete menus[menu.id]; menu.un("beforehide", onBeforeHide); menu.un("hide", onHide); menu.un("beforeshow", onBeforeShow); menu.un("show", onShow); var g = menu.group; if(g && menu.events["checkchange"]){ groups[g].remove(menu); menu.un("checkchange", onCheck); } }, registerCheckable : function(menuItem){ var g = menuItem.group; if(g){ if(!groups[g]){ groups[g] = []; } groups[g].push(menuItem); menuItem.on("beforecheckchange", onBeforeCheck); } }, unregisterCheckable : function(menuItem){ var g = menuItem.group; if(g){ groups[g].remove(menuItem); menuItem.un("beforecheckchange", onBeforeCheck); } }, getCheckedItem : function(groupId){ var g = groups[groupId]; if(g){ for(var i = 0, l = g.length; i < l; i++){ if(g[i].checked){ return g[i]; } } } return null; }, setCheckedItem : function(groupId, itemId){ var g = groups[groupId]; if(g){ for(var i = 0, l = g.length; i < l; i++){ if(g[i].id == itemId){ g[i].setChecked(true); } } } return null; } }; }(); Ext.menu.BaseItem = function(config){ Ext.menu.BaseItem.superclass.constructor.call(this, config); this.addEvents( 'click', 'activate', 'deactivate' ); if(this.handler){ this.on("click", this.handler, this.scope); } }; Ext.extend(Ext.menu.BaseItem, Ext.Component, { canActivate : false, activeClass : "x-menu-item-active", hideOnClick : true, hideDelay : 100, ctype: "Ext.menu.BaseItem", actionMode : "container", render : function(container, parentMenu){ this.parentMenu = parentMenu; Ext.menu.BaseItem.superclass.render.call(this, container); this.container.menuItemId = this.id; }, onRender : function(container, position){ this.el = Ext.get(this.el); container.dom.appendChild(this.el.dom); }, setHandler : function(handler, scope){ if(this.handler){ this.un("click", this.handler, this.scope); } this.on("click", this.handler = handler, this.scope = scope); }, onClick : function(e){ if(!this.disabled && this.fireEvent("click", this, e) !== false && this.parentMenu.fireEvent("itemclick", this, e) !== false){ this.handleClick(e); }else{ e.stopEvent(); } }, activate : function(){ if(this.disabled){ return false; } var li = this.container; li.addClass(this.activeClass); this.region = li.getRegion().adjust(2, 2, -2, -2); this.fireEvent("activate", this); return true; }, deactivate : function(){ this.container.removeClass(this.activeClass); this.fireEvent("deactivate", this); }, shouldDeactivate : function(e){ return !this.region || !this.region.contains(e.getPoint()); }, handleClick : function(e){ if(this.hideOnClick){ this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]); } }, expandMenu : function(autoActivate){ }, hideMenu : function(){ } }); Ext.menu.TextItem = function(text){ this.text = text; Ext.menu.TextItem.superclass.constructor.call(this); }; Ext.extend(Ext.menu.TextItem, Ext.menu.BaseItem, { hideOnClick : false, itemCls : "x-menu-text", onRender : function(){ var s = document.createElement("span"); s.className = this.itemCls; s.innerHTML = this.text; this.el = s; Ext.menu.TextItem.superclass.onRender.apply(this, arguments); } }); Ext.menu.Separator = function(config){ Ext.menu.Separator.superclass.constructor.call(this, config); }; Ext.extend(Ext.menu.Separator, Ext.menu.BaseItem, { itemCls : "x-menu-sep", hideOnClick : false, onRender : function(li){ var s = document.createElement("span"); s.className = this.itemCls; s.innerHTML = "&#160;"; this.el = s; li.addClass("x-menu-sep-li"); Ext.menu.Separator.superclass.onRender.apply(this, arguments); } }); Ext.menu.Item = function(config){ Ext.menu.Item.superclass.constructor.call(this, config); if(this.menu){ this.menu = Ext.menu.MenuMgr.get(this.menu); } }; Ext.extend(Ext.menu.Item, Ext.menu.BaseItem, { itemCls : "x-menu-item", canActivate : true, showDelay: 200, hideDelay: 200, ctype: "Ext.menu.Item", onRender : function(container, position){ var el = document.createElement("a"); el.hideFocus = true; el.unselectable = "on"; el.href = this.href || "#"; if(this.hrefTarget){ el.target = this.hrefTarget; } el.className = this.itemCls + (this.menu ? " x-menu-item-arrow" : "") + (this.cls ? " " + this.cls : ""); el.innerHTML = String.format( '<img src="{0}" class="x-menu-item-icon {2}" />{1}', this.icon || Ext.BLANK_IMAGE_URL, this.itemText||this.text, this.iconCls || ''); this.el = el; Ext.menu.Item.superclass.onRender.call(this, container, position); }, setText : function(text){ this.text = text; if(this.rendered){ this.el.update(String.format( '<img src="{0}" class="x-menu-item-icon {2}">{1}', this.icon || Ext.BLANK_IMAGE_URL, this.text, this.iconCls || '')); this.parentMenu.autoWidth(); } }, setIconClass : function(cls){ var oldCls = this.iconCls; this.iconCls = cls; if(this.rendered){ this.el.child('img.x-menu-item-icon').replaceClass(oldCls, this.iconCls); } }, handleClick : function(e){ if(!this.href){ e.stopEvent(); } Ext.menu.Item.superclass.handleClick.apply(this, arguments); }, activate : function(autoExpand){ if(Ext.menu.Item.superclass.activate.apply(this, arguments)){ this.focus(); if(autoExpand){ this.expandMenu(); } } return true; }, shouldDeactivate : function(e){ if(Ext.menu.Item.superclass.shouldDeactivate.call(this, e)){ if(this.menu && this.menu.isVisible()){ return !this.menu.getEl().getRegion().contains(e.getPoint()); } return true; } return false; }, deactivate : function(){ Ext.menu.Item.superclass.deactivate.apply(this, arguments); this.hideMenu(); }, expandMenu : function(autoActivate){ if(!this.disabled && this.menu){ clearTimeout(this.hideTimer); delete this.hideTimer; if(!this.menu.isVisible() && !this.showTimer){ this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]); }else if (this.menu.isVisible() && autoActivate){ this.menu.tryActivate(0, 1); } } }, deferExpand : function(autoActivate){ delete this.showTimer; this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu); if(autoActivate){ this.menu.tryActivate(0, 1); } }, hideMenu : function(){ clearTimeout(this.showTimer); delete this.showTimer; if(!this.hideTimer && this.menu && this.menu.isVisible()){ this.hideTimer = this.deferHide.defer(this.hideDelay, this); } }, deferHide : function(){ delete this.hideTimer; this.menu.hide(); } }); Ext.menu.CheckItem = function(config){ Ext.menu.CheckItem.superclass.constructor.call(this, config); this.addEvents( "beforecheckchange" , "checkchange" ); if(this.checkHandler){ this.on('checkchange', this.checkHandler, this.scope); } Ext.menu.MenuMgr.registerCheckable(this); }; Ext.extend(Ext.menu.CheckItem, Ext.menu.Item, { itemCls : "x-menu-item x-menu-check-item", groupClass : "x-menu-group-item", checked: false, ctype: "Ext.menu.CheckItem", onRender : function(c){ Ext.menu.CheckItem.superclass.onRender.apply(this, arguments); if(this.group){ this.el.addClass(this.groupClass); } if(this.checked){ this.checked = false; this.setChecked(true, true); } }, destroy : function(){ Ext.menu.MenuMgr.unregisterCheckable(this); Ext.menu.CheckItem.superclass.destroy.apply(this, arguments); }, setChecked : function(state, suppressEvent){ if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){ if(this.container){ this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked"); } this.checked = state; if(suppressEvent !== true){ this.fireEvent("checkchange", this, state); } } }, handleClick : function(e){ if(!this.disabled && !(this.checked && this.group)){ this.setChecked(!this.checked); } Ext.menu.CheckItem.superclass.handleClick.apply(this, arguments); } }); Ext.menu.Adapter = function(component, config){ Ext.menu.Adapter.superclass.constructor.call(this, config); this.component = component; }; Ext.extend(Ext.menu.Adapter, Ext.menu.BaseItem, { canActivate : true, onRender : function(container, position){ this.component.render(container); this.el = this.component.getEl(); }, activate : function(){ if(this.disabled){ return false; } this.component.focus(); this.fireEvent("activate", this); return true; }, deactivate : function(){ this.fireEvent("deactivate", this); }, disable : function(){ this.component.disable(); Ext.menu.Adapter.superclass.disable.call(this); }, enable : function(){ this.component.enable(); Ext.menu.Adapter.superclass.enable.call(this); } }); Ext.menu.DateItem = function(config){ Ext.menu.DateItem.superclass.constructor.call(this, new Ext.DatePicker(config), config); this.picker = this.component; this.addEvents('select'); this.picker.on("render", function(picker){ picker.getEl().swallowEvent("click"); picker.container.addClass("x-menu-date-item"); }); this.picker.on("select", this.onSelect, this); }; Ext.extend(Ext.menu.DateItem, Ext.menu.Adapter, { onSelect : function(picker, date){ this.fireEvent("select", this, date, picker); Ext.menu.DateItem.superclass.handleClick.call(this); } }); Ext.menu.ColorItem = function(config){ Ext.menu.ColorItem.superclass.constructor.call(this, new Ext.ColorPalette(config), config); this.palette = this.component; this.relayEvents(this.palette, ["select"]); if(this.selectHandler){ this.on('select', this.selectHandler, this.scope); } }; Ext.extend(Ext.menu.ColorItem, Ext.menu.Adapter); Ext.menu.DateMenu = function(config){ Ext.menu.DateMenu.superclass.constructor.call(this, config); this.plain = true; var di = new Ext.menu.DateItem(config); this.add(di); this.picker = di.picker; this.relayEvents(di, ["select"]); this.on('beforeshow', function(){ if(this.picker){ this.picker.hideMonthPicker(true); } }, this); }; Ext.extend(Ext.menu.DateMenu, Ext.menu.Menu, { cls:'x-date-menu', beforeDestroy : function() { this.picker.destroy(); } }); Ext.menu.ColorMenu = function(config){ Ext.menu.ColorMenu.superclass.constructor.call(this, config); this.plain = true; var ci = new Ext.menu.ColorItem(config); this.add(ci); this.palette = ci.palette; this.relayEvents(ci, ["select"]); }; Ext.extend(Ext.menu.ColorMenu, Ext.menu.Menu); Ext.form.Field = Ext.extend(Ext.BoxComponent, { invalidClass : "x-form-invalid", invalidText : "The value in this field is invalid", focusClass : "x-form-focus", validationEvent : "keyup", validateOnBlur : true, validationDelay : 250, defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "off"}, fieldClass : "x-form-field", msgTarget : 'qtip', msgFx : 'normal', readOnly : false, disabled : false, isFormField : true, hasFocus : false, initComponent : function(){ Ext.form.Field.superclass.initComponent.call(this); this.addEvents( 'focus', 'blur', 'specialkey', 'change', 'invalid', 'valid' ); }, getName: function(){ return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || ''); }, onRender : function(ct, position){ Ext.form.Field.superclass.onRender.call(this, ct, position); if(!this.el){ var cfg = this.getAutoCreate(); if(!cfg.name){ cfg.name = this.name || this.id; } if(this.inputType){ cfg.type = this.inputType; } this.el = ct.createChild(cfg, position); } var type = this.el.dom.type; if(type){ if(type == 'password'){ type = 'text'; } this.el.addClass('x-form-'+type); } if(this.readOnly){ this.el.dom.readOnly = true; } if(this.tabIndex !== undefined){ this.el.dom.setAttribute('tabIndex', this.tabIndex); } this.el.addClass([this.fieldClass, this.cls]); this.initValue(); }, initValue : function(){ if(this.value !== undefined){ this.setValue(this.value); }else if(this.el.dom.value.length > 0){ this.setValue(this.el.dom.value); } }, isDirty : function() { if(this.disabled) { return false; } return String(this.getValue()) !== String(this.originalValue); }, afterRender : function(){ Ext.form.Field.superclass.afterRender.call(this); this.initEvents(); }, fireKey : function(e){ if(e.isSpecialKey()){ this.fireEvent("specialkey", this, e); } }, reset : function(){ this.setValue(this.originalValue); this.clearInvalid(); }, initEvents : function(){ this.el.on(Ext.isIE ? "keydown" : "keypress", this.fireKey, this); this.el.on("focus", this.onFocus, this); this.el.on("blur", this.onBlur, this); this.originalValue = this.getValue(); }, onFocus : function(){ if(!Ext.isOpera && this.focusClass){ this.el.addClass(this.focusClass); } if(!this.hasFocus){ this.hasFocus = true; this.startValue = this.getValue(); this.fireEvent("focus", this); } }, beforeBlur : Ext.emptyFn, onBlur : function(){ this.beforeBlur(); if(!Ext.isOpera && this.focusClass){ this.el.removeClass(this.focusClass); } this.hasFocus = false; if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){ this.validate(); } var v = this.getValue(); if(String(v) !== String(this.startValue)){ this.fireEvent('change', this, v, this.startValue); } this.fireEvent("blur", this); }, isValid : function(preventMark){ if(this.disabled){ return true; } var restore = this.preventMark; this.preventMark = preventMark === true; var v = this.validateValue(this.processValue(this.getRawValue())); this.preventMark = restore; return v; }, validate : function(){ if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){ this.clearInvalid(); return true; } return false; }, processValue : function(value){ return value; }, validateValue : function(value){ return true; }, markInvalid : function(msg){ if(!this.rendered || this.preventMark){ return; } this.el.addClass(this.invalidClass); msg = msg || this.invalidText; switch(this.msgTarget){ case 'qtip': this.el.dom.qtip = msg; this.el.dom.qclass = 'x-form-invalid-tip'; if(Ext.QuickTips){ Ext.QuickTips.enable(); } break; case 'title': this.el.dom.title = msg; break; case 'under': if(!this.errorEl){ var elp = this.el.findParent('.x-form-element', 5, true); this.errorEl = elp.createChild({cls:'x-form-invalid-msg'}); this.errorEl.setWidth(elp.getWidth(true)-20); } this.errorEl.update(msg); Ext.form.Field.msgFx[this.msgFx].show(this.errorEl, this); break; case 'side': if(!this.errorIcon){ var elp = this.el.findParent('.x-form-element', 5, true); this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'}); } this.alignErrorIcon(); this.errorIcon.dom.qtip = msg; this.errorIcon.dom.qclass = 'x-form-invalid-tip'; this.errorIcon.show(); this.on('resize', this.alignErrorIcon, this); break; default: var t = Ext.getDom(this.msgTarget); t.innerHTML = msg; t.style.display = this.msgDisplay; break; } this.fireEvent('invalid', this, msg); }, alignErrorIcon : function(){ this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]); }, clearInvalid : function(){ if(!this.rendered || this.preventMark){ return; } this.el.removeClass(this.invalidClass); switch(this.msgTarget){ case 'qtip': this.el.dom.qtip = ''; break; case 'title': this.el.dom.title = ''; break; case 'under': if(this.errorEl){ Ext.form.Field.msgFx[this.msgFx].hide(this.errorEl, this); } break; case 'side': if(this.errorIcon){ this.errorIcon.dom.qtip = ''; this.errorIcon.hide(); this.un('resize', this.alignErrorIcon, this); } break; default: var t = Ext.getDom(this.msgTarget); t.innerHTML = ''; t.style.display = 'none'; break; } this.fireEvent('valid', this); }, getRawValue : function(){ var v = this.rendered ? this.el.getValue() : Ext.value(this.value, ''); if(v === this.emptyText){ v = ''; } return v; }, getValue : function(){ if(!this.rendered) { return this.value; } var v = this.el.getValue(); if(v === this.emptyText || v === undefined){ v = ''; } return v; }, setRawValue : function(v){ return this.el.dom.value = (v === null || v === undefined ? '' : v); }, setValue : function(v){ this.value = v; if(this.rendered){ this.el.dom.value = (v === null || v === undefined ? '' : v); this.validate(); } }, adjustSize : function(w, h){ var s = Ext.form.Field.superclass.adjustSize.call(this, w, h); s.width = this.adjustWidth(this.el.dom.tagName, s.width); return s; }, adjustWidth : function(tag, w){ tag = tag.toLowerCase(); if(typeof w == 'number' && !Ext.isSafari){ if(Ext.isIE && (tag == 'input' || tag == 'textarea')){ if(tag == 'input' && !Ext.isStrict){ return this.inEditor ? w : w - 3; } if(tag == 'input' && Ext.isStrict){ return w - (Ext.isIE6 ? 4 : 1); } if(tag = 'textarea' && Ext.isStrict){ return w-2; } }else if(Ext.isOpera && Ext.isStrict){ if(tag == 'input'){ return w + 2; } if(tag = 'textarea'){ return w-2; } } } return w; } }); Ext.form.Field.msgFx = { normal : { show: function(msgEl, f){ msgEl.setDisplayed('block'); }, hide : function(msgEl, f){ msgEl.setDisplayed(false).update(''); } }, slide : { show: function(msgEl, f){ msgEl.slideIn('t', {stopFx:true}); }, hide : function(msgEl, f){ msgEl.slideOut('t', {stopFx:true,useDisplay:true}); } }, slideRight : { show: function(msgEl, f){ msgEl.fixDisplay(); msgEl.alignTo(f.el, 'tl-tr'); msgEl.slideIn('l', {stopFx:true}); }, hide : function(msgEl, f){ msgEl.slideOut('l', {stopFx:true,useDisplay:true}); } } }; Ext.reg('field', Ext.form.Field); Ext.form.TextField = Ext.extend(Ext.form.Field, { grow : false, growMin : 30, growMax : 800, vtype : null, maskRe : null, disableKeyFilter : false, allowBlank : true, minLength : 0, maxLength : Number.MAX_VALUE, minLengthText : "The minimum length for this field is {0}", maxLengthText : "The maximum length for this field is {0}", selectOnFocus : false, blankText : "This field is required", validator : null, regex : null, regexText : "", emptyText : null, emptyClass : 'x-form-empty-field', initComponent : function(){ Ext.form.TextField.superclass.initComponent.call(this); this.addEvents( 'autosize' ); }, initEvents : function(){ Ext.form.TextField.superclass.initEvents.call(this); if(this.validationEvent == 'keyup'){ this.validationTask = new Ext.util.DelayedTask(this.validate, this); this.el.on('keyup', this.filterValidation, this); } else if(this.validationEvent !== false){ this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay}); } if(this.selectOnFocus || this.emptyText){ this.on("focus", this.preFocus, this); if(this.emptyText){ this.on('blur', this.postBlur, this); this.applyEmptyText(); } } if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Ext.form.VTypes[this.vtype+'Mask']))){ this.el.on("keypress", this.filterKeys, this); } if(this.grow){ this.el.on("keyup", this.onKeyUp, this, {buffer:50}); this.el.on("click", this.autoSize, this); } }, processValue : function(value){ if(this.stripCharsRe){ var newValue = value.replace(this.stripCharsRe, ''); if(newValue !== value){ this.setRawValue(newValue); return newValue; } } return value; }, filterValidation : function(e){ if(!e.isNavKeyPress()){ this.validationTask.delay(this.validationDelay); } }, onKeyUp : function(e){ if(!e.isNavKeyPress()){ this.autoSize(); } }, reset : function(){ Ext.form.TextField.superclass.reset.call(this); this.applyEmptyText(); }, applyEmptyText : function(){ if(this.rendered && this.emptyText && this.getRawValue().length < 1){ this.setRawValue(this.emptyText); this.el.addClass(this.emptyClass); } }, preFocus : function(){ if(this.emptyText){ if(this.el.dom.value == this.emptyText){ this.setRawValue(''); } this.el.removeClass(this.emptyClass); } if(this.selectOnFocus){ this.el.dom.select(); } }, postBlur : function(){ this.applyEmptyText(); }, filterKeys : function(e){ var k = e.getKey(); if(!Ext.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){ return; } var c = e.getCharCode(), cc = String.fromCharCode(c); if(Ext.isIE && (e.isSpecialKey() || !cc)){ return; } if(!this.maskRe.test(cc)){ e.stopEvent(); } }, setValue : function(v){ if(this.emptyText && this.el && v !== undefined && v !== null && v !== ''){ this.el.removeClass(this.emptyClass); } Ext.form.TextField.superclass.setValue.apply(this, arguments); this.applyEmptyText(); this.autoSize(); }, validateValue : function(value){ if(value.length < 1 || value === this.emptyText){ if(this.allowBlank){ this.clearInvalid(); return true; }else{ this.markInvalid(this.blankText); return false; } } if(value.length < this.minLength){ this.markInvalid(String.format(this.minLengthText, this.minLength)); return false; } if(value.length > this.maxLength){ this.markInvalid(String.format(this.maxLengthText, this.maxLength)); return false; } if(this.vtype){ var vt = Ext.form.VTypes; if(!vt[this.vtype](value, this)){ this.markInvalid(this.vtypeText || vt[this.vtype +'Text']); return false; } } if(typeof this.validator == "function"){ var msg = this.validator(value); if(msg !== true){ this.markInvalid(msg); return false; } } if(this.regex && !this.regex.test(value)){ this.markInvalid(this.regexText); return false; } return true; }, selectText : function(start, end){ var v = this.getRawValue(); if(v.length > 0){ start = start === undefined ? 0 : start; end = end === undefined ? v.length : end; var d = this.el.dom; if(d.setSelectionRange){ d.setSelectionRange(start, end); }else if(d.createTextRange){ var range = d.createTextRange(); range.moveStart("character", start); range.moveEnd("character", end-v.length); range.select(); } } }, autoSize : function(){ if(!this.grow || !this.rendered){ return; } if(!this.metrics){ this.metrics = Ext.util.TextMetrics.createInstance(this.el); } var el = this.el; var v = el.dom.value; var d = document.createElement('div'); d.appendChild(document.createTextNode(v)); v = d.innerHTML; d = null; v += "&#160;"; var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + 10, this.growMin)); this.el.setWidth(w); this.fireEvent("autosize", this, w); } }); Ext.reg('textfield', Ext.form.TextField); Ext.form.TriggerField = Ext.extend(Ext.form.TextField, { defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "off"}, hideTrigger:false, autoSize: Ext.emptyFn, monitorTab : true, deferHeight : true, mimicing : false, onResize : function(w, h){ Ext.form.TriggerField.superclass.onResize.call(this, w, h); if(typeof w == 'number'){ this.el.setWidth(this.adjustWidth('input', w - this.trigger.getWidth())); } this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth()); }, adjustSize : Ext.BoxComponent.prototype.adjustSize, getResizeEl : function(){ return this.wrap; }, getPositionEl : function(){ return this.wrap; }, alignErrorIcon : function(){ this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]); }, onRender : function(ct, position){ Ext.form.TriggerField.superclass.onRender.call(this, ct, position); this.wrap = this.el.wrap({cls: "x-form-field-wrap"}); this.trigger = this.wrap.createChild(this.triggerConfig || {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass}); if(this.hideTrigger){ this.trigger.setDisplayed(false); } this.initTrigger(); if(!this.width){ this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth()); } }, initTrigger : function(){ this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true}); this.trigger.addClassOnOver('x-form-trigger-over'); this.trigger.addClassOnClick('x-form-trigger-click'); }, onDestroy : function(){ if(this.trigger){ this.trigger.removeAllListeners(); this.trigger.remove(); } if(this.wrap){ this.wrap.remove(); } Ext.form.TriggerField.superclass.onDestroy.call(this); }, onFocus : function(){ Ext.form.TriggerField.superclass.onFocus.call(this); if(!this.mimicing){ this.wrap.addClass('x-trigger-wrap-focus'); this.mimicing = true; Ext.get(Ext.isIE ? document.body : document).on("mousedown", this.mimicBlur, this, {delay: 10}); if(this.monitorTab){ this.el.on("keydown", this.checkTab, this); } } }, checkTab : function(e){ if(e.getKey() == e.TAB){ this.triggerBlur(); } }, onBlur : function(){ }, mimicBlur : function(e){ if(!this.wrap.contains(e.target) && this.validateBlur(e)){ this.triggerBlur(); } }, triggerBlur : function(){ this.mimicing = false; Ext.get(Ext.isIE ? document.body : document).un("mousedown", this.mimicBlur); if(this.monitorTab){ this.el.un("keydown", this.checkTab, this); } this.beforeBlur(); this.wrap.removeClass('x-trigger-wrap-focus'); Ext.form.TriggerField.superclass.onBlur.call(this); }, beforeBlur : Ext.emptyFn, validateBlur : function(e){ return true; }, onDisable : function(){ Ext.form.TriggerField.superclass.onDisable.call(this); if(this.wrap){ this.wrap.addClass('x-item-disabled'); } }, onEnable : function(){ Ext.form.TriggerField.superclass.onEnable.call(this); if(this.wrap){ this.wrap.removeClass('x-item-disabled'); } }, onShow : function(){ if(this.wrap){ this.wrap.dom.style.display = ''; this.wrap.dom.style.visibility = 'visible'; } }, onHide : function(){ this.wrap.dom.style.display = 'none'; }, onTriggerClick : Ext.emptyFn }); Ext.form.TwinTriggerField = Ext.extend(Ext.form.TriggerField, { initComponent : function(){ Ext.form.TwinTriggerField.superclass.initComponent.call(this); this.triggerConfig = { tag:'span', cls:'x-form-twin-triggers', cn:[ {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class}, {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class} ]}; }, getTrigger : function(index){ return this.triggers[index]; }, initTrigger : function(){ var ts = this.trigger.select('.x-form-trigger', true); this.wrap.setStyle('overflow', 'hidden'); var triggerField = this; ts.each(function(t, all, index){ t.hide = function(){ var w = triggerField.wrap.getWidth(); this.dom.style.display = 'none'; triggerField.el.setWidth(w-triggerField.trigger.getWidth()); }; t.show = function(){ var w = triggerField.wrap.getWidth(); this.dom.style.display = ''; triggerField.el.setWidth(w-triggerField.trigger.getWidth()); }; var triggerIndex = 'Trigger'+(index+1); if(this['hide'+triggerIndex]){ t.dom.style.display = 'none'; } t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true}); t.addClassOnOver('x-form-trigger-over'); t.addClassOnClick('x-form-trigger-click'); }, this); this.triggers = ts.elements; }, onTrigger1Click : Ext.emptyFn, onTrigger2Click : Ext.emptyFn }); Ext.reg('trigger', Ext.form.TriggerField); Ext.form.TextArea = Ext.extend(Ext.form.TextField, { growMin : 60, growMax: 1000, growAppend : '&#160;\n&#160;', growPad : 0, enterIsSpecial : false, preventScrollbars: false, onRender : function(ct, position){ if(!this.el){ this.defaultAutoCreate = { tag: "textarea", style:"width:100px;height:60px;", autocomplete: "off" }; } Ext.form.TextArea.superclass.onRender.call(this, ct, position); if(this.grow){ this.textSizeEl = Ext.DomHelper.append(document.body, { tag: "pre", cls: "x-form-grow-sizer" }); if(this.preventScrollbars){ this.el.setStyle("overflow", "hidden"); } this.el.setHeight(this.growMin); } }, onDestroy : function(){ if(this.textSizeEl){ Ext.removeNode(this.textSizeEl); } Ext.form.TextArea.superclass.onDestroy.call(this); }, fireKey : function(e){ if(e.isSpecialKey() && (this.enterIsSpecial || (e.getKey() != e.ENTER || e.hasModifier()))){ this.fireEvent("specialkey", this, e); } }, onKeyUp : function(e){ if(!e.isNavKeyPress() || e.getKey() == e.ENTER){ this.autoSize(); } }, autoSize : function(){ if(!this.grow || !this.textSizeEl){ return; } var el = this.el; var v = el.dom.value; var ts = this.textSizeEl; ts.innerHTML = ''; ts.appendChild(document.createTextNode(v)); v = ts.innerHTML; Ext.fly(ts).setWidth(this.el.getWidth()); if(v.length < 1){ v = "&#160;&#160;"; }else{ if(Ext.isIE){ v = v.replace(/\n/g, '<p>&#160;</p>'); } v += this.growAppend; } ts.innerHTML = v; var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin)+this.growPad); if(h != this.lastHeight){ this.lastHeight = h; this.el.setHeight(h); this.fireEvent("autosize", this, h); } } }); Ext.reg('textarea', Ext.form.TextArea); Ext.form.NumberField = Ext.extend(Ext.form.TextField, { fieldClass: "x-form-field x-form-num-field", allowDecimals : true, decimalSeparator : ".", decimalPrecision : 2, allowNegative : true, minValue : Number.NEGATIVE_INFINITY, maxValue : Number.MAX_VALUE, minText : "The minimum value for this field is {0}", maxText : "The maximum value for this field is {0}", nanText : "{0} is not a valid number", baseChars : "0123456789", initEvents : function(){ Ext.form.NumberField.superclass.initEvents.call(this); var allowed = this.baseChars+''; if(this.allowDecimals){ allowed += this.decimalSeparator; } if(this.allowNegative){ allowed += "-"; } this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi'); var keyPress = function(e){ var k = e.getKey(); if(!Ext.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){ return; } var c = e.getCharCode(); if(allowed.indexOf(String.fromCharCode(c)) === -1){ e.stopEvent(); } }; this.el.on("keypress", keyPress, this); }, validateValue : function(value){ if(!Ext.form.NumberField.superclass.validateValue.call(this, value)){ return false; } if(value.length < 1){ return true; } value = String(value).replace(this.decimalSeparator, "."); if(isNaN(value)){ this.markInvalid(String.format(this.nanText, value)); return false; } var num = this.parseValue(value); if(num < this.minValue){ this.markInvalid(String.format(this.minText, this.minValue)); return false; } if(num > this.maxValue){ this.markInvalid(String.format(this.maxText, this.maxValue)); return false; } return true; }, getValue : function(){ return this.fixPrecision(this.parseValue(Ext.form.NumberField.superclass.getValue.call(this))); }, setValue : function(v){ v = parseFloat(v); v = isNaN(v) ? '' : String(v).replace(".", this.decimalSeparator); Ext.form.NumberField.superclass.setValue.call(this, v); }, parseValue : function(value){ value = parseFloat(String(value).replace(this.decimalSeparator, ".")); return isNaN(value) ? '' : value; }, fixPrecision : function(value){ var nan = isNaN(value); if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){ return nan ? '' : value; } return parseFloat(parseFloat(value).toFixed(this.decimalPrecision)); }, beforeBlur : function(){ var v = this.parseValue(this.getRawValue()); if(v){ this.setValue(this.fixPrecision(v)); } } }); Ext.reg('numberfield', Ext.form.NumberField); Ext.form.DateField = Ext.extend(Ext.form.TriggerField, { format : "m/d/y", altFormats : "m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d", disabledDays : null, disabledDaysText : "Disabled", disabledDates : null, disabledDatesText : "Disabled", minValue : null, maxValue : null, minText : "The date in this field must be equal to or after {0}", maxText : "The date in this field must be equal to or before {0}", invalidText : "{0} is not a valid date - it must be in the format {1}", triggerClass : 'x-form-date-trigger', defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"}, initComponent : function(){ Ext.form.DateField.superclass.initComponent.call(this); if(typeof this.minValue == "string"){ this.minValue = this.parseDate(this.minValue); } if(typeof this.maxValue == "string"){ this.maxValue = this.parseDate(this.maxValue); } this.ddMatch = null; if(this.disabledDates){ var dd = this.disabledDates; var re = "(?:"; for(var i = 0; i < dd.length; i++){ re += dd[i]; if(i != dd.length-1) re += "|"; } this.ddMatch = new RegExp(re + ")"); } }, validateValue : function(value){ value = this.formatDate(value); if(!Ext.form.DateField.superclass.validateValue.call(this, value)){ return false; } if(value.length < 1){ return true; } var svalue = value; value = this.parseDate(value); if(!value){ this.markInvalid(String.format(this.invalidText, svalue, this.format)); return false; } var time = value.getTime(); if(this.minValue && time < this.minValue.getTime()){ this.markInvalid(String.format(this.minText, this.formatDate(this.minValue))); return false; } if(this.maxValue && time > this.maxValue.getTime()){ this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue))); return false; } if(this.disabledDays){ var day = value.getDay(); for(var i = 0; i < this.disabledDays.length; i++) { if(day === this.disabledDays[i]){ this.markInvalid(this.disabledDaysText); return false; } } } var fvalue = this.formatDate(value); if(this.ddMatch && this.ddMatch.test(fvalue)){ this.markInvalid(String.format(this.disabledDatesText, fvalue)); return false; } return true; }, validateBlur : function(){ return !this.menu || !this.menu.isVisible(); }, getValue : function(){ return this.parseDate(Ext.form.DateField.superclass.getValue.call(this)) || ""; }, setValue : function(date){ Ext.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date))); }, parseDate : function(value){ if(!value || Ext.isDate(value)){ return value; } var v = Date.parseDate(value, this.format); if(!v && this.altFormats){ if(!this.altFormatsArray){ this.altFormatsArray = this.altFormats.split("|"); } for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){ v = Date.parseDate(value, this.altFormatsArray[i]); } } return v; }, onDestroy : function(){ if(this.menu) { this.menu.destroy(); } if(this.wrap){ this.wrap.remove(); } Ext.form.DateField.superclass.onDestroy.call(this); }, formatDate : function(date){ return Ext.isDate(date) ? date.dateFormat(this.format) : date; }, menuListeners : { select: function(m, d){ this.setValue(d); }, show : function(){ this.onFocus(); }, hide : function(){ this.focus.defer(10, this); var ml = this.menuListeners; this.menu.un("select", ml.select, this); this.menu.un("show", ml.show, this); this.menu.un("hide", ml.hide, this); } }, onTriggerClick : function(){ if(this.disabled){ return; } if(this.menu == null){ this.menu = new Ext.menu.DateMenu(); } Ext.apply(this.menu.picker, { minDate : this.minValue, maxDate : this.maxValue, disabledDatesRE : this.ddMatch, disabledDatesText : this.disabledDatesText, disabledDays : this.disabledDays, disabledDaysText : this.disabledDaysText, format : this.format, minText : String.format(this.minText, this.formatDate(this.minValue)), maxText : String.format(this.maxText, this.formatDate(this.maxValue)) }); this.menu.on(Ext.apply({}, this.menuListeners, { scope:this })); this.menu.picker.setValue(this.getValue() || new Date()); this.menu.show(this.el, "tl-bl?"); }, beforeBlur : function(){ var v = this.parseDate(this.getRawValue()); if(v){ this.setValue(v); } } }); Ext.reg('datefield', Ext.form.DateField); Ext.form.ComboBox = Ext.extend(Ext.form.TriggerField, { defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"}, listClass: '', selectedClass: 'x-combo-selected', triggerClass : 'x-form-arrow-trigger', shadow:'sides', listAlign: 'tl-bl?', maxHeight: 300, minHeight: 90, triggerAction: 'query', minChars : 4, typeAhead: false, queryDelay: 500, pageSize: 0, selectOnFocus:false, queryParam: 'query', loadingText: 'Loading...', resizable: false, handleHeight : 8, editable: true, allQuery: '', mode: 'remote', minListWidth : 70, forceSelection:false, typeAheadDelay : 250, lazyInit : true, initComponent : function(){ Ext.form.ComboBox.superclass.initComponent.call(this); this.addEvents( 'expand', 'collapse', 'beforeselect', 'select', 'beforequery' ); if(this.transform){ this.allowDomMove = false; var s = Ext.getDom(this.transform); if(!this.hiddenName){ this.hiddenName = s.name; } if(!this.store){ this.mode = 'local'; var d = [], opts = s.options; for(var i = 0, len = opts.length;i < len; i++){ var o = opts[i]; var value = (Ext.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text; if(o.selected) { this.value = value; } d.push([value, o.text]); } this.store = new Ext.data.SimpleStore({ 'id': 0, fields: ['value', 'text'], data : d }); this.valueField = 'value'; this.displayField = 'text'; } s.name = Ext.id(); if(!this.lazyRender){ this.target = true; this.el = Ext.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate); Ext.removeNode(s); this.render(this.el.parentNode); }else{ Ext.removeNode(s); } } this.selectedIndex = -1; if(this.mode == 'local'){ if(this.initialConfig.queryDelay === undefined){ this.queryDelay = 10; } if(this.initialConfig.minChars === undefined){ this.minChars = 0; } } }, onRender : function(ct, position){ Ext.form.ComboBox.superclass.onRender.call(this, ct, position); if(this.hiddenName){ this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)}, 'before', true); this.hiddenField.value = this.hiddenValue !== undefined ? this.hiddenValue : this.value !== undefined ? this.value : ''; this.el.dom.removeAttribute('name'); } if(Ext.isGecko){ this.el.dom.setAttribute('autocomplete', 'off'); } if(!this.lazyInit){ this.initList(); }else{ this.on('focus', this.initList, this, {single: true}); } if(!this.editable){ this.editable = true; this.setEditable(false); } }, initList : function(){ if(!this.list){ var cls = 'x-combo-list'; this.list = new Ext.Layer({ shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false }); var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth); this.list.setWidth(lw); this.list.swallowEvent('mousewheel'); this.assetHeight = 0; if(this.title){ this.header = this.list.createChild({cls:cls+'-hd', html: this.title}); this.assetHeight += this.header.getHeight(); } this.innerList = this.list.createChild({cls:cls+'-inner'}); this.innerList.on('mouseover', this.onViewOver, this); this.innerList.on('mousemove', this.onViewMove, this); this.innerList.setWidth(lw - this.list.getFrameWidth('lr')); if(this.pageSize){ this.footer = this.list.createChild({cls:cls+'-ft'}); this.pageTb = new Ext.PagingToolbar({ store:this.store, pageSize: this.pageSize, renderTo:this.footer }); this.assetHeight += this.footer.getHeight(); } if(!this.tpl){ this.tpl = '<tpl for="."><div class="'+cls+'-item">{' + this.displayField + '}</div></tpl>'; } this.view = new Ext.DataView({ applyTo: this.innerList, tpl: this.tpl, singleSelect: true, selectedClass: this.selectedClass, itemSelector: this.itemSelector || '.' + cls + '-item' }); this.view.on('click', this.onViewClick, this); this.bindStore(this.store, true); if(this.resizable){ this.resizer = new Ext.Resizable(this.list, { pinned:true, handles:'se' }); this.resizer.on('resize', function(r, w, h){ this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight; this.listWidth = w; this.innerList.setWidth(w - this.list.getFrameWidth('lr')); this.restrictHeight(); }, this); this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px'); } } }, bindStore : function(store, initial){ if(this.store && !initial){ this.store.un('beforeload', this.onBeforeLoad, this); this.store.un('load', this.onLoad, this); this.store.un('loadexception', this.collapse, this); if(!store){ this.store = null; if(this.view){ this.view.setStore(null); } } } if(store){ this.store = Ext.StoreMgr.lookup(store); this.store.on('beforeload', this.onBeforeLoad, this); this.store.on('load', this.onLoad, this); this.store.on('loadexception', this.collapse, this); if(this.view){ this.view.setStore(store); } } }, initEvents : function(){ Ext.form.ComboBox.superclass.initEvents.call(this); this.keyNav = new Ext.KeyNav(this.el, { "up" : function(e){ this.inKeyMode = true; this.selectPrev(); }, "down" : function(e){ if(!this.isExpanded()){ this.onTriggerClick(); }else{ this.inKeyMode = true; this.selectNext(); } }, "enter" : function(e){ this.onViewClick(); this.delayedCheck = true; this.unsetDelayCheck.defer(10, this); }, "esc" : function(e){ this.collapse(); }, "tab" : function(e){ this.onViewClick(false); return true; }, scope : this, doRelay : function(foo, bar, hname){ if(hname == 'down' || this.scope.isExpanded()){ return Ext.KeyNav.prototype.doRelay.apply(this, arguments); } return true; }, forceKeyDown : true }); this.queryDelay = Math.max(this.queryDelay || 10, this.mode == 'local' ? 10 : 250); this.dqTask = new Ext.util.DelayedTask(this.initQuery, this); if(this.typeAhead){ this.taTask = new Ext.util.DelayedTask(this.onTypeAhead, this); } if(this.editable !== false){ this.el.on("keyup", this.onKeyUp, this); } if(this.forceSelection){ this.on('blur', this.doForce, this); } }, onDestroy : function(){ if(this.view){ this.view.el.removeAllListeners(); this.view.el.remove(); this.view.purgeListeners(); } if(this.list){ this.list.destroy(); } this.bindStore(null); Ext.form.ComboBox.superclass.onDestroy.call(this); }, unsetDelayCheck : function(){ delete this.delayedCheck; }, fireKey : function(e){ if(e.isNavKeyPress() && !this.isExpanded() && !this.delayedCheck){ this.fireEvent("specialkey", this, e); } }, onResize: function(w, h){ Ext.form.ComboBox.superclass.onResize.apply(this, arguments); if(this.list && this.listWidth === undefined){ var lw = Math.max(w, this.minListWidth); this.list.setWidth(lw); this.innerList.setWidth(lw - this.list.getFrameWidth('lr')); } }, onEnable: function(){ Ext.form.ComboBox.superclass.onEnable.apply(this, arguments); if(this.hiddenField){ this.hiddenField.disabled = false; } }, onDisable: function(){ Ext.form.ComboBox.superclass.onDisable.apply(this, arguments); if(this.hiddenField){ this.hiddenField.disabled = true; } }, setEditable : function(value){ if(value == this.editable){ return; } this.editable = value; if(!value){ this.el.dom.setAttribute('readOnly', true); this.el.on('mousedown', this.onTriggerClick, this); this.el.addClass('x-combo-noedit'); }else{ this.el.dom.setAttribute('readOnly', false); this.el.un('mousedown', this.onTriggerClick, this); this.el.removeClass('x-combo-noedit'); } }, onBeforeLoad : function(){ if(!this.hasFocus){ return; } this.innerList.update(this.loadingText ? '<div class="loading-indicator">'+this.loadingText+'</div>' : ''); this.restrictHeight(); this.selectedIndex = -1; }, onLoad : function(){ if(!this.hasFocus){ return; } if(this.store.getCount() > 0){ this.expand(); this.restrictHeight(); if(this.lastQuery == this.allQuery){ if(this.editable){ this.el.dom.select(); } if(!this.selectByValue(this.value, true)){ this.select(0, true); } }else{ this.selectNext(); if(this.typeAhead && this.lastKey != Ext.EventObject.BACKSPACE && this.lastKey != Ext.EventObject.DELETE){ this.taTask.delay(this.typeAheadDelay); } } }else{ this.onEmptyResults(); } }, onTypeAhead : function(){ if(this.store.getCount() > 0){ var r = this.store.getAt(0); var newValue = r.data[this.displayField]; var len = newValue.length; var selStart = this.getRawValue().length; if(selStart != len){ this.setRawValue(newValue); this.selectText(selStart, newValue.length); } } }, onSelect : function(record, index){ if(this.fireEvent('beforeselect', this, record, index) !== false){ this.setValue(record.data[this.valueField || this.displayField]); this.collapse(); this.fireEvent('select', this, record, index); } }, getValue : function(){ if(this.valueField){ return typeof this.value != 'undefined' ? this.value : ''; }else{ return Ext.form.ComboBox.superclass.getValue.call(this); } }, clearValue : function(){ if(this.hiddenField){ this.hiddenField.value = ''; } this.setRawValue(''); this.lastSelectionText = ''; this.applyEmptyText(); this.value = ''; }, setValue : function(v){ var text = v; if(this.valueField){ var r = this.findRecord(this.valueField, v); if(r){ text = r.data[this.displayField]; }else if(this.valueNotFoundText !== undefined){ text = this.valueNotFoundText; } } this.lastSelectionText = text; if(this.hiddenField){ this.hiddenField.value = v; } Ext.form.ComboBox.superclass.setValue.call(this, text); this.value = v; }, findRecord : function(prop, value){ var record; if(this.store.getCount() > 0){ this.store.each(function(r){ if(r.data[prop] == value){ record = r; return false; } }); } return record; }, onViewMove : function(e, t){ this.inKeyMode = false; }, onViewOver : function(e, t){ if(this.inKeyMode){ return; } var item = this.view.findItemFromChild(t); if(item){ var index = this.view.indexOf(item); this.select(index, false); } }, onViewClick : function(doFocus){ var index = this.view.getSelectedIndexes()[0]; var r = this.store.getAt(index); if(r){ this.onSelect(r, index); } if(doFocus !== false){ this.el.focus(); } }, restrictHeight : function(){ this.innerList.dom.style.height = ''; var inner = this.innerList.dom; var pad = this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight; var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight); var ha = this.getPosition()[1]-Ext.getBody().getScroll().top; var hb = Ext.lib.Dom.getViewHeight()-ha-this.getSize().height; var space = Math.max(ha, hb, this.minHeight || 0)-this.list.shadow.offset-pad-2; h = Math.min(h, space, this.maxHeight); this.innerList.setHeight(h); this.list.beginUpdate(); this.list.setHeight(h+pad); this.list.alignTo(this.el, this.listAlign); this.list.endUpdate(); }, onEmptyResults : function(){ this.collapse(); }, isExpanded : function(){ return this.list && this.list.isVisible(); }, selectByValue : function(v, scrollIntoView){ if(v !== undefined && v !== null){ var r = this.findRecord(this.valueField || this.displayField, v); if(r){ this.select(this.store.indexOf(r), scrollIntoView); return true; } } return false; }, select : function(index, scrollIntoView){ this.selectedIndex = index; this.view.select(index); if(scrollIntoView !== false){ var el = this.view.getNode(index); if(el){ this.innerList.scrollChildIntoView(el, false); } } }, selectNext : function(){ var ct = this.store.getCount(); if(ct > 0){ if(this.selectedIndex == -1){ this.select(0); }else if(this.selectedIndex < ct-1){ this.select(this.selectedIndex+1); } } }, selectPrev : function(){ var ct = this.store.getCount(); if(ct > 0){ if(this.selectedIndex == -1){ this.select(0); }else if(this.selectedIndex != 0){ this.select(this.selectedIndex-1); } } }, onKeyUp : function(e){ if(this.editable !== false && !e.isSpecialKey()){ this.lastKey = e.getKey(); this.dqTask.delay(this.queryDelay); } }, validateBlur : function(){ return !this.list || !this.list.isVisible(); }, initQuery : function(){ this.doQuery(this.getRawValue()); }, doForce : function(){ if(this.el.dom.value.length > 0){ this.el.dom.value = this.lastSelectionText === undefined ? '' : this.lastSelectionText; this.applyEmptyText(); } }, doQuery : function(q, forceAll){ if(q === undefined || q === null){ q = ''; } var qe = { query: q, forceAll: forceAll, combo: this, cancel:false }; if(this.fireEvent('beforequery', qe)===false || qe.cancel){ return false; } q = qe.query; forceAll = qe.forceAll; if(forceAll === true || (q.length >= this.minChars)){ if(this.lastQuery !== q){ this.lastQuery = q; if(this.mode == 'local'){ this.selectedIndex = -1; if(forceAll){ this.store.clearFilter(); }else{ this.store.filter(this.displayField, q); } this.onLoad(); }else{ this.store.baseParams[this.queryParam] = q; this.store.load({ params: this.getParams(q) }); this.expand(); } }else{ this.selectedIndex = -1; this.onLoad(); } } }, getParams : function(q){ var p = {}; if(this.pageSize){ p.start = 0; p.limit = this.pageSize; } return p; }, collapse : function(){ if(!this.isExpanded()){ return; } this.list.hide(); Ext.getDoc().un('mousewheel', this.collapseIf, this); Ext.getDoc().un('mousedown', this.collapseIf, this); this.fireEvent('collapse', this); }, collapseIf : function(e){ if(!e.within(this.wrap) && !e.within(this.list)){ this.collapse(); } }, expand : function(){ if(this.isExpanded() || !this.hasFocus){ return; } this.list.alignTo(this.wrap, this.listAlign); this.list.show(); this.innerList.setOverflow('auto'); Ext.getDoc().on('mousewheel', this.collapseIf, this); Ext.getDoc().on('mousedown', this.collapseIf, this); this.fireEvent('expand', this); }, onTriggerClick : function(){ if(this.disabled){ return; } if(this.isExpanded()){ this.collapse(); this.el.focus(); }else { this.onFocus({}); if(this.triggerAction == 'all') { this.doQuery(this.allQuery, true); } else { this.doQuery(this.getRawValue()); } this.el.focus(); } } }); Ext.reg('combo', Ext.form.ComboBox); Ext.form.Checkbox = Ext.extend(Ext.form.Field, { focusClass : undefined, fieldClass: "x-form-field", checked: false, defaultAutoCreate : { tag: "input", type: 'checkbox', autocomplete: "off"}, initComponent : function(){ Ext.form.Checkbox.superclass.initComponent.call(this); this.addEvents( 'check' ); }, onResize : function(){ Ext.form.Checkbox.superclass.onResize.apply(this, arguments); if(!this.boxLabel){ this.el.alignTo(this.wrap, 'c-c'); } }, initEvents : function(){ Ext.form.Checkbox.superclass.initEvents.call(this); this.el.on("click", this.onClick, this); this.el.on("change", this.onClick, this); }, getResizeEl : function(){ return this.wrap; }, getPositionEl : function(){ return this.wrap; }, markInvalid : Ext.emptyFn, clearInvalid : Ext.emptyFn, onRender : function(ct, position){ Ext.form.Checkbox.superclass.onRender.call(this, ct, position); if(this.inputValue !== undefined){ this.el.dom.value = this.inputValue; } this.wrap = this.el.wrap({cls: "x-form-check-wrap"}); if(this.boxLabel){ this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel}); } if(this.checked){ this.setValue(true); }else{ this.checked = this.el.dom.checked; } }, onDestroy : function(){ if(this.wrap){ this.wrap.remove(); } Ext.form.Checkbox.superclass.onDestroy.call(this); }, initValue : Ext.emptyFn, getValue : function(){ if(this.rendered){ return this.el.dom.checked; } return false; }, onClick : function(){ if(this.el.dom.checked != this.checked){ this.setValue(this.el.dom.checked); } }, setValue : function(v){ this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on'); if(this.el && this.el.dom){ this.el.dom.checked = this.checked; this.el.dom.defaultChecked = this.checked; } this.fireEvent("check", this, this.checked); } }); Ext.reg('checkbox', Ext.form.Checkbox); Ext.form.Radio = Ext.extend(Ext.form.Checkbox, { inputType: 'radio', markInvalid : Ext.emptyFn, clearInvalid : Ext.emptyFn, getGroupValue : function(){ var p = this.el.up('form') || Ext.getBody(); var c = p.child('input[name='+this.el.dom.name+']:checked', true); return c ? c.value : null; }, onClick : function(){ if(this.el.dom.checked != this.checked){ var p = this.el.up('form') || Ext.getBody(); var els = p.select('input[name='+this.el.dom.name+']'); els.each(function(el){ if(el.dom.id == this.id){ this.setValue(true); }else{ Ext.getCmp(el.dom.id).setValue(false); } }, this); } }, setValue : function(v){ if (typeof v == 'boolean') { Ext.form.Radio.superclass.setValue.call(this, v); } else { var r = this.el.up('form').child('input[name='+this.el.dom.name+'][value='+v+']', true); if (r){ r.checked = true; }; } } }); Ext.reg('radio', Ext.form.Radio); Ext.form.Hidden = Ext.extend(Ext.form.Field, { inputType : 'hidden', onRender : function(){ Ext.form.Hidden.superclass.onRender.apply(this, arguments); }, initEvents : function(){ this.originalValue = this.getValue(); }, setSize : Ext.emptyFn, setWidth : Ext.emptyFn, setHeight : Ext.emptyFn, setPosition : Ext.emptyFn, setPagePosition : Ext.emptyFn, markInvalid : Ext.emptyFn, clearInvalid : Ext.emptyFn }); Ext.reg('hidden', Ext.form.Hidden); Ext.form.BasicForm = function(el, config){ Ext.apply(this, config); this.items = new Ext.util.MixedCollection(false, function(o){ return o.id || (o.id = Ext.id()); }); this.addEvents( 'beforeaction', 'actionfailed', 'actioncomplete' ); if(el){ this.initEl(el); } Ext.form.BasicForm.superclass.constructor.call(this); }; Ext.extend(Ext.form.BasicForm, Ext.util.Observable, { timeout: 30, activeAction : null, trackResetOnLoad : false, initEl : function(el){ this.el = Ext.get(el); this.id = this.el.id || Ext.id(); if(!this.standardSubmit){ this.el.on('submit', this.onSubmit, this); } this.el.addClass('x-form'); }, getEl: function(){ return this.el; }, onSubmit : function(e){ e.stopEvent(); }, destroy: function() { this.items.each(function(f){ Ext.destroy(f); }); if(this.el){ this.el.removeAllListeners(); this.el.remove(); } this.purgeListeners(); }, isValid : function(){ var valid = true; this.items.each(function(f){ if(!f.validate()){ valid = false; } }); return valid; }, isDirty : function(){ var dirty = false; this.items.each(function(f){ if(f.isDirty()){ dirty = true; return false; } }); return dirty; }, doAction : function(action, options){ if(typeof action == 'string'){ action = new Ext.form.Action.ACTION_TYPES[action](this, options); } if(this.fireEvent('beforeaction', this, action) !== false){ this.beforeAction(action); action.run.defer(100, action); } return this; }, submit : function(options){ if(this.standardSubmit){ var v = this.isValid(); if(v){ this.el.dom.submit(); } return v; } this.doAction('submit', options); return this; }, load : function(options){ this.doAction('load', options); return this; }, updateRecord : function(record){ record.beginEdit(); var fs = record.fields; fs.each(function(f){ var field = this.findField(f.name); if(field){ record.set(f.name, field.getValue()); } }, this); record.endEdit(); return this; }, loadRecord : function(record){ this.setValues(record.data); return this; }, beforeAction : function(action){ var o = action.options; if(o.waitMsg){ if(this.waitMsgTarget === true){ this.el.mask(o.waitMsg, 'x-mask-loading'); }else if(this.waitMsgTarget){ this.waitMsgTarget = Ext.get(this.waitMsgTarget); this.waitMsgTarget.mask(o.waitMsg, 'x-mask-loading'); }else{ Ext.MessageBox.wait(o.waitMsg, o.waitTitle || this.waitTitle || 'Please Wait...'); } } }, afterAction : function(action, success){ this.activeAction = null; var o = action.options; if(o.waitMsg){ if(this.waitMsgTarget === true){ this.el.unmask(); }else if(this.waitMsgTarget){ this.waitMsgTarget.unmask(); }else{ Ext.MessageBox.updateProgress(1); Ext.MessageBox.hide(); } } if(success){ if(o.reset){ this.reset(); } Ext.callback(o.success, o.scope, [this, action]); this.fireEvent('actioncomplete', this, action); }else{ Ext.callback(o.failure, o.scope, [this, action]); this.fireEvent('actionfailed', this, action); } }, findField : function(id){ var field = this.items.get(id); if(!field){ this.items.each(function(f){ if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){ field = f; return false; } }); } return field || null; }, markInvalid : function(errors){ if(Ext.isArray(errors)){ for(var i = 0, len = errors.length; i < len; i++){ var fieldError = errors[i]; var f = this.findField(fieldError.id); if(f){ f.markInvalid(fieldError.msg); } } }else{ var field, id; for(id in errors){ if(typeof errors[id] != 'function' && (field = this.findField(id))){ field.markInvalid(errors[id]); } } } return this; }, setValues : function(values){ if(Ext.isArray(values)){ for(var i = 0, len = values.length; i < len; i++){ var v = values[i]; var f = this.findField(v.id); if(f){ f.setValue(v.value); if(this.trackResetOnLoad){ f.originalValue = f.getValue(); } } } }else{ var field, id; for(id in values){ if(typeof values[id] != 'function' && (field = this.findField(id))){ field.setValue(values[id]); if(this.trackResetOnLoad){ field.originalValue = field.getValue(); } } } } return this; }, getValues : function(asString){ var fs = Ext.lib.Ajax.serializeForm(this.el.dom); if(asString === true){ return fs; } return Ext.urlDecode(fs); }, clearInvalid : function(){ this.items.each(function(f){ f.clearInvalid(); }); return this; }, reset : function(){ this.items.each(function(f){ f.reset(); }); return this; }, add : function(){ this.items.addAll(Array.prototype.slice.call(arguments, 0)); return this; }, remove : function(field){ this.items.remove(field); return this; }, render : function(){ this.items.each(function(f){ if(f.isFormField && !f.rendered && document.getElementById(f.id)){ f.applyToMarkup(f.id); } }); return this; }, applyToFields : function(o){ this.items.each(function(f){ Ext.apply(f, o); }); return this; }, applyIfToFields : function(o){ this.items.each(function(f){ Ext.applyIf(f, o); }); return this; } }); Ext.BasicForm = Ext.form.BasicForm; Ext.FormPanel = Ext.extend(Ext.Panel, { buttonAlign:'center', minButtonWidth:75, labelAlign:'left', monitorValid : false, monitorPoll : 200, layout: 'form', initComponent :function(){ this.form = this.createForm(); Ext.FormPanel.superclass.initComponent.call(this); this.addEvents( 'clientvalidation' ); this.relayEvents(this.form, ['beforeaction', 'actionfailed', 'actioncomplete']); }, createForm: function(){ delete this.initialConfig.listeners; return new Ext.form.BasicForm(null, this.initialConfig); }, initFields : function(){ var f = this.form; var formPanel = this; var fn = function(c){ if(c.doLayout && c != formPanel){ Ext.applyIf(c, { labelAlign: c.ownerCt.labelAlign, labelWidth: c.ownerCt.labelWidth, itemCls: c.ownerCt.itemCls }); if(c.items){ c.items.each(fn); } }else if(c.isFormField){ f.add(c); } } this.items.each(fn); }, getLayoutTarget : function(){ return this.form.el; }, getForm : function(){ return this.form; }, onRender : function(ct, position){ this.initFields(); Ext.FormPanel.superclass.onRender.call(this, ct, position); var o = { tag: 'form', method : this.method || 'POST', id : this.formId || Ext.id() }; if(this.fileUpload) { o.enctype = 'multipart/form-data'; } this.form.initEl(this.body.createChild(o)); }, beforeDestroy: function(){ Ext.FormPanel.superclass.beforeDestroy.call(this); Ext.destroy(this.form); }, initEvents : function(){ Ext.FormPanel.superclass.initEvents.call(this); this.items.on('remove', this.onRemove, this); this.items.on('add', this.onAdd, this); if(this.monitorValid){ this.startMonitoring(); } }, onAdd : function(ct, c) { if (c.isFormField) { this.form.add(c); } }, onRemove : function(c) { if (c.isFormField) { Ext.destroy(c.container.up('.x-form-item')); this.form.remove(c); } }, startMonitoring : function(){ if(!this.bound){ this.bound = true; Ext.TaskMgr.start({ run : this.bindHandler, interval : this.monitorPoll || 200, scope: this }); } }, stopMonitoring : function(){ this.bound = false; }, load : function(){ this.form.load.apply(this.form, arguments); }, onDisable : function(){ Ext.FormPanel.superclass.onDisable.call(this); if(this.form){ this.form.items.each(function(){ this.disable(); }); } }, onEnable : function(){ Ext.FormPanel.superclass.onEnable.call(this); if(this.form){ this.form.items.each(function(){ this.enable(); }); } }, bindHandler : function(){ if(!this.bound){ return false; } var valid = true; this.form.items.each(function(f){ if(!f.isValid(true)){ valid = false; return false; } }); if(this.buttons){ for(var i = 0, len = this.buttons.length; i < len; i++){ var btn = this.buttons[i]; if(btn.formBind === true && btn.disabled === valid){ btn.setDisabled(!valid); } } } this.fireEvent('clientvalidation', this, valid); } }); Ext.reg('form', Ext.FormPanel); Ext.form.FormPanel = Ext.FormPanel; Ext.form.FieldSet = Ext.extend(Ext.Panel, { baseCls:'x-fieldset', layout: 'form', onRender : function(ct, position){ if(!this.el){ this.el = document.createElement('fieldset'); this.el.id = this.id; if (this.title || this.header || this.checkboxToggle) { this.el.appendChild(document.createElement('legend')).className = 'x-fieldset-header'; } } Ext.form.FieldSet.superclass.onRender.call(this, ct, position); if(this.checkboxToggle){ var o = typeof this.checkboxToggle == 'object' ? this.checkboxToggle : {tag: 'input', type: 'checkbox', name: this.checkboxName || this.id+'-checkbox'}; this.checkbox = this.header.insertFirst(o); this.checkbox.dom.checked = !this.collapsed; this.checkbox.on('click', this.onCheckClick, this); } }, onCollapse : function(doAnim, animArg){ if(this.checkbox){ this.checkbox.dom.checked = false; } this.afterCollapse(); }, onExpand : function(doAnim, animArg){ if(this.checkbox){ this.checkbox.dom.checked = true; } this.afterExpand(); }, onCheckClick : function(){ this[this.checkbox.dom.checked ? 'expand' : 'collapse'](); } }); Ext.reg('fieldset', Ext.form.FieldSet); Ext.form.HtmlEditor = Ext.extend(Ext.form.Field, { enableFormat : true, enableFontSize : true, enableColors : true, enableAlignments : true, enableLists : true, enableSourceEdit : true, enableLinks : true, enableFont : true, createLinkText : 'Please enter the URL for the link:', defaultLinkValue : 'http:/'+'/', fontFamilies : [ 'Arial', 'Courier New', 'Tahoma', 'Times New Roman', 'Verdana' ], defaultFont: 'tahoma', validationEvent : false, deferHeight: true, initialized : false, activated : false, sourceEditMode : false, onFocus : Ext.emptyFn, iframePad:3, hideMode:'offsets', defaultAutoCreate : { tag: "textarea", style:"width:500px;height:300px;", autocomplete: "off" }, initComponent : function(){ this.addEvents( 'initialize', 'activate', 'beforesync', 'beforepush', 'sync', 'push', 'editmodechange' ) }, createFontOptions : function(){ var buf = [], fs = this.fontFamilies, ff, lc; for(var i = 0, len = fs.length; i< len; i++){ ff = fs[i]; lc = ff.toLowerCase(); buf.push( '<option value="',lc,'" style="font-family:',ff,';"', (this.defaultFont == lc ? ' selected="true">' : '>'), ff, '</option>' ); } return buf.join(''); }, createToolbar : function(editor){ function btn(id, toggle, handler){ return { itemId : id, cls : 'x-btn-icon x-edit-'+id, enableToggle:toggle !== false, scope: editor, handler:handler||editor.relayBtnCmd, clickEvent:'mousedown', tooltip: editor.buttonTips[id] || undefined, tabIndex:-1 }; } var tb = new Ext.Toolbar({ renderTo:this.wrap.dom.firstChild }); tb.el.on('click', function(e){ e.preventDefault(); }); if(this.enableFont && !Ext.isSafari){ this.fontSelect = tb.el.createChild({ tag:'select', cls:'x-font-select', html: this.createFontOptions() }); this.fontSelect.on('change', function(){ var font = this.fontSelect.dom.value; this.relayCmd('fontname', font); this.deferFocus(); }, this); tb.add( this.fontSelect.dom, '-' ); }; if(this.enableFormat){ tb.add( btn('bold'), btn('italic'), btn('underline') ); }; if(this.enableFontSize){ tb.add( '-', btn('increasefontsize', false, this.adjustFont), btn('decreasefontsize', false, this.adjustFont) ); }; if(this.enableColors){ tb.add( '-', { itemId:'forecolor', cls:'x-btn-icon x-edit-forecolor', clickEvent:'mousedown', tooltip: editor.buttonTips['forecolor'] || undefined, tabIndex:-1, menu : new Ext.menu.ColorMenu({ allowReselect: true, focus: Ext.emptyFn, value:'000000', plain:true, selectHandler: function(cp, color){ this.execCmd('forecolor', Ext.isSafari || Ext.isIE ? '#'+color : color); this.deferFocus(); }, scope: this, clickEvent:'mousedown' }) }, { itemId:'backcolor', cls:'x-btn-icon x-edit-backcolor', clickEvent:'mousedown', tooltip: editor.buttonTips['backcolor'] || undefined, tabIndex:-1, menu : new Ext.menu.ColorMenu({ focus: Ext.emptyFn, value:'FFFFFF', plain:true, allowReselect: true, selectHandler: function(cp, color){ if(Ext.isGecko){ this.execCmd('useCSS', false); this.execCmd('hilitecolor', color); this.execCmd('useCSS', true); this.deferFocus(); }else{ this.execCmd(Ext.isOpera ? 'hilitecolor' : 'backcolor', Ext.isSafari || Ext.isIE ? '#'+color : color); this.deferFocus(); } }, scope:this, clickEvent:'mousedown' }) } ); }; if(this.enableAlignments){ tb.add( '-', btn('justifyleft'), btn('justifycenter'), btn('justifyright') ); }; if(!Ext.isSafari){ if(this.enableLinks){ tb.add( '-', btn('createlink', false, this.createLink) ); }; if(this.enableLists){ tb.add( '-', btn('insertorderedlist'), btn('insertunorderedlist') ); } if(this.enableSourceEdit){ tb.add( '-', btn('sourceedit', true, function(btn){ this.toggleSourceEdit(btn.pressed); }) ); } } this.tb = tb; }, getDocMarkup : function(){ return '<html><head><style type="text/css">body{border:0;margin:0;padding:3px;height:98%;cursor:text;}</style></head><body></body></html>'; }, getEditorBody : function(){ return this.doc.body || this.doc.documentElement; }, onRender : function(ct, position){ Ext.form.HtmlEditor.superclass.onRender.call(this, ct, position); this.el.dom.style.border = '0 none'; this.el.dom.setAttribute('tabIndex', -1); this.el.addClass('x-hidden'); if(Ext.isIE){ this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;') } this.wrap = this.el.wrap({ cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'} }); this.createToolbar(this); this.tb.items.each(function(item){ if(item.itemId != 'sourceedit'){ item.disable(); } }); var iframe = document.createElement('iframe'); iframe.name = Ext.id(); iframe.frameBorder = 'no'; iframe.src=(Ext.SSL_SECURE_URL || "javascript:false"); this.wrap.dom.appendChild(iframe); this.iframe = iframe; if(Ext.isIE){ iframe.contentWindow.document.designMode = 'on'; this.doc = iframe.contentWindow.document; this.win = iframe.contentWindow; } else { this.doc = (iframe.contentDocument || window.frames[iframe.name].document); this.win = window.frames[iframe.name]; this.doc.designMode = 'on'; } this.doc.open(); this.doc.write(this.getDocMarkup()) this.doc.close(); var task = { run : function(){ if(this.doc.body || this.doc.readyState == 'complete'){ Ext.TaskMgr.stop(task); this.doc.designMode="on"; this.initEditor.defer(10, this); } }, interval : 10, duration:10000, scope: this }; Ext.TaskMgr.start(task); if(!this.width){ this.setSize(this.el.getSize()); } }, onResize : function(w, h){ Ext.form.HtmlEditor.superclass.onResize.apply(this, arguments); if(this.el && this.iframe){ if(typeof w == 'number'){ var aw = w - this.wrap.getFrameWidth('lr'); this.el.setWidth(this.adjustWidth('textarea', aw)); this.iframe.style.width = aw + 'px'; } if(typeof h == 'number'){ var ah = h - this.wrap.getFrameWidth('tb') - this.tb.el.getHeight(); this.el.setHeight(this.adjustWidth('textarea', ah)); this.iframe.style.height = ah + 'px'; if(this.doc){ this.getEditorBody().style.height = (ah - (this.iframePad*2)) + 'px'; } } } }, toggleSourceEdit : function(sourceEditMode){ if(sourceEditMode === undefined){ sourceEditMode = !this.sourceEditMode; } this.sourceEditMode = sourceEditMode === true; var btn = this.tb.items.get('sourceedit'); if(btn.pressed !== this.sourceEditMode){ btn.toggle(this.sourceEditMode); return; } if(this.sourceEditMode){ this.tb.items.each(function(item){ if(item.itemId != 'sourceedit'){ item.disable(); } }); this.syncValue(); this.iframe.className = 'x-hidden'; this.el.removeClass('x-hidden'); this.el.dom.removeAttribute('tabIndex'); this.el.focus(); }else{ if(this.initialized){ this.tb.items.each(function(item){ item.enable(); }); } this.pushValue(); this.iframe.className = ''; this.el.addClass('x-hidden'); this.el.dom.setAttribute('tabIndex', -1); this.deferFocus(); } var lastSize = this.lastSize; if(lastSize){ delete this.lastSize; this.setSize(lastSize); } this.fireEvent('editmodechange', this, this.sourceEditMode); }, createLink : function(){ var url = prompt(this.createLinkText, this.defaultLinkValue); if(url && url != 'http:/'+'/'){ this.relayCmd('createlink', url); } }, adjustSize : Ext.BoxComponent.prototype.adjustSize, getResizeEl : function(){ return this.wrap; }, getPositionEl : function(){ return this.wrap; }, initEvents : function(){ this.originalValue = this.getValue(); }, markInvalid : Ext.emptyFn, clearInvalid : Ext.emptyFn, setValue : function(v){ Ext.form.HtmlEditor.superclass.setValue.call(this, v); this.pushValue(); }, cleanHtml : function(html){ html = String(html); if(html.length > 5){ if(Ext.isSafari){ html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, ''); } } if(html == '&nbsp;'){ html = ''; } return html; }, syncValue : function(){ if(this.initialized){ var bd = this.getEditorBody(); var html = bd.innerHTML; if(Ext.isSafari){ var bs = bd.getAttribute('style'); var m = bs.match(/text-align:(.*?);/i); if(m && m[1]){ html = '<div style="'+m[0]+'">' + html + '</div>'; } } html = this.cleanHtml(html); if(this.fireEvent('beforesync', this, html) !== false){ this.el.dom.value = html; this.fireEvent('sync', this, html); } } }, pushValue : function(){ if(this.initialized){ var v = this.el.dom.value; if(!this.activated && v.length < 1){ v = '&nbsp;'; } if(this.fireEvent('beforepush', this, v) !== false){ this.getEditorBody().innerHTML = v; this.fireEvent('push', this, v); } } }, deferFocus : function(){ this.focus.defer(10, this); }, focus : function(){ if(this.win && !this.sourceEditMode){ this.win.focus(); }else{ this.el.focus(); } }, initEditor : function(){ var dbody = this.getEditorBody(); var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat'); ss['background-attachment'] = 'fixed'; dbody.bgProperties = 'fixed'; Ext.DomHelper.applyStyles(dbody, ss); Ext.EventManager.on(this.doc, { 'mousedown': this.onEditorEvent, 'dblclick': this.onEditorEvent, 'click': this.onEditorEvent, 'keyup': this.onEditorEvent, buffer:100, scope: this }); if(Ext.isGecko){ Ext.EventManager.on(this.doc, 'keypress', this.applyCommand, this); } if(Ext.isIE || Ext.isSafari || Ext.isOpera){ Ext.EventManager.on(this.doc, 'keydown', this.fixKeys, this); } this.initialized = true; this.fireEvent('initialize', this); this.pushValue(); }, onDestroy : function(){ if(this.rendered){ this.tb.items.each(function(item){ if(item.menu){ item.menu.removeAll(); if(item.menu.el){ item.menu.el.destroy(); } } item.destroy(); }); this.wrap.dom.innerHTML = ''; this.wrap.remove(); } }, onFirstFocus : function(){ this.activated = true; this.tb.items.each(function(item){ item.enable(); }); if(Ext.isGecko){ this.win.focus(); var s = this.win.getSelection(); if(!s.focusNode || s.focusNode.nodeType != 3){ var r = s.getRangeAt(0); r.selectNodeContents(this.getEditorBody()); r.collapse(true); this.deferFocus(); } try{ this.execCmd('useCSS', true); this.execCmd('styleWithCSS', false); }catch(e){} } this.fireEvent('activate', this); }, adjustFont: function(btn){ var adjust = btn.itemId == 'increasefontsize' ? 1 : -1; var v = parseInt(this.doc.queryCommandValue('FontSize') || 2, 10); if(Ext.isSafari3 || Ext.isAir){ if(v <= 10){ v = 1 + adjust; }else if(v <= 13){ v = 2 + adjust; }else if(v <= 16){ v = 3 + adjust; }else if(v <= 18){ v = 4 + adjust; }else if(v <= 24){ v = 5 + adjust; }else { v = 6 + adjust; } v = v.constrain(1, 6); }else{ if(Ext.isSafari){ adjust *= 2; } v = Math.max(1, v+adjust) + (Ext.isSafari ? 'px' : 0); } this.execCmd('FontSize', v); }, onEditorEvent : function(e){ this.updateToolbar(); }, updateToolbar: function(){ if(!this.activated){ this.onFirstFocus(); return; } var btns = this.tb.items.map, doc = this.doc; if(this.enableFont && !Ext.isSafari){ var name = (this.doc.queryCommandValue('FontName')||this.defaultFont).toLowerCase(); if(name != this.fontSelect.dom.value){ this.fontSelect.dom.value = name; } } if(this.enableFormat){ btns.bold.toggle(doc.queryCommandState('bold')); btns.italic.toggle(doc.queryCommandState('italic')); btns.underline.toggle(doc.queryCommandState('underline')); } if(this.enableAlignments){ btns.justifyleft.toggle(doc.queryCommandState('justifyleft')); btns.justifycenter.toggle(doc.queryCommandState('justifycenter')); btns.justifyright.toggle(doc.queryCommandState('justifyright')); } if(!Ext.isSafari && this.enableLists){ btns.insertorderedlist.toggle(doc.queryCommandState('insertorderedlist')); btns.insertunorderedlist.toggle(doc.queryCommandState('insertunorderedlist')); } Ext.menu.MenuMgr.hideAll(); this.syncValue(); }, relayBtnCmd : function(btn){ this.relayCmd(btn.itemId); }, relayCmd : function(cmd, value){ this.win.focus(); this.execCmd(cmd, value); this.updateToolbar(); this.deferFocus(); }, execCmd : function(cmd, value){ this.doc.execCommand(cmd, false, value === undefined ? null : value); this.syncValue(); }, applyCommand : function(e){ if(e.ctrlKey){ var c = e.getCharCode(), cmd; if(c > 0){ c = String.fromCharCode(c); switch(c){ case 'b': cmd = 'bold'; break; case 'i': cmd = 'italic'; break; case 'u': cmd = 'underline'; break; } if(cmd){ this.win.focus(); this.execCmd(cmd); this.deferFocus(); e.preventDefault(); } } } }, insertAtCursor : function(text){ if(!this.activated){ return; } if(Ext.isIE){ this.win.focus(); var r = this.doc.selection.createRange(); if(r){ r.collapse(true); r.pasteHTML(text); this.syncValue(); this.deferFocus(); } }else if(Ext.isGecko || Ext.isOpera){ this.win.focus(); this.execCmd('InsertHTML', text); this.deferFocus(); }else if(Ext.isSafari){ this.execCmd('InsertText', text); this.deferFocus(); } }, fixKeys : function(){ if(Ext.isIE){ return function(e){ var k = e.getKey(), r; if(k == e.TAB){ e.stopEvent(); r = this.doc.selection.createRange(); if(r){ r.collapse(true); r.pasteHTML('&nbsp;&nbsp;&nbsp;&nbsp;'); this.deferFocus(); } }else if(k == e.ENTER){ r = this.doc.selection.createRange(); if(r){ var target = r.parentElement(); if(!target || target.tagName.toLowerCase() != 'li'){ e.stopEvent(); r.pasteHTML('<br />'); r.collapse(false); r.select(); } } } }; }else if(Ext.isOpera){ return function(e){ var k = e.getKey(); if(k == e.TAB){ e.stopEvent(); this.win.focus(); this.execCmd('InsertHTML','&nbsp;&nbsp;&nbsp;&nbsp;'); this.deferFocus(); } }; }else if(Ext.isSafari){ return function(e){ var k = e.getKey(); if(k == e.TAB){ e.stopEvent(); this.execCmd('InsertText','\t'); this.deferFocus(); } }; } }(), getToolbar : function(){ return this.tb; }, buttonTips : { bold : { title: 'Bold (Ctrl+B)', text: 'Make the selected text bold.', cls: 'x-html-editor-tip' }, italic : { title: 'Italic (Ctrl+I)', text: 'Make the selected text italic.', cls: 'x-html-editor-tip' }, underline : { title: 'Underline (Ctrl+U)', text: 'Underline the selected text.', cls: 'x-html-editor-tip' }, increasefontsize : { title: 'Grow Text', text: 'Increase the font size.', cls: 'x-html-editor-tip' }, decreasefontsize : { title: 'Shrink Text', text: 'Decrease the font size.', cls: 'x-html-editor-tip' }, backcolor : { title: 'Text Highlight Color', text: 'Change the background color of the selected text.', cls: 'x-html-editor-tip' }, forecolor : { title: 'Font Color', text: 'Change the color of the selected text.', cls: 'x-html-editor-tip' }, justifyleft : { title: 'Align Text Left', text: 'Align text to the left.', cls: 'x-html-editor-tip' }, justifycenter : { title: 'Center Text', text: 'Center text in the editor.', cls: 'x-html-editor-tip' }, justifyright : { title: 'Align Text Right', text: 'Align text to the right.', cls: 'x-html-editor-tip' }, insertunorderedlist : { title: 'Bullet List', text: 'Start a bulleted list.', cls: 'x-html-editor-tip' }, insertorderedlist : { title: 'Numbered List', text: 'Start a numbered list.', cls: 'x-html-editor-tip' }, createlink : { title: 'Hyperlink', text: 'Make the selected text a hyperlink.', cls: 'x-html-editor-tip' }, sourceedit : { title: 'Source Edit', text: 'Switch to source editing mode.', cls: 'x-html-editor-tip' } } }); Ext.reg('htmleditor', Ext.form.HtmlEditor); Ext.form.TimeField = Ext.extend(Ext.form.ComboBox, { minValue : null, maxValue : null, minText : "The time in this field must be equal to or after {0}", maxText : "The time in this field must be equal to or before {0}", invalidText : "{0} is not a valid time", format : "g:i A", altFormats : "g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H", increment: 15, mode: 'local', triggerAction: 'all', typeAhead: false, initComponent : function(){ Ext.form.TimeField.superclass.initComponent.call(this); if(typeof this.minValue == "string"){ this.minValue = this.parseDate(this.minValue); } if(typeof this.maxValue == "string"){ this.maxValue = this.parseDate(this.maxValue); } if(!this.store){ var min = this.parseDate(this.minValue); if(!min){ min = new Date().clearTime(); } var max = this.parseDate(this.maxValue); if(!max){ max = new Date().clearTime().add('mi', (24 * 60) - 1); } var times = []; while(min <= max){ times.push([min.dateFormat(this.format)]); min = min.add('mi', this.increment); } this.store = new Ext.data.SimpleStore({ fields: ['text'], data : times }); this.displayField = 'text'; } }, getValue : function(){ var v = Ext.form.TimeField.superclass.getValue.call(this); return this.formatDate(this.parseDate(v)) || ''; }, setValue : function(value){ Ext.form.TimeField.superclass.setValue.call(this, this.formatDate(this.parseDate(value))); }, validateValue : Ext.form.DateField.prototype.validateValue, parseDate : Ext.form.DateField.prototype.parseDate, formatDate : Ext.form.DateField.prototype.formatDate, beforeBlur : function(){ var v = this.parseDate(this.getRawValue()); if(v){ this.setValue(v.dateFormat(this.format)); } } }); Ext.reg('timefield', Ext.form.TimeField); Ext.form.Label = Ext.extend(Ext.BoxComponent, { onRender : function(ct, position){ if(!this.el){ this.el = document.createElement('label'); this.el.innerHTML = this.text ? Ext.util.Format.htmlEncode(this.text) : (this.html || ''); if(this.forId){ this.el.setAttribute('htmlFor', this.forId); } } Ext.form.Label.superclass.onRender.call(this, ct, position); } }); Ext.reg('label', Ext.form.Label); Ext.form.Action = function(form, options){ this.form = form; this.options = options || {}; }; Ext.form.Action.CLIENT_INVALID = 'client'; Ext.form.Action.SERVER_INVALID = 'server'; Ext.form.Action.CONNECT_FAILURE = 'connect'; Ext.form.Action.LOAD_FAILURE = 'load'; Ext.form.Action.prototype = { type : 'default', run : function(options){ }, success : function(response){ }, handleResponse : function(response){ }, failure : function(response){ this.response = response; this.failureType = Ext.form.Action.CONNECT_FAILURE; this.form.afterAction(this, false); }, processResponse : function(response){ this.response = response; if(!response.responseText){ return true; } this.result = this.handleResponse(response); return this.result; }, getUrl : function(appendParams){ var url = this.options.url || this.form.url || this.form.el.dom.action; if(appendParams){ var p = this.getParams(); if(p){ url += (url.indexOf('?') != -1 ? '&' : '?') + p; } } return url; }, getMethod : function(){ return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase(); }, getParams : function(){ var bp = this.form.baseParams; var p = this.options.params; if(p){ if(typeof p == "object"){ p = Ext.urlEncode(Ext.applyIf(p, bp)); }else if(typeof p == 'string' && bp){ p += '&' + Ext.urlEncode(bp); } }else if(bp){ p = Ext.urlEncode(bp); } return p; }, createCallback : function(opts){ var opts = opts || {}; return { success: this.success, failure: this.failure, scope: this, timeout: (opts.timeout*1000) || (this.form.timeout*1000), upload: this.form.fileUpload ? this.success : undefined }; } }; Ext.form.Action.Submit = function(form, options){ Ext.form.Action.Submit.superclass.constructor.call(this, form, options); }; Ext.extend(Ext.form.Action.Submit, Ext.form.Action, { type : 'submit', run : function(){ var o = this.options; var method = this.getMethod(); var isPost = method == 'POST'; if(o.clientValidation === false || this.form.isValid()){ Ext.Ajax.request(Ext.apply(this.createCallback(o), { form:this.form.el.dom, url:this.getUrl(!isPost), method: method, params:isPost ? this.getParams() : null, isUpload: this.form.fileUpload })); }else if (o.clientValidation !== false){ this.failureType = Ext.form.Action.CLIENT_INVALID; this.form.afterAction(this, false); } }, success : function(response){ var result = this.processResponse(response); if(result === true || result.success){ this.form.afterAction(this, true); return; } if(result.errors){ this.form.markInvalid(result.errors); this.failureType = Ext.form.Action.SERVER_INVALID; } this.form.afterAction(this, false); }, handleResponse : function(response){ if(this.form.errorReader){ var rs = this.form.errorReader.read(response); var errors = []; if(rs.records){ for(var i = 0, len = rs.records.length; i < len; i++) { var r = rs.records[i]; errors[i] = r.data; } } if(errors.length < 1){ errors = null; } return { success : rs.success, errors : errors }; } return Ext.decode(response.responseText); } }); Ext.form.Action.Load = function(form, options){ Ext.form.Action.Load.superclass.constructor.call(this, form, options); this.reader = this.form.reader; }; Ext.extend(Ext.form.Action.Load, Ext.form.Action, { type : 'load', run : function(){ Ext.Ajax.request(Ext.apply( this.createCallback(this.options), { method:this.getMethod(), url:this.getUrl(false), params:this.getParams() })); }, success : function(response){ var result = this.processResponse(response); if(result === true || !result.success || !result.data){ this.failureType = Ext.form.Action.LOAD_FAILURE; this.form.afterAction(this, false); return; } this.form.clearInvalid(); this.form.setValues(result.data); this.form.afterAction(this, true); }, handleResponse : function(response){ if(this.form.reader){ var rs = this.form.reader.read(response); var data = rs.records && rs.records[0] ? rs.records[0].data : null; return { success : rs.success, data : data }; } return Ext.decode(response.responseText); } }); Ext.form.Action.ACTION_TYPES = { 'load' : Ext.form.Action.Load, 'submit' : Ext.form.Action.Submit }; Ext.form.VTypes = function(){ var alpha = /^[a-zA-Z_]+$/; var alphanum = /^[a-zA-Z0-9_]+$/; var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/; var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i; return { 'email' : function(v){ return email.test(v); }, 'emailText' : 'This field should be an e-mail address in the format "user@domain.com"', 'emailMask' : /[a-z0-9_\.\-@]/i, 'url' : function(v){ return url.test(v); }, 'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"', 'alpha' : function(v){ return alpha.test(v); }, 'alphaText' : 'This field should only contain letters and _', 'alphaMask' : /[a-z_]/i, 'alphanum' : function(v){ return alphanum.test(v); }, 'alphanumText' : 'This field should only contain letters, numbers and _', 'alphanumMask' : /[a-z0-9_]/i }; }(); Ext.grid.GridPanel = Ext.extend(Ext.Panel, { ddText : "{0} selected row{1}", minColumnWidth : 25, trackMouseOver : true, enableDragDrop : false, enableColumnMove : true, enableColumnHide : true, enableHdMenu : true, stripeRows : false, autoExpandColumn : false, autoExpandMin : 50, autoExpandMax : 1000, view : null, loadMask : false, rendered : false, viewReady: false, stateEvents: ["columnmove", "columnresize", "sortchange"], initComponent : function(){ Ext.grid.GridPanel.superclass.initComponent.call(this); this.autoScroll = false; this.autoWidth = false; if(Ext.isArray(this.columns)){ this.colModel = new Ext.grid.ColumnModel(this.columns); delete this.columns; } if(this.ds){ this.store = this.ds; delete this.ds; } if(this.cm){ this.colModel = this.cm; delete this.cm; } if(this.sm){ this.selModel = this.sm; delete this.sm; } this.store = Ext.StoreMgr.lookup(this.store); this.addEvents( "click", "dblclick", "contextmenu", "mousedown", "mouseup", "mouseover", "mouseout", "keypress", "keydown", "cellmousedown", "rowmousedown", "headermousedown", "cellclick", "celldblclick", "rowclick", "rowdblclick", "headerclick", "headerdblclick", "rowcontextmenu", "cellcontextmenu", "headercontextmenu", "bodyscroll", "columnresize", "columnmove", "sortchange" ); }, onRender : function(ct, position){ Ext.grid.GridPanel.superclass.onRender.apply(this, arguments); var c = this.body; this.el.addClass('x-grid-panel'); var view = this.getView(); view.init(this); c.on("mousedown", this.onMouseDown, this); c.on("click", this.onClick, this); c.on("dblclick", this.onDblClick, this); c.on("contextmenu", this.onContextMenu, this); c.on("keydown", this.onKeyDown, this); this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]); this.getSelectionModel().init(this); this.view.render(); }, initEvents : function(){ Ext.grid.GridPanel.superclass.initEvents.call(this); if(this.loadMask){ this.loadMask = new Ext.LoadMask(this.bwrap, Ext.apply({store:this.store}, this.loadMask)); } }, initStateEvents : function(){ Ext.grid.GridPanel.superclass.initStateEvents.call(this); this.colModel.on('hiddenchange', this.saveState, this, {delay: 100}); }, applyState : function(state){ var cm = this.colModel; var cs = state.columns; if(cs){ for(var i = 0, len = cs.length; i < len; i++){ var s = cs[i]; var c = cm.getColumnById(s.id); if(c){ c.hidden = s.hidden; c.width = s.width; var oldIndex = cm.getIndexById(s.id); if(oldIndex != i){ cm.moveColumn(oldIndex, i); } } } } if(state.sort){ this.store[this.store.remoteSort ? 'setDefaultSort' : 'sort'](state.sort.field, state.sort.direction); } }, getState : function(){ var o = {columns: []}; for(var i = 0, c; c = this.colModel.config[i]; i++){ o.columns[i] = { id: c.id, width: c.width }; if(c.hidden){ o.columns[i].hidden = true; } } var ss = this.store.getSortState(); if(ss){ o.sort = ss; } return o; }, afterRender : function(){ Ext.grid.GridPanel.superclass.afterRender.call(this); this.view.layout(); this.viewReady = true; }, reconfigure : function(store, colModel){ if(this.loadMask){ this.loadMask.destroy(); this.loadMask = new Ext.LoadMask(this.bwrap, Ext.apply({store:store}, this.initialConfig.loadMask)); } this.view.bind(store, colModel); this.store = store; this.colModel = colModel; if(this.rendered){ this.view.refresh(true); } }, onKeyDown : function(e){ this.fireEvent("keydown", e); }, onDestroy : function(){ if(this.rendered){ if(this.loadMask){ this.loadMask.destroy(); } var c = this.body; c.removeAllListeners(); this.view.destroy(); c.update(""); } this.colModel.purgeListeners(); Ext.grid.GridPanel.superclass.onDestroy.call(this); }, processEvent : function(name, e){ this.fireEvent(name, e); var t = e.getTarget(); var v = this.view; var header = v.findHeaderIndex(t); if(header !== false){ this.fireEvent("header" + name, this, header, e); }else{ var row = v.findRowIndex(t); var cell = v.findCellIndex(t); if(row !== false){ this.fireEvent("row" + name, this, row, e); if(cell !== false){ this.fireEvent("cell" + name, this, row, cell, e); } } } }, onClick : function(e){ this.processEvent("click", e); }, onMouseDown : function(e){ this.processEvent("mousedown", e); }, onContextMenu : function(e, t){ this.processEvent("contextmenu", e); }, onDblClick : function(e){ this.processEvent("dblclick", e); }, walkCells : function(row, col, step, fn, scope){ var cm = this.colModel, clen = cm.getColumnCount(); var ds = this.store, rlen = ds.getCount(), first = true; if(step < 0){ if(col < 0){ row--; first = false; } while(row >= 0){ if(!first){ col = clen-1; } first = false; while(col >= 0){ if(fn.call(scope || this, row, col, cm) === true){ return [row, col]; } col--; } row--; } } else { if(col >= clen){ row++; first = false; } while(row < rlen){ if(!first){ col = 0; } first = false; while(col < clen){ if(fn.call(scope || this, row, col, cm) === true){ return [row, col]; } col++; } row++; } } return null; }, getSelections : function(){ return this.selModel.getSelections(); }, onResize : function(){ Ext.grid.GridPanel.superclass.onResize.apply(this, arguments); if(this.viewReady){ this.view.layout(); } }, getGridEl : function(){ return this.body; }, stopEditing : function(){}, getSelectionModel : function(){ if(!this.selModel){ this.selModel = new Ext.grid.RowSelectionModel( this.disableSelection ? {selectRow: Ext.emptyFn} : null); } return this.selModel; }, getStore : function(){ return this.store; }, getColumnModel : function(){ return this.colModel; }, getView : function(){ if(!this.view){ this.view = new Ext.grid.GridView(this.viewConfig); } return this.view; }, getDragDropText : function(){ var count = this.selModel.getCount(); return String.format(this.ddText, count, count == 1 ? '' : 's'); } }); Ext.reg('grid', Ext.grid.GridPanel); Ext.grid.GridView = function(config){ Ext.apply(this, config); this.addEvents( "beforerowremoved", "beforerowsinserted", "beforerefresh", "rowremoved", "rowsinserted", "rowupdated", "refresh" ); Ext.grid.GridView.superclass.constructor.call(this); }; Ext.extend(Ext.grid.GridView, Ext.util.Observable, { scrollOffset: 19, autoFill: false, forceFit: false, sortClasses : ["sort-asc", "sort-desc"], sortAscText : "Sort Ascending", sortDescText : "Sort Descending", columnsText : "Columns", borderWidth: 2, initTemplates : function(){ var ts = this.templates || {}; if(!ts.master){ ts.master = new Ext.Template( '<div class="x-grid3" hidefocus="true">', '<div class="x-grid3-viewport">', '<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset">{header}</div></div><div class="x-clear"></div></div>', '<div class="x-grid3-scroller"><div class="x-grid3-body">{body}</div><a href="#" class="x-grid3-focus" tabIndex="-1"></a></div>', "</div>", '<div class="x-grid3-resize-marker">&#160;</div>', '<div class="x-grid3-resize-proxy">&#160;</div>', "</div>" ); } if(!ts.header){ ts.header = new Ext.Template( '<table border="0" cellspacing="0" cellpadding="0" style="{tstyle}">', '<thead><tr class="x-grid3-hd-row">{cells}</tr></thead>', "</table>" ); } if(!ts.hcell){ ts.hcell = new Ext.Template( '<td class="x-grid3-hd x-grid3-cell x-grid3-td-{id}" style="{style}"><div {tooltip} {attr} class="x-grid3-hd-inner x-grid3-hd-{id}" unselectable="on" style="{istyle}">', this.grid.enableHdMenu ? '<a class="x-grid3-hd-btn" href="#"></a>' : '', '{value}<img class="x-grid3-sort-icon" src="', Ext.BLANK_IMAGE_URL, '" />', "</div></td>" ); } if(!ts.body){ ts.body = new Ext.Template('{rows}'); } if(!ts.row){ ts.row = new Ext.Template( '<div class="x-grid3-row {alt}" style="{tstyle}"><table class="x-grid3-row-table" border="0" cellspacing="0" cellpadding="0" style="{tstyle}">', '<tbody><tr>{cells}</tr>', (this.enableRowBody ? '<tr class="x-grid3-row-body-tr" style="{bodyStyle}"><td colspan="{cols}" class="x-grid3-body-cell" tabIndex="0" hidefocus="on"><div class="x-grid3-row-body">{body}</div></td></tr>' : ''), '</tbody></table></div>' ); } if(!ts.cell){ ts.cell = new Ext.Template( '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} {css}" style="{style}" tabIndex="0" {cellAttr}>', '<div class="x-grid3-cell-inner x-grid3-col-{id}" unselectable="on" {attr}>{value}</div>', "</td>" ); } for(var k in ts){ var t = ts[k]; if(t && typeof t.compile == 'function' && !t.compiled){ t.disableFormats = true; t.compile(); } } this.templates = ts; this.tdClass = 'x-grid3-cell'; this.cellSelector = 'td.x-grid3-cell'; this.hdCls = 'x-grid3-hd'; this.rowSelector = 'div.x-grid3-row'; this.colRe = new RegExp("x-grid3-td-([^\\s]+)", ""); }, fly : function(el){ if(!this._flyweight){ this._flyweight = new Ext.Element.Flyweight(document.body); } this._flyweight.dom = el; return this._flyweight; }, getEditorParent : function(ed){ return this.scroller.dom; }, initElements : function(){ var E = Ext.Element; var el = this.grid.getGridEl().dom.firstChild; var cs = el.childNodes; this.el = new E(el); this.mainWrap = new E(cs[0]); this.mainHd = new E(this.mainWrap.dom.firstChild); if(this.grid.hideHeaders){ this.mainHd.setDisplayed(false); } this.innerHd = this.mainHd.dom.firstChild; this.scroller = new E(this.mainWrap.dom.childNodes[1]); if(this.forceFit){ this.scroller.setStyle('overflow-x', 'hidden'); } this.mainBody = new E(this.scroller.dom.firstChild); this.focusEl = new E(this.scroller.dom.childNodes[1]); this.focusEl.swallowEvent("click", true); this.resizeMarker = new E(cs[1]); this.resizeProxy = new E(cs[2]); }, getRows : function(){ return this.hasRows() ? this.mainBody.dom.childNodes : []; }, findCell : function(el){ if(!el){ return false; } return this.fly(el).findParent(this.cellSelector, 3); }, findCellIndex : function(el, requiredCls){ var cell = this.findCell(el); if(cell && (!requiredCls || this.fly(cell).hasClass(requiredCls))){ return this.getCellIndex(cell); } return false; }, getCellIndex : function(el){ if(el){ var m = el.className.match(this.colRe); if(m && m[1]){ return this.cm.getIndexById(m[1]); } } return false; }, findHeaderCell : function(el){ var cell = this.findCell(el); return cell && this.fly(cell).hasClass(this.hdCls) ? cell : null; }, findHeaderIndex : function(el){ return this.findCellIndex(el, this.hdCls); }, findRow : function(el){ if(!el){ return false; } return this.fly(el).findParent(this.rowSelector, 10); }, findRowIndex : function(el){ var r = this.findRow(el); return r ? r.rowIndex : false; }, getRow : function(row){ return this.getRows()[row]; }, getCell : function(row, col){ return this.getRow(row).getElementsByTagName('td')[col]; }, getHeaderCell : function(index){ return this.mainHd.dom.getElementsByTagName('td')[index]; }, addRowClass : function(row, cls){ var r = this.getRow(row); if(r){ this.fly(r).addClass(cls); } }, removeRowClass : function(row, cls){ var r = this.getRow(row); if(r){ this.fly(r).removeClass(cls); } }, removeRow : function(row){ Ext.removeNode(this.getRow(row)); }, removeRows : function(firstRow, lastRow){ var bd = this.mainBody.dom; for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){ Ext.removeNode(bd.childNodes[firstRow]); } }, getScrollState : function(){ var sb = this.scroller.dom; return {left: sb.scrollLeft, top: sb.scrollTop}; }, restoreScroll : function(state){ var sb = this.scroller.dom; sb.scrollLeft = state.left; sb.scrollTop = state.top; }, scrollToTop : function(){ this.scroller.dom.scrollTop = 0; this.scroller.dom.scrollLeft = 0; }, syncScroll : function(){ this.syncHeaderScroll(); var mb = this.scroller.dom; this.grid.fireEvent("bodyscroll", mb.scrollLeft, mb.scrollTop); }, syncHeaderScroll : function(){ var mb = this.scroller.dom; this.innerHd.scrollLeft = mb.scrollLeft; this.innerHd.scrollLeft = mb.scrollLeft; }, updateSortIcon : function(col, dir){ var sc = this.sortClasses; var hds = this.mainHd.select('td').removeClass(sc); hds.item(col).addClass(sc[dir == "DESC" ? 1 : 0]); }, updateAllColumnWidths : function(){ var tw = this.getTotalWidth(); var clen = this.cm.getColumnCount(); var ws = []; for(var i = 0; i < clen; i++){ ws[i] = this.getColumnWidth(i); } this.innerHd.firstChild.firstChild.style.width = tw; for(var i = 0; i < clen; i++){ var hd = this.getHeaderCell(i); hd.style.width = ws[i]; } var ns = this.getRows(); for(var i = 0, len = ns.length; i < len; i++){ ns[i].style.width = tw; ns[i].firstChild.style.width = tw; var row = ns[i].firstChild.rows[0]; for(var j = 0; j < clen; j++){ row.childNodes[j].style.width = ws[j]; } } this.onAllColumnWidthsUpdated(ws, tw); }, updateColumnWidth : function(col, width){ var w = this.getColumnWidth(col); var tw = this.getTotalWidth(); this.innerHd.firstChild.firstChild.style.width = tw; var hd = this.getHeaderCell(col); hd.style.width = w; var ns = this.getRows(); for(var i = 0, len = ns.length; i < len; i++){ ns[i].style.width = tw; ns[i].firstChild.style.width = tw; ns[i].firstChild.rows[0].childNodes[col].style.width = w; } this.onColumnWidthUpdated(col, w, tw); }, updateColumnHidden : function(col, hidden){ var tw = this.getTotalWidth(); this.innerHd.firstChild.firstChild.style.width = tw; var display = hidden ? 'none' : ''; var hd = this.getHeaderCell(col); hd.style.display = display; var ns = this.getRows(); for(var i = 0, len = ns.length; i < len; i++){ ns[i].style.width = tw; ns[i].firstChild.style.width = tw; ns[i].firstChild.rows[0].childNodes[col].style.display = display; } this.onColumnHiddenUpdated(col, hidden, tw); delete this.lastViewWidth; this.layout(); }, doRender : function(cs, rs, ds, startRow, colCount, stripe){ var ts = this.templates, ct = ts.cell, rt = ts.row, last = colCount-1; var tstyle = 'width:'+this.getTotalWidth()+';'; var buf = [], cb, c, p = {}, rp = {tstyle: tstyle}, r; for(var j = 0, len = rs.length; j < len; j++){ r = rs[j]; cb = []; var rowIndex = (j+startRow); for(var i = 0; i < colCount; i++){ c = cs[i]; p.id = c.id; p.css = i == 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : ''); p.attr = p.cellAttr = ""; p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds); p.style = c.style; if(p.value == undefined || p.value === "") p.value = "&#160;"; if(r.dirty && typeof r.modified[c.name] !== 'undefined'){ p.css += ' x-grid3-dirty-cell'; } cb[cb.length] = ct.apply(p); } var alt = []; if(stripe && ((rowIndex+1) % 2 == 0)){ alt[0] = "x-grid3-row-alt"; } if(r.dirty){ alt[1] = " x-grid3-dirty-row"; } rp.cols = colCount; if(this.getRowClass){ alt[2] = this.getRowClass(r, rowIndex, rp, ds); } rp.alt = alt.join(" "); rp.cells = cb.join(""); buf[buf.length] = rt.apply(rp); } return buf.join(""); }, processRows : function(startRow, skipStripe){ if(this.ds.getCount() < 1){ return; } skipStripe = skipStripe || !this.grid.stripeRows; startRow = startRow || 0; var rows = this.getRows(); var cls = ' x-grid3-row-alt '; for(var i = startRow, len = rows.length; i < len; i++){ var row = rows[i]; row.rowIndex = i; if(!skipStripe){ var isAlt = ((i+1) % 2 == 0); var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1; if(isAlt == hasAlt){ continue; } if(isAlt){ row.className += " x-grid3-row-alt"; }else{ row.className = row.className.replace("x-grid3-row-alt", ""); } } } }, renderUI : function(){ var header = this.renderHeaders(); var body = this.templates.body.apply({rows:''}); var html = this.templates.master.apply({ body: body, header: header }); var g = this.grid; g.getGridEl().dom.innerHTML = html; this.initElements(); this.mainBody.dom.innerHTML = this.renderRows(); this.processRows(0, true); Ext.fly(this.innerHd).on("click", this.handleHdDown, this); this.mainHd.on("mouseover", this.handleHdOver, this); this.mainHd.on("mouseout", this.handleHdOut, this); this.mainHd.on("mousemove", this.handleHdMove, this); this.scroller.on('scroll', this.syncScroll, this); if(g.enableColumnResize !== false){ this.splitone = new Ext.grid.GridView.SplitDragZone(g, this.mainHd.dom); } if(g.enableColumnMove){ this.columnDrag = new Ext.grid.GridView.ColumnDragZone(g, this.innerHd); this.columnDrop = new Ext.grid.HeaderDropZone(g, this.mainHd.dom); } if(g.enableHdMenu !== false){ if(g.enableColumnHide !== false){ this.colMenu = new Ext.menu.Menu({id:g.id + "-hcols-menu"}); this.colMenu.on("beforeshow", this.beforeColMenuShow, this); this.colMenu.on("itemclick", this.handleHdMenuClick, this); } this.hmenu = new Ext.menu.Menu({id: g.id + "-hctx"}); this.hmenu.add( {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"}, {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"} ); if(g.enableColumnHide !== false){ this.hmenu.add('-', {id:"columns", text: this.columnsText, menu: this.colMenu, iconCls: 'x-cols-icon'} ); } this.hmenu.on("itemclick", this.handleHdMenuClick, this); } if(g.enableDragDrop || g.enableDrag){ var dd = new Ext.grid.GridDragZone(g, { ddGroup : g.ddGroup || 'GridDD' }); } this.updateHeaderSortState(); }, layout : function(){ if(!this.mainBody){ return; } var g = this.grid; var c = g.getGridEl(), cm = this.cm, expandCol = g.autoExpandColumn, gv = this; var csize = c.getSize(true); var vw = csize.width; if(vw < 20 || csize.height < 20){ return; } if(g.autoHeight){ this.scroller.dom.style.overflow = 'visible'; }else{ this.el.setSize(csize.width, csize.height); var hdHeight = this.mainHd.getHeight(); var vh = csize.height - (hdHeight); this.scroller.setSize(vw, vh); if(this.innerHd){ this.innerHd.style.width = (vw)+'px'; } } if(this.forceFit){ if(this.lastViewWidth != vw){ this.fitColumns(false, false); this.lastViewWidth = vw; } }else { this.autoExpand(); this.syncHeaderScroll(); } this.onLayout(vw, vh); }, onLayout : function(vw, vh){ }, onColumnWidthUpdated : function(col, w, tw){ }, onAllColumnWidthsUpdated : function(ws, tw){ }, onColumnHiddenUpdated : function(col, hidden, tw){ }, updateColumnText : function(col, text){ }, afterMove : function(colIndex){ }, init: function(grid){ this.grid = grid; this.initTemplates(); this.initData(grid.store, grid.colModel); this.initUI(grid); }, getColumnId : function(index){ return this.cm.getColumnId(index); }, renderHeaders : function(){ var cm = this.cm, ts = this.templates; var ct = ts.hcell; var cb = [], sb = [], p = {}; for(var i = 0, len = cm.getColumnCount(); i < len; i++){ p.id = cm.getColumnId(i); p.value = cm.getColumnHeader(i) || ""; p.style = this.getColumnStyle(i, true); p.tooltip = this.getColumnTooltip(i); if(cm.config[i].align == 'right'){ p.istyle = 'padding-right:16px'; } else { delete p.istyle; } cb[cb.length] = ct.apply(p); } return ts.header.apply({cells: cb.join(""), tstyle:'width:'+this.getTotalWidth()+';'}); }, getColumnTooltip : function(i){ var tt = this.cm.getColumnTooltip(i); if(tt){ if(Ext.QuickTips.isEnabled()){ return 'ext:qtip="'+tt+'"'; }else{ return 'title="'+tt+'"'; } } return ""; }, beforeUpdate : function(){ this.grid.stopEditing(true); }, updateHeaders : function(){ this.innerHd.firstChild.innerHTML = this.renderHeaders(); }, focusRow : function(row){ this.focusCell(row, 0, false); }, focusCell : function(row, col, hscroll){ var xy = this.ensureVisible(row, col, hscroll); this.focusEl.setXY(xy); if(Ext.isGecko){ this.focusEl.focus(); }else{ this.focusEl.focus.defer(1, this.focusEl); } }, ensureVisible : function(row, col, hscroll){ if(typeof row != "number"){ row = row.rowIndex; } if(!this.ds){ return; } if(row < 0 || row >= this.ds.getCount()){ return; } col = (col !== undefined ? col : 0); var rowEl = this.getRow(row), cellEl; if(!(hscroll === false && col === 0)){ while(this.cm.isHidden(col)){ col++; } cellEl = this.getCell(row, col); } if(!rowEl){ return; } var c = this.scroller.dom; var ctop = 0; var p = rowEl, stop = this.el.dom; while(p && p != stop){ ctop += p.offsetTop; p = p.offsetParent; } ctop -= this.mainHd.dom.offsetHeight; var cbot = ctop + rowEl.offsetHeight; var ch = c.clientHeight; var stop = parseInt(c.scrollTop, 10); var sbot = stop + ch; if(ctop < stop){ c.scrollTop = ctop; }else if(cbot > sbot){ c.scrollTop = cbot-ch; } if(hscroll !== false){ var cleft = parseInt(cellEl.offsetLeft, 10); var cright = cleft + cellEl.offsetWidth; var sleft = parseInt(c.scrollLeft, 10); var sright = sleft + c.clientWidth; if(cleft < sleft){ c.scrollLeft = cleft; }else if(cright > sright){ c.scrollLeft = cright-c.clientWidth; } } return cellEl ? Ext.fly(cellEl).getXY() : [c.scrollLeft, Ext.fly(rowEl).getY()]; }, insertRows : function(dm, firstRow, lastRow, isUpdate){ if(!isUpdate && firstRow === 0 && lastRow == dm.getCount()-1){ this.refresh(); }else{ if(!isUpdate){ this.fireEvent("beforerowsinserted", this, firstRow, lastRow); } var html = this.renderRows(firstRow, lastRow); var before = this.getRow(firstRow); if(before){ Ext.DomHelper.insertHtml('beforeBegin', before, html); }else{ Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html); } if(!isUpdate){ this.fireEvent("rowsinserted", this, firstRow, lastRow); this.processRows(firstRow); } } }, deleteRows : function(dm, firstRow, lastRow){ if(dm.getRowCount()<1){ this.refresh(); }else{ this.fireEvent("beforerowsdeleted", this, firstRow, lastRow); this.removeRows(firstRow, lastRow); this.processRows(firstRow); this.fireEvent("rowsdeleted", this, firstRow, lastRow); } }, getColumnStyle : function(col, isHeader){ var style = !isHeader ? (this.cm.config[col].css || '') : ''; style += 'width:'+this.getColumnWidth(col)+';'; if(this.cm.isHidden(col)){ style += 'display:none;'; } var align = this.cm.config[col].align; if(align){ style += 'text-align:'+align+';'; } return style; }, getColumnWidth : function(col){ var w = this.cm.getColumnWidth(col); if(typeof w == 'number'){ return (Ext.isBorderBox ? w : (w-this.borderWidth > 0 ? w-this.borderWidth:0)) + 'px'; } return w; }, getTotalWidth : function(){ return this.cm.getTotalWidth()+'px'; }, fitColumns : function(preventRefresh, onlyExpand, omitColumn){ var cm = this.cm, leftOver, dist, i; var tw = cm.getTotalWidth(false); var aw = this.grid.getGridEl().getWidth(true)-this.scrollOffset; if(aw < 20){ return; } var extra = aw - tw; if(extra === 0){ return false; } var vc = cm.getColumnCount(true); var ac = vc-(typeof omitColumn == 'number' ? 1 : 0); if(ac === 0){ ac = 1; omitColumn = undefined; } var colCount = cm.getColumnCount(); var cols = []; var extraCol = 0; var width = 0; var w; for (i = 0; i < colCount; i++){ if(!cm.isHidden(i) && !cm.isFixed(i) && i !== omitColumn){ w = cm.getColumnWidth(i); cols.push(i); extraCol = i; cols.push(w); width += w; } } var frac = (aw - cm.getTotalWidth())/width; while (cols.length){ w = cols.pop(); i = cols.pop(); cm.setColumnWidth(i, Math.max(this.grid.minColumnWidth, Math.floor(w + w*frac)), true); } if((tw = cm.getTotalWidth(false)) > aw){ var adjustCol = ac != vc ? omitColumn : extraCol; cm.setColumnWidth(adjustCol, Math.max(1, cm.getColumnWidth(adjustCol)- (tw-aw)), true); } if(preventRefresh !== true){ this.updateAllColumnWidths(); } return true; }, autoExpand : function(preventUpdate){ var g = this.grid, cm = this.cm; if(!this.userResized && g.autoExpandColumn){ var tw = cm.getTotalWidth(false); var aw = this.grid.getGridEl().getWidth(true)-this.scrollOffset; if(tw != aw){ var ci = cm.getIndexById(g.autoExpandColumn); var currentWidth = cm.getColumnWidth(ci); var cw = Math.min(Math.max(((aw-tw)+currentWidth), g.autoExpandMin), g.autoExpandMax); if(cw != currentWidth){ cm.setColumnWidth(ci, cw, true); if(preventUpdate !== true){ this.updateColumnWidth(ci, cw); } } } } }, getColumnData : function(){ var cs = [], cm = this.cm, colCount = cm.getColumnCount(); for(var i = 0; i < colCount; i++){ var name = cm.getDataIndex(i); cs[i] = { name : (typeof name == 'undefined' ? this.ds.fields.get(i).name : name), renderer : cm.getRenderer(i), id : cm.getColumnId(i), style : this.getColumnStyle(i) }; } return cs; }, renderRows : function(startRow, endRow){ var g = this.grid, cm = g.colModel, ds = g.store, stripe = g.stripeRows; var colCount = cm.getColumnCount(); if(ds.getCount() < 1){ return ""; } var cs = this.getColumnData(); startRow = startRow || 0; endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow; var rs = ds.getRange(startRow, endRow); return this.doRender(cs, rs, ds, startRow, colCount, stripe); }, renderBody : function(){ var markup = this.renderRows(); return this.templates.body.apply({rows: markup}); }, refreshRow : function(record){ var ds = this.ds, index; if(typeof record == 'number'){ index = record; record = ds.getAt(index); }else{ index = ds.indexOf(record); } var cls = []; this.insertRows(ds, index, index, true); this.getRow(index).rowIndex = index; this.onRemove(ds, record, index+1, true); this.fireEvent("rowupdated", this, index, record); }, refresh : function(headersToo){ this.fireEvent("beforerefresh", this); this.grid.stopEditing(true); var result = this.renderBody(); this.mainBody.update(result); if(headersToo === true){ this.updateHeaders(); this.updateHeaderSortState(); } this.processRows(0, true); this.layout(); this.applyEmptyText(); this.fireEvent("refresh", this); }, applyEmptyText : function(){ if(this.emptyText && !this.hasRows()){ this.mainBody.update('<div class="x-grid-empty">' + this.emptyText + '</div>'); } }, updateHeaderSortState : function(){ var state = this.ds.getSortState(); if(!state){ return; } if(!this.sortState || (this.sortState.field != state.field || this.sortState.direction != state.direction)){ this.grid.fireEvent('sortchange', this.grid, state); } this.sortState = state; var sortColumn = this.cm.findColumnIndex(state.field); if(sortColumn != -1){ var sortDir = state.direction; this.updateSortIcon(sortColumn, sortDir); } }, destroy : function(){ if(this.colMenu){ this.colMenu.removeAll(); Ext.menu.MenuMgr.unregister(this.colMenu); this.colMenu.getEl().remove(); delete this.colMenu; } if(this.hmenu){ this.hmenu.removeAll(); Ext.menu.MenuMgr.unregister(this.hmenu); this.hmenu.getEl().remove(); delete this.hmenu; } if(this.grid.enableColumnMove){ var dds = Ext.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id]; if(dds){ for(var dd in dds){ if(!dds[dd].config.isTarget && dds[dd].dragElId){ var elid = dds[dd].dragElId; dds[dd].unreg(); Ext.get(elid).remove(); } else if(dds[dd].config.isTarget){ dds[dd].proxyTop.remove(); dds[dd].proxyBottom.remove(); dds[dd].unreg(); } if(Ext.dd.DDM.locationCache[dd]){ delete Ext.dd.DDM.locationCache[dd]; } } delete Ext.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id]; } } Ext.destroy(this.resizeMarker, this.resizeProxy); this.initData(null, null); Ext.EventManager.removeResizeListener(this.onWindowResize, this); }, onDenyColumnHide : function(){ }, render : function(){ var cm = this.cm; var colCount = cm.getColumnCount(); if(this.autoFill){ this.fitColumns(true, true); }else if(this.forceFit){ this.fitColumns(true, false); }else if(this.grid.autoExpandColumn){ this.autoExpand(true); } this.renderUI(); }, initData : function(ds, cm){ if(this.ds){ this.ds.un("load", this.onLoad, this); this.ds.un("datachanged", this.onDataChange, this); this.ds.un("add", this.onAdd, this); this.ds.un("remove", this.onRemove, this); this.ds.un("update", this.onUpdate, this); this.ds.un("clear", this.onClear, this); } if(ds){ ds.on("load", this.onLoad, this); ds.on("datachanged", this.onDataChange, this); ds.on("add", this.onAdd, this); ds.on("remove", this.onRemove, this); ds.on("update", this.onUpdate, this); ds.on("clear", this.onClear, this); } this.ds = ds; if(this.cm){ this.cm.un("configchange", this.onColConfigChange, this); this.cm.un("widthchange", this.onColWidthChange, this); this.cm.un("headerchange", this.onHeaderChange, this); this.cm.un("hiddenchange", this.onHiddenChange, this); this.cm.un("columnmoved", this.onColumnMove, this); this.cm.un("columnlockchange", this.onColumnLock, this); } if(cm){ cm.on("configchange", this.onColConfigChange, this); cm.on("widthchange", this.onColWidthChange, this); cm.on("headerchange", this.onHeaderChange, this); cm.on("hiddenchange", this.onHiddenChange, this); cm.on("columnmoved", this.onColumnMove, this); cm.on("columnlockchange", this.onColumnLock, this); } this.cm = cm; }, onDataChange : function(){ this.refresh(); this.updateHeaderSortState(); }, onClear : function(){ this.refresh(); }, onUpdate : function(ds, record){ this.refreshRow(record); }, onAdd : function(ds, records, index){ this.insertRows(ds, index, index + (records.length-1)); }, onRemove : function(ds, record, index, isUpdate){ if(isUpdate !== true){ this.fireEvent("beforerowremoved", this, index, record); } this.removeRow(index); if(isUpdate !== true){ this.processRows(index); this.applyEmptyText(); this.fireEvent("rowremoved", this, index, record); } }, onLoad : function(){ this.scrollToTop(); }, onColWidthChange : function(cm, col, width){ this.updateColumnWidth(col, width); }, onHeaderChange : function(cm, col, text){ this.updateHeaders(); }, onHiddenChange : function(cm, col, hidden){ this.updateColumnHidden(col, hidden); }, onColumnMove : function(cm, oldIndex, newIndex){ this.indexMap = null; var s = this.getScrollState(); this.refresh(true); this.restoreScroll(s); this.afterMove(newIndex); }, onColConfigChange : function(){ delete this.lastViewWidth; this.indexMap = null; this.refresh(true); }, initUI : function(grid){ grid.on("headerclick", this.onHeaderClick, this); if(grid.trackMouseOver){ grid.on("mouseover", this.onRowOver, this); grid.on("mouseout", this.onRowOut, this); } }, initEvents : function(){ }, onHeaderClick : function(g, index){ if(this.headersDisabled || !this.cm.isSortable(index)){ return; } g.stopEditing(true); g.store.sort(this.cm.getDataIndex(index)); }, onRowOver : function(e, t){ var row; if((row = this.findRowIndex(t)) !== false){ this.addRowClass(row, "x-grid3-row-over"); } }, onRowOut : function(e, t){ var row; if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){ this.removeRowClass(row, "x-grid3-row-over"); } }, handleWheel : function(e){ e.stopPropagation(); }, onRowSelect : function(row){ this.addRowClass(row, "x-grid3-row-selected"); }, onRowDeselect : function(row){ this.removeRowClass(row, "x-grid3-row-selected"); }, onCellSelect : function(row, col){ var cell = this.getCell(row, col); if(cell){ this.fly(cell).addClass("x-grid3-cell-selected"); } }, onCellDeselect : function(row, col){ var cell = this.getCell(row, col); if(cell){ this.fly(cell).removeClass("x-grid3-cell-selected"); } }, onColumnSplitterMoved : function(i, w){ this.userResized = true; var cm = this.grid.colModel; cm.setColumnWidth(i, w, true); if(this.forceFit){ this.fitColumns(true, false, i); this.updateAllColumnWidths(); }else{ this.updateColumnWidth(i, w); } this.grid.fireEvent("columnresize", i, w); }, handleHdMenuClick : function(item){ var index = this.hdCtxIndex; var cm = this.cm, ds = this.ds; switch(item.id){ case "asc": ds.sort(cm.getDataIndex(index), "ASC"); break; case "desc": ds.sort(cm.getDataIndex(index), "DESC"); break; default: index = cm.getIndexById(item.id.substr(4)); if(index != -1){ if(item.checked && cm.getColumnsBy(this.isHideableColumn, this).length <= 1){ this.onDenyColumnHide(); return false; } cm.setHidden(index, item.checked); } } return true; }, isHideableColumn : function(c){ return !c.hidden && !c.fixed; }, beforeColMenuShow : function(){ var cm = this.cm, colCount = cm.getColumnCount(); this.colMenu.removeAll(); for(var i = 0; i < colCount; i++){ if(cm.config[i].fixed !== true && cm.config[i].hideable !== false){ this.colMenu.add(new Ext.menu.CheckItem({ id: "col-"+cm.getColumnId(i), text: cm.getColumnHeader(i), checked: !cm.isHidden(i), hideOnClick:false, disabled: cm.config[i].hideable === false })); } } }, handleHdDown : function(e, t){ if(Ext.fly(t).hasClass('x-grid3-hd-btn')){ e.stopEvent(); var hd = this.findHeaderCell(t); Ext.fly(hd).addClass('x-grid3-hd-menu-open'); var index = this.getCellIndex(hd); this.hdCtxIndex = index; var ms = this.hmenu.items, cm = this.cm; ms.get("asc").setDisabled(!cm.isSortable(index)); ms.get("desc").setDisabled(!cm.isSortable(index)); this.hmenu.on("hide", function(){ Ext.fly(hd).removeClass('x-grid3-hd-menu-open'); }, this, {single:true}); this.hmenu.show(t, "tl-bl?"); } }, handleHdOver : function(e, t){ var hd = this.findHeaderCell(t); if(hd && !this.headersDisabled){ this.activeHd = hd; this.activeHdIndex = this.getCellIndex(hd); var fly = this.fly(hd); this.activeHdRegion = fly.getRegion(); if(!this.cm.isMenuDisabled(this.activeHdIndex)){ fly.addClass("x-grid3-hd-over"); this.activeHdBtn = fly.child('.x-grid3-hd-btn'); if(this.activeHdBtn){ this.activeHdBtn.dom.style.height = (hd.firstChild.offsetHeight-1)+'px'; } } } }, handleHdMove : function(e, t){ if(this.activeHd && !this.headersDisabled){ var hw = this.splitHandleWidth || 5; var r = this.activeHdRegion; var x = e.getPageX(); var ss = this.activeHd.style; if(x - r.left <= hw && this.cm.isResizable(this.activeHdIndex-1)){ ss.cursor = Ext.isAir ? 'move' : Ext.isSafari ? 'e-resize' : 'col-resize'; }else if(r.right - x <= (!this.activeHdBtn ? hw : 2) && this.cm.isResizable(this.activeHdIndex)){ ss.cursor = Ext.isAir ? 'move' : Ext.isSafari ? 'w-resize' : 'col-resize'; }else{ ss.cursor = ''; } } }, handleHdOut : function(e, t){ var hd = this.findHeaderCell(t); if(hd && (!Ext.isIE || !e.within(hd, true))){ this.activeHd = null; this.fly(hd).removeClass("x-grid3-hd-over"); hd.style.cursor = ''; } }, hasRows : function(){ var fc = this.mainBody.dom.firstChild; return fc && fc.className != 'x-grid-empty'; }, bind : function(d, c){ this.initData(d, c); } }); Ext.grid.GridView.SplitDragZone = function(grid, hd){ this.grid = grid; this.view = grid.getView(); this.marker = this.view.resizeMarker; this.proxy = this.view.resizeProxy; Ext.grid.GridView.SplitDragZone.superclass.constructor.call(this, hd, "gridSplitters" + this.grid.getGridEl().id, { dragElId : Ext.id(this.proxy.dom), resizeFrame:false }); this.scroll = false; this.hw = this.view.splitHandleWidth || 5; }; Ext.extend(Ext.grid.GridView.SplitDragZone, Ext.dd.DDProxy, { b4StartDrag : function(x, y){ this.view.headersDisabled = true; var h = this.view.mainWrap.getHeight(); this.marker.setHeight(h); this.marker.show(); this.marker.alignTo(this.view.getHeaderCell(this.cellIndex), 'tl-tl', [-2, 0]); this.proxy.setHeight(h); var w = this.cm.getColumnWidth(this.cellIndex); var minw = Math.max(w-this.grid.minColumnWidth, 0); this.resetConstraints(); this.setXConstraint(minw, 1000); this.setYConstraint(0, 0); this.minX = x - minw; this.maxX = x + 1000; this.startPos = x; Ext.dd.DDProxy.prototype.b4StartDrag.call(this, x, y); }, handleMouseDown : function(e){ var t = this.view.findHeaderCell(e.getTarget()); if(t){ var xy = this.view.fly(t).getXY(), x = xy[0], y = xy[1]; var exy = e.getXY(), ex = exy[0], ey = exy[1]; var w = t.offsetWidth, adjust = false; if((ex - x) <= this.hw){ adjust = -1; }else if((x+w) - ex <= this.hw){ adjust = 0; } if(adjust !== false){ this.cm = this.grid.colModel; var ci = this.view.getCellIndex(t); if(adjust == -1){ if (ci + adjust < 0) { return; } while(this.cm.isHidden(ci+adjust)){ --adjust; if(ci+adjust < 0){ return; } } } this.cellIndex = ci+adjust; this.split = t.dom; if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){ Ext.grid.GridView.SplitDragZone.superclass.handleMouseDown.apply(this, arguments); } }else if(this.view.columnDrag){ this.view.columnDrag.callHandleMouseDown(e); } } }, endDrag : function(e){ this.marker.hide(); var v = this.view; var endX = Math.max(this.minX, e.getPageX()); var diff = endX - this.startPos; v.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff); setTimeout(function(){ v.headersDisabled = false; }, 50); }, autoOffset : function(){ this.setDelta(0,0); } }); Ext.grid.GroupingView = Ext.extend(Ext.grid.GridView, { hideGroupedColumn:false, showGroupName:true, startCollapsed:false, enableGrouping:true, enableGroupingMenu:true, enableNoGroups:true, emptyGroupText : '(None)', ignoreAdd: false, groupTextTpl : '{text}', gidSeed : 1000, initTemplates : function(){ Ext.grid.GroupingView.superclass.initTemplates.call(this); this.state = {}; var sm = this.grid.getSelectionModel(); sm.on(sm.selectRow ? 'beforerowselect' : 'beforecellselect', this.onBeforeRowSelect, this); if(!this.startGroup){ this.startGroup = new Ext.XTemplate( '<div id="{groupId}" class="x-grid-group {cls}">', '<div id="{groupId}-hd" class="x-grid-group-hd" style="{style}"><div>', this.groupTextTpl ,'</div></div>', '<div id="{groupId}-bd" class="x-grid-group-body">' ); } this.startGroup.compile(); this.endGroup = '</div></div>'; }, findGroup : function(el){ return Ext.fly(el).up('.x-grid-group', this.mainBody.dom); }, getGroups : function(){ return this.hasRows() ? this.mainBody.dom.childNodes : []; }, onAdd : function(){ if(this.enableGrouping && !this.ignoreAdd){ var ss = this.getScrollState(); this.refresh(); this.restoreScroll(ss); }else if(!this.enableGrouping){ Ext.grid.GroupingView.superclass.onAdd.apply(this, arguments); } }, onRemove : function(ds, record, index, isUpdate){ Ext.grid.GroupingView.superclass.onRemove.apply(this, arguments); var g = document.getElementById(record._groupId); if(g && g.childNodes[1].childNodes.length < 1){ Ext.removeNode(g); } this.applyEmptyText(); }, refreshRow : function(record){ if(this.ds.getCount()==1){ this.refresh(); }else{ this.isUpdating = true; Ext.grid.GroupingView.superclass.refreshRow.apply(this, arguments); this.isUpdating = false; } }, beforeMenuShow : function(){ var field = this.getGroupField(); var g = this.hmenu.items.get('groupBy'); if(g){ g.setDisabled(this.cm.config[this.hdCtxIndex].groupable === false); } var s = this.hmenu.items.get('showGroups'); if(s){ if (!!field){ s.setDisabled(this.cm.config[this.hdCtxIndex].groupable === false) } s.setChecked(!!field); } }, renderUI : function(){ Ext.grid.GroupingView.superclass.renderUI.call(this); this.mainBody.on('mousedown', this.interceptMouse, this); if(this.enableGroupingMenu && this.hmenu){ this.hmenu.add('-',{ id:'groupBy', text: this.groupByText, handler: this.onGroupByClick, scope: this, iconCls:'x-group-by-icon' }); if(this.enableNoGroups){ this.hmenu.add({ id:'showGroups', text: this.showGroupsText, checked: true, checkHandler: this.onShowGroupsClick, scope: this }); } this.hmenu.on('beforeshow', this.beforeMenuShow, this); } }, onGroupByClick : function(){ this.grid.store.groupBy(this.cm.getDataIndex(this.hdCtxIndex)); this.beforeMenuShow(); }, onShowGroupsClick : function(mi, checked){ if(checked){ this.onGroupByClick(); }else{ this.grid.store.clearGrouping(); } }, toggleGroup : function(group, expanded){ this.grid.stopEditing(true); group = Ext.getDom(group); var gel = Ext.fly(group); expanded = expanded !== undefined ? expanded : gel.hasClass('x-grid-group-collapsed'); this.state[gel.dom.id] = expanded; gel[expanded ? 'removeClass' : 'addClass']('x-grid-group-collapsed'); }, toggleAllGroups : function(expanded){ var groups = this.getGroups(); for(var i = 0, len = groups.length; i < len; i++){ this.toggleGroup(groups[i], expanded); } }, expandAllGroups : function(){ this.toggleAllGroups(true); }, collapseAllGroups : function(){ this.toggleAllGroups(false); }, interceptMouse : function(e){ var hd = e.getTarget('.x-grid-group-hd', this.mainBody); if(hd){ e.stopEvent(); this.toggleGroup(hd.parentNode); } }, getGroup : function(v, r, groupRenderer, rowIndex, colIndex, ds){ var g = groupRenderer ? groupRenderer(v, {}, r, rowIndex, colIndex, ds) : String(v); if(g === ''){ g = this.cm.config[colIndex].emptyGroupText || this.emptyGroupText; } return g; }, getGroupField : function(){ return this.grid.store.getGroupState(); }, renderRows : function(){ var groupField = this.getGroupField(); var eg = !!groupField; if(this.hideGroupedColumn) { var colIndex = this.cm.findColumnIndex(groupField); if(!eg && this.lastGroupField !== undefined) { this.mainBody.update(''); this.cm.setHidden(this.cm.findColumnIndex(this.lastGroupField), false); delete this.lastGroupField; }else if (eg && this.lastGroupField === undefined) { this.lastGroupField = groupField; this.cm.setHidden(colIndex, true); }else if (eg && this.lastGroupField !== undefined && groupField !== this.lastGroupField) { this.mainBody.update(''); var oldIndex = this.cm.findColumnIndex(this.lastGroupField); this.cm.setHidden(oldIndex, false); this.lastGroupField = groupField; this.cm.setHidden(colIndex, true); } } return Ext.grid.GroupingView.superclass.renderRows.apply( this, arguments); }, doRender : function(cs, rs, ds, startRow, colCount, stripe){ if(rs.length < 1){ return ''; } var groupField = this.getGroupField(); var colIndex = this.cm.findColumnIndex(groupField); this.enableGrouping = !!groupField; if(!this.enableGrouping || this.isUpdating){ return Ext.grid.GroupingView.superclass.doRender.apply( this, arguments); } var gstyle = 'width:'+this.getTotalWidth()+';'; var gidPrefix = this.grid.getGridEl().id; var cfg = this.cm.config[colIndex]; var groupRenderer = cfg.groupRenderer || cfg.renderer; var prefix = this.showGroupName ? (cfg.groupName || cfg.header)+': ' : ''; var groups = [], curGroup, i, len, gid; for(i = 0, len = rs.length; i < len; i++){ var rowIndex = startRow + i; var r = rs[i], gvalue = r.data[groupField], g = this.getGroup(gvalue, r, groupRenderer, rowIndex, colIndex, ds); if(!curGroup || curGroup.group != g){ gid = gidPrefix + '-gp-' + groupField + '-' + Ext.util.Format.htmlEncode(g); var isCollapsed = typeof this.state[gid] !== 'undefined' ? !this.state[gid] : this.startCollapsed; var gcls = isCollapsed ? 'x-grid-group-collapsed' : ''; curGroup = { group: g, gvalue: gvalue, text: prefix + g, groupId: gid, startRow: rowIndex, rs: [r], cls: gcls, style: gstyle }; groups.push(curGroup); }else{ curGroup.rs.push(r); } r._groupId = gid; } var buf = []; for(i = 0, len = groups.length; i < len; i++){ var g = groups[i]; this.doGroupStart(buf, g, cs, ds, colCount); buf[buf.length] = Ext.grid.GroupingView.superclass.doRender.call( this, cs, g.rs, ds, g.startRow, colCount, stripe); this.doGroupEnd(buf, g, cs, ds, colCount); } return buf.join(''); }, getGroupId : function(value){ var gidPrefix = this.grid.getGridEl().id; var groupField = this.getGroupField(); var colIndex = this.cm.findColumnIndex(groupField); var cfg = this.cm.config[colIndex]; var groupRenderer = cfg.groupRenderer || cfg.renderer; var gtext = this.getGroup(value, {data:{}}, groupRenderer, 0, colIndex, this.ds); return gidPrefix + '-gp-' + groupField + '-' + Ext.util.Format.htmlEncode(value); }, doGroupStart : function(buf, g, cs, ds, colCount){ buf[buf.length] = this.startGroup.apply(g); }, doGroupEnd : function(buf, g, cs, ds, colCount){ buf[buf.length] = this.endGroup; }, getRows : function(){ if(!this.enableGrouping){ return Ext.grid.GroupingView.superclass.getRows.call(this); } var r = []; var g, gs = this.getGroups(); for(var i = 0, len = gs.length; i < len; i++){ g = gs[i].childNodes[1].childNodes; for(var j = 0, jlen = g.length; j < jlen; j++){ r[r.length] = g[j]; } } return r; }, updateGroupWidths : function(){ if(!this.enableGrouping || !this.hasRows()){ return; } var tw = Math.max(this.cm.getTotalWidth(), this.el.dom.offsetWidth-this.scrollOffset) +'px'; var gs = this.getGroups(); for(var i = 0, len = gs.length; i < len; i++){ gs[i].firstChild.style.width = tw; } }, onColumnWidthUpdated : function(col, w, tw){ this.updateGroupWidths(); }, onAllColumnWidthsUpdated : function(ws, tw){ this.updateGroupWidths(); }, onColumnHiddenUpdated : function(col, hidden, tw){ this.updateGroupWidths(); }, onLayout : function(){ this.updateGroupWidths(); }, onBeforeRowSelect : function(sm, rowIndex){ if(!this.enableGrouping){ return; } var row = this.getRow(rowIndex); if(row && !row.offsetParent){ var g = this.findGroup(row); this.toggleGroup(g, true); } }, groupByText: 'Group By This Field', showGroupsText: 'Show in Groups' }); Ext.grid.GroupingView.GROUP_ID = 1000; Ext.grid.HeaderDragZone = function(grid, hd, hd2){ this.grid = grid; this.view = grid.getView(); this.ddGroup = "gridHeader" + this.grid.getGridEl().id; Ext.grid.HeaderDragZone.superclass.constructor.call(this, hd); if(hd2){ this.setHandleElId(Ext.id(hd)); this.setOuterHandleElId(Ext.id(hd2)); } this.scroll = false; }; Ext.extend(Ext.grid.HeaderDragZone, Ext.dd.DragZone, { maxDragWidth: 120, getDragData : function(e){ var t = Ext.lib.Event.getTarget(e); var h = this.view.findHeaderCell(t); if(h){ return {ddel: h.firstChild, header:h}; } return false; }, onInitDrag : function(e){ this.view.headersDisabled = true; var clone = this.dragData.ddel.cloneNode(true); clone.id = Ext.id(); clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px"; this.proxy.update(clone); return true; }, afterValidDrop : function(){ var v = this.view; setTimeout(function(){ v.headersDisabled = false; }, 50); }, afterInvalidDrop : function(){ var v = this.view; setTimeout(function(){ v.headersDisabled = false; }, 50); } }); Ext.grid.HeaderDropZone = function(grid, hd, hd2){ this.grid = grid; this.view = grid.getView(); this.proxyTop = Ext.DomHelper.append(document.body, { cls:"col-move-top", html:"&#160;" }, true); this.proxyBottom = Ext.DomHelper.append(document.body, { cls:"col-move-bottom", html:"&#160;" }, true); this.proxyTop.hide = this.proxyBottom.hide = function(){ this.setLeftTop(-100,-100); this.setStyle("visibility", "hidden"); }; this.ddGroup = "gridHeader" + this.grid.getGridEl().id; Ext.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom); }; Ext.extend(Ext.grid.HeaderDropZone, Ext.dd.DropZone, { proxyOffsets : [-4, -9], fly: Ext.Element.fly, getTargetFromEvent : function(e){ var t = Ext.lib.Event.getTarget(e); var cindex = this.view.findCellIndex(t); if(cindex !== false){ return this.view.getHeaderCell(cindex); } }, nextVisible : function(h){ var v = this.view, cm = this.grid.colModel; h = h.nextSibling; while(h){ if(!cm.isHidden(v.getCellIndex(h))){ return h; } h = h.nextSibling; } return null; }, prevVisible : function(h){ var v = this.view, cm = this.grid.colModel; h = h.prevSibling; while(h){ if(!cm.isHidden(v.getCellIndex(h))){ return h; } h = h.prevSibling; } return null; }, positionIndicator : function(h, n, e){ var x = Ext.lib.Event.getPageX(e); var r = Ext.lib.Dom.getRegion(n.firstChild); var px, pt, py = r.top + this.proxyOffsets[1]; if((r.right - x) <= (r.right-r.left)/2){ px = r.right+this.view.borderWidth; pt = "after"; }else{ px = r.left; pt = "before"; } var oldIndex = this.view.getCellIndex(h); var newIndex = this.view.getCellIndex(n); if(this.grid.colModel.isFixed(newIndex)){ return false; } var locked = this.grid.colModel.isLocked(newIndex); if(pt == "after"){ newIndex++; } if(oldIndex < newIndex){ newIndex--; } if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){ return false; } px += this.proxyOffsets[0]; this.proxyTop.setLeftTop(px, py); this.proxyTop.show(); if(!this.bottomOffset){ this.bottomOffset = this.view.mainHd.getHeight(); } this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset); this.proxyBottom.show(); return pt; }, onNodeEnter : function(n, dd, e, data){ if(data.header != n){ this.positionIndicator(data.header, n, e); } }, onNodeOver : function(n, dd, e, data){ var result = false; if(data.header != n){ result = this.positionIndicator(data.header, n, e); } if(!result){ this.proxyTop.hide(); this.proxyBottom.hide(); } return result ? this.dropAllowed : this.dropNotAllowed; }, onNodeOut : function(n, dd, e, data){ this.proxyTop.hide(); this.proxyBottom.hide(); }, onNodeDrop : function(n, dd, e, data){ var h = data.header; if(h != n){ var cm = this.grid.colModel; var x = Ext.lib.Event.getPageX(e); var r = Ext.lib.Dom.getRegion(n.firstChild); var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before"; var oldIndex = this.view.getCellIndex(h); var newIndex = this.view.getCellIndex(n); var locked = cm.isLocked(newIndex); if(pt == "after"){ newIndex++; } if(oldIndex < newIndex){ newIndex--; } if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){ return false; } cm.setLocked(oldIndex, locked, true); cm.moveColumn(oldIndex, newIndex); this.grid.fireEvent("columnmove", oldIndex, newIndex); return true; } return false; } }); Ext.grid.GridView.ColumnDragZone = function(grid, hd){ Ext.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null); this.proxy.el.addClass('x-grid3-col-dd'); }; Ext.extend(Ext.grid.GridView.ColumnDragZone, Ext.grid.HeaderDragZone, { handleMouseDown : function(e){ }, callHandleMouseDown : function(e){ Ext.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e); } }); Ext.grid.SplitDragZone = function(grid, hd, hd2){ this.grid = grid; this.view = grid.getView(); this.proxy = this.view.resizeProxy; Ext.grid.SplitDragZone.superclass.constructor.call(this, hd, "gridSplitters" + this.grid.getGridEl().id, { dragElId : Ext.id(this.proxy.dom), resizeFrame:false }); this.setHandleElId(Ext.id(hd)); this.setOuterHandleElId(Ext.id(hd2)); this.scroll = false; }; Ext.extend(Ext.grid.SplitDragZone, Ext.dd.DDProxy, { fly: Ext.Element.fly, b4StartDrag : function(x, y){ this.view.headersDisabled = true; this.proxy.setHeight(this.view.mainWrap.getHeight()); var w = this.cm.getColumnWidth(this.cellIndex); var minw = Math.max(w-this.grid.minColumnWidth, 0); this.resetConstraints(); this.setXConstraint(minw, 1000); this.setYConstraint(0, 0); this.minX = x - minw; this.maxX = x + 1000; this.startPos = x; Ext.dd.DDProxy.prototype.b4StartDrag.call(this, x, y); }, handleMouseDown : function(e){ ev = Ext.EventObject.setEvent(e); var t = this.fly(ev.getTarget()); if(t.hasClass("x-grid-split")){ this.cellIndex = this.view.getCellIndex(t.dom); this.split = t.dom; this.cm = this.grid.colModel; if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){ Ext.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments); } } }, endDrag : function(e){ this.view.headersDisabled = false; var endX = Math.max(this.minX, Ext.lib.Event.getPageX(e)); var diff = endX - this.startPos; this.view.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff); }, autoOffset : function(){ this.setDelta(0,0); } }); Ext.grid.GridDragZone = function(grid, config){ this.view = grid.getView(); Ext.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config); if(this.view.lockedBody){ this.setHandleElId(Ext.id(this.view.mainBody.dom)); this.setOuterHandleElId(Ext.id(this.view.lockedBody.dom)); } this.scroll = false; this.grid = grid; this.ddel = document.createElement('div'); this.ddel.className = 'x-grid-dd-wrap'; }; Ext.extend(Ext.grid.GridDragZone, Ext.dd.DragZone, { ddGroup : "GridDD", getDragData : function(e){ var t = Ext.lib.Event.getTarget(e); var rowIndex = this.view.findRowIndex(t); if(rowIndex !== false){ var sm = this.grid.selModel; if(!sm.isSelected(rowIndex) || e.hasModifier()){ sm.handleMouseDown(this.grid, rowIndex, e); } return {grid: this.grid, ddel: this.ddel, rowIndex: rowIndex, selections:sm.getSelections()}; } return false; }, onInitDrag : function(e){ var data = this.dragData; this.ddel.innerHTML = this.grid.getDragDropText(); this.proxy.update(this.ddel); }, afterRepair : function(){ this.dragging = false; }, getRepairXY : function(e, data){ return false; }, onEndDrag : function(data, e){ }, onValidDrop : function(dd, e, id){ this.hideProxy(); }, beforeInvalidDrop : function(e, id){ } }); Ext.grid.ColumnModel = function(config){ this.defaultWidth = 100; this.defaultSortable = false; if(config.columns){ Ext.apply(this, config); this.setConfig(config.columns, true); }else{ this.setConfig(config, true); } this.addEvents( "widthchange", "headerchange", "hiddenchange", "columnmoved", "columnlockchange", "configchange" ); Ext.grid.ColumnModel.superclass.constructor.call(this); }; Ext.extend(Ext.grid.ColumnModel, Ext.util.Observable, { getColumnId : function(index){ return this.config[index].id; }, setConfig : function(config, initial){ if(!initial){ delete this.totalWidth; for(var i = 0, len = this.config.length; i < len; i++){ var c = this.config[i]; if(c.editor){ c.editor.destroy(); } } } this.config = config; this.lookup = {}; for(var i = 0, len = config.length; i < len; i++){ var c = config[i]; if(typeof c.renderer == "string"){ c.renderer = Ext.util.Format[c.renderer]; } if(typeof c.id == "undefined"){ c.id = i; } if(c.editor && c.editor.isFormField){ c.editor = new Ext.grid.GridEditor(c.editor); } this.lookup[c.id] = c; } if(!initial){ this.fireEvent('configchange', this); } }, getColumnById : function(id){ return this.lookup[id]; }, getIndexById : function(id){ for(var i = 0, len = this.config.length; i < len; i++){ if(this.config[i].id == id){ return i; } } return -1; }, moveColumn : function(oldIndex, newIndex){ var c = this.config[oldIndex]; this.config.splice(oldIndex, 1); this.config.splice(newIndex, 0, c); this.dataMap = null; this.fireEvent("columnmoved", this, oldIndex, newIndex); }, isLocked : function(colIndex){ return this.config[colIndex].locked === true; }, setLocked : function(colIndex, value, suppressEvent){ if(this.isLocked(colIndex) == value){ return; } this.config[colIndex].locked = value; if(!suppressEvent){ this.fireEvent("columnlockchange", this, colIndex, value); } }, getTotalLockedWidth : function(){ var totalWidth = 0; for(var i = 0; i < this.config.length; i++){ if(this.isLocked(i) && !this.isHidden(i)){ this.totalWidth += this.getColumnWidth(i); } } return totalWidth; }, getLockedCount : function(){ for(var i = 0, len = this.config.length; i < len; i++){ if(!this.isLocked(i)){ return i; } } }, getColumnCount : function(visibleOnly){ if(visibleOnly === true){ var c = 0; for(var i = 0, len = this.config.length; i < len; i++){ if(!this.isHidden(i)){ c++; } } return c; } return this.config.length; }, getColumnsBy : function(fn, scope){ var r = []; for(var i = 0, len = this.config.length; i < len; i++){ var c = this.config[i]; if(fn.call(scope||this, c, i) === true){ r[r.length] = c; } } return r; }, isSortable : function(col){ if(typeof this.config[col].sortable == "undefined"){ return this.defaultSortable; } return this.config[col].sortable; }, isMenuDisabled : function(col){ return !!this.config[col].menuDisabled; }, getRenderer : function(col){ if(!this.config[col].renderer){ return Ext.grid.ColumnModel.defaultRenderer; } return this.config[col].renderer; }, setRenderer : function(col, fn){ this.config[col].renderer = fn; }, getColumnWidth : function(col){ return this.config[col].width || this.defaultWidth; }, setColumnWidth : function(col, width, suppressEvent){ this.config[col].width = width; this.totalWidth = null; if(!suppressEvent){ this.fireEvent("widthchange", this, col, width); } }, getTotalWidth : function(includeHidden){ if(!this.totalWidth){ this.totalWidth = 0; for(var i = 0, len = this.config.length; i < len; i++){ if(includeHidden || !this.isHidden(i)){ this.totalWidth += this.getColumnWidth(i); } } } return this.totalWidth; }, getColumnHeader : function(col){ return this.config[col].header; }, setColumnHeader : function(col, header){ this.config[col].header = header; this.fireEvent("headerchange", this, col, header); }, getColumnTooltip : function(col){ return this.config[col].tooltip; }, setColumnTooltip : function(col, tooltip){ this.config[col].tooltip = tooltip; }, getDataIndex : function(col){ return this.config[col].dataIndex; }, setDataIndex : function(col, dataIndex){ this.config[col].dataIndex = dataIndex; }, findColumnIndex : function(dataIndex){ var c = this.config; for(var i = 0, len = c.length; i < len; i++){ if(c[i].dataIndex == dataIndex){ return i; } } return -1; }, isCellEditable : function(colIndex, rowIndex){ return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false; }, getCellEditor : function(colIndex, rowIndex){ return this.config[colIndex].editor; }, setEditable : function(col, editable){ this.config[col].editable = editable; }, isHidden : function(colIndex){ return this.config[colIndex].hidden; }, isFixed : function(colIndex){ return this.config[colIndex].fixed; }, isResizable : function(colIndex){ return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true; }, setHidden : function(colIndex, hidden){ var c = this.config[colIndex]; if(c.hidden !== hidden){ c.hidden = hidden; this.totalWidth = null; this.fireEvent("hiddenchange", this, colIndex, hidden); } }, setEditor : function(col, editor){ this.config[col].editor = editor; } }); Ext.grid.ColumnModel.defaultRenderer = function(value){ if(typeof value == "string" && value.length < 1){ return "&#160;"; } return value; }; Ext.grid.DefaultColumnModel = Ext.grid.ColumnModel; Ext.grid.AbstractSelectionModel = function(){ this.locked = false; Ext.grid.AbstractSelectionModel.superclass.constructor.call(this); }; Ext.extend(Ext.grid.AbstractSelectionModel, Ext.util.Observable, { init : function(grid){ this.grid = grid; this.initEvents(); }, lock : function(){ this.locked = true; }, unlock : function(){ this.locked = false; }, isLocked : function(){ return this.locked; } }); Ext.grid.RowSelectionModel = function(config){ Ext.apply(this, config); this.selections = new Ext.util.MixedCollection(false, function(o){ return o.id; }); this.last = false; this.lastActive = false; this.addEvents( "selectionchange", "beforerowselect", "rowselect", "rowdeselect" ); Ext.grid.RowSelectionModel.superclass.constructor.call(this); }; Ext.extend(Ext.grid.RowSelectionModel, Ext.grid.AbstractSelectionModel, { singleSelect : false, initEvents : function(){ if(!this.grid.enableDragDrop && !this.grid.enableDrag){ this.grid.on("rowmousedown", this.handleMouseDown, this); }else{ this.grid.on("rowclick", function(grid, rowIndex, e) { if(e.button === 0 && !e.shiftKey && !e.ctrlKey) { this.selectRow(rowIndex, false); grid.view.focusRow(rowIndex); } }, this); } this.rowNav = new Ext.KeyNav(this.grid.getGridEl(), { "up" : function(e){ if(!e.shiftKey){ this.selectPrevious(e.shiftKey); }else if(this.last !== false && this.lastActive !== false){ var last = this.last; this.selectRange(this.last, this.lastActive-1); this.grid.getView().focusRow(this.lastActive); if(last !== false){ this.last = last; } }else{ this.selectFirstRow(); } }, "down" : function(e){ if(!e.shiftKey){ this.selectNext(e.shiftKey); }else if(this.last !== false && this.lastActive !== false){ var last = this.last; this.selectRange(this.last, this.lastActive+1); this.grid.getView().focusRow(this.lastActive); if(last !== false){ this.last = last; } }else{ this.selectFirstRow(); } }, scope: this }); var view = this.grid.view; view.on("refresh", this.onRefresh, this); view.on("rowupdated", this.onRowUpdated, this); view.on("rowremoved", this.onRemove, this); }, onRefresh : function(){ var ds = this.grid.store, index; var s = this.getSelections(); this.clearSelections(true); for(var i = 0, len = s.length; i < len; i++){ var r = s[i]; if((index = ds.indexOfId(r.id)) != -1){ this.selectRow(index, true); } } if(s.length != this.selections.getCount()){ this.fireEvent("selectionchange", this); } }, onRemove : function(v, index, r){ if(this.selections.remove(r) !== false){ this.fireEvent('selectionchange', this); } }, onRowUpdated : function(v, index, r){ if(this.isSelected(r)){ v.onRowSelect(index); } }, selectRecords : function(records, keepExisting){ if(!keepExisting){ this.clearSelections(); } var ds = this.grid.store; for(var i = 0, len = records.length; i < len; i++){ this.selectRow(ds.indexOf(records[i]), true); } }, getCount : function(){ return this.selections.length; }, selectFirstRow : function(){ this.selectRow(0); }, selectLastRow : function(keepExisting){ this.selectRow(this.grid.store.getCount() - 1, keepExisting); }, selectNext : function(keepExisting){ if(this.hasNext()){ this.selectRow(this.last+1, keepExisting); this.grid.getView().focusRow(this.last); return true; } return false; }, selectPrevious : function(keepExisting){ if(this.hasPrevious()){ this.selectRow(this.last-1, keepExisting); this.grid.getView().focusRow(this.last); return true; } return false; }, hasNext : function(){ return this.last !== false && (this.last+1) < this.grid.store.getCount(); }, hasPrevious : function(){ return !!this.last; }, getSelections : function(){ return [].concat(this.selections.items); }, getSelected : function(){ return this.selections.itemAt(0); }, each : function(fn, scope){ var s = this.getSelections(); for(var i = 0, len = s.length; i < len; i++){ if(fn.call(scope || this, s[i], i) === false){ return false; } } return true; }, clearSelections : function(fast){ if(this.locked) return; if(fast !== true){ var ds = this.grid.store; var s = this.selections; s.each(function(r){ this.deselectRow(ds.indexOfId(r.id)); }, this); s.clear(); }else{ this.selections.clear(); } this.last = false; }, selectAll : function(){ if(this.locked) return; this.selections.clear(); for(var i = 0, len = this.grid.store.getCount(); i < len; i++){ this.selectRow(i, true); } }, hasSelection : function(){ return this.selections.length > 0; }, isSelected : function(index){ var r = typeof index == "number" ? this.grid.store.getAt(index) : index; return (r && this.selections.key(r.id) ? true : false); }, isIdSelected : function(id){ return (this.selections.key(id) ? true : false); }, handleMouseDown : function(g, rowIndex, e){ if(e.button !== 0 || this.isLocked()){ return; }; var view = this.grid.getView(); if(e.shiftKey && this.last !== false){ var last = this.last; this.selectRange(last, rowIndex, e.ctrlKey); this.last = last; view.focusRow(rowIndex); }else{ var isSelected = this.isSelected(rowIndex); if(e.ctrlKey && isSelected){ this.deselectRow(rowIndex); }else if(!isSelected || this.getCount() > 1){ this.selectRow(rowIndex, e.ctrlKey || e.shiftKey); view.focusRow(rowIndex); } } }, selectRows : function(rows, keepExisting){ if(!keepExisting){ this.clearSelections(); } for(var i = 0, len = rows.length; i < len; i++){ this.selectRow(rows[i], true); } }, selectRange : function(startRow, endRow, keepExisting){ if(this.locked) return; if(!keepExisting){ this.clearSelections(); } if(startRow <= endRow){ for(var i = startRow; i <= endRow; i++){ this.selectRow(i, true); } }else{ for(var i = startRow; i >= endRow; i--){ this.selectRow(i, true); } } }, deselectRange : function(startRow, endRow, preventViewNotify){ if(this.locked) return; for(var i = startRow; i <= endRow; i++){ this.deselectRow(i, preventViewNotify); } }, selectRow : function(index, keepExisting, preventViewNotify){ if(this.locked || (index < 0 || index >= this.grid.store.getCount())) return; var r = this.grid.store.getAt(index); if(r && this.fireEvent("beforerowselect", this, index, keepExisting, r) !== false){ if(!keepExisting || this.singleSelect){ this.clearSelections(); } this.selections.add(r); this.last = this.lastActive = index; if(!preventViewNotify){ this.grid.getView().onRowSelect(index); } this.fireEvent("rowselect", this, index, r); this.fireEvent("selectionchange", this); } }, deselectRow : function(index, preventViewNotify){ if(this.locked) return; if(this.last == index){ this.last = false; } if(this.lastActive == index){ this.lastActive = false; } var r = this.grid.store.getAt(index); if(r){ this.selections.remove(r); if(!preventViewNotify){ this.grid.getView().onRowDeselect(index); } this.fireEvent("rowdeselect", this, index, r); this.fireEvent("selectionchange", this); } }, restoreLast : function(){ if(this._last){ this.last = this._last; } }, acceptsNav : function(row, col, cm){ return !cm.isHidden(col) && cm.isCellEditable(col, row); }, onEditorKey : function(field, e){ var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor; var shift = e.shiftKey; if(k == e.TAB){ e.stopEvent(); ed.completeEdit(); if(shift){ newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this); }else{ newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this); } }else if(k == e.ENTER){ e.stopEvent(); ed.completeEdit(); if(this.moveEditorOnEnter !== false){ if(shift){ newCell = g.walkCells(ed.row - 1, ed.col, -1, this.acceptsNav, this); }else{ newCell = g.walkCells(ed.row + 1, ed.col, 1, this.acceptsNav, this); } } }else if(k == e.ESC){ ed.cancelEdit(); } if(newCell){ g.startEditing(newCell[0], newCell[1]); } } }); Ext.grid.CellSelectionModel = function(config){ Ext.apply(this, config); this.selection = null; this.addEvents( "beforecellselect", "cellselect", "selectionchange" ); Ext.grid.CellSelectionModel.superclass.constructor.call(this); }; Ext.extend(Ext.grid.CellSelectionModel, Ext.grid.AbstractSelectionModel, { initEvents : function(){ this.grid.on("cellmousedown", this.handleMouseDown, this); this.grid.getGridEl().on(Ext.isIE ? "keydown" : "keypress", this.handleKeyDown, this); var view = this.grid.view; view.on("refresh", this.onViewChange, this); view.on("rowupdated", this.onRowUpdated, this); view.on("beforerowremoved", this.clearSelections, this); view.on("beforerowsinserted", this.clearSelections, this); if(this.grid.isEditor){ this.grid.on("beforeedit", this.beforeEdit, this); } }, beforeEdit : function(e){ this.select(e.row, e.column, false, true, e.record); }, onRowUpdated : function(v, index, r){ if(this.selection && this.selection.record == r){ v.onCellSelect(index, this.selection.cell[1]); } }, onViewChange : function(){ this.clearSelections(true); }, getSelectedCell : function(){ return this.selection ? this.selection.cell : null; }, clearSelections : function(preventNotify){ var s = this.selection; if(s){ if(preventNotify !== true){ this.grid.view.onCellDeselect(s.cell[0], s.cell[1]); } this.selection = null; this.fireEvent("selectionchange", this, null); } }, hasSelection : function(){ return this.selection ? true : false; }, handleMouseDown : function(g, row, cell, e){ if(e.button !== 0 || this.isLocked()){ return; }; this.select(row, cell); }, select : function(rowIndex, colIndex, preventViewNotify, preventFocus, r){ if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){ this.clearSelections(); r = r || this.grid.store.getAt(rowIndex); this.selection = { record : r, cell : [rowIndex, colIndex] }; if(!preventViewNotify){ var v = this.grid.getView(); v.onCellSelect(rowIndex, colIndex); if(preventFocus !== true){ v.focusCell(rowIndex, colIndex); } } this.fireEvent("cellselect", this, rowIndex, colIndex); this.fireEvent("selectionchange", this, this.selection); } }, isSelectable : function(rowIndex, colIndex, cm){ return !cm.isHidden(colIndex); }, handleKeyDown : function(e){ if(!e.isNavKeyPress()){ return; } var g = this.grid, s = this.selection; if(!s){ e.stopEvent(); var cell = g.walkCells(0, 0, 1, this.isSelectable, this); if(cell){ this.select(cell[0], cell[1]); } return; } var sm = this; var walk = function(row, col, step){ return g.walkCells(row, col, step, sm.isSelectable, sm); }; var k = e.getKey(), r = s.cell[0], c = s.cell[1]; var newCell; switch(k){ case e.TAB: if(e.shiftKey){ newCell = walk(r, c-1, -1); }else{ newCell = walk(r, c+1, 1); } break; case e.DOWN: newCell = walk(r+1, c, 1); break; case e.UP: newCell = walk(r-1, c, -1); break; case e.RIGHT: newCell = walk(r, c+1, 1); break; case e.LEFT: newCell = walk(r, c-1, -1); break; case e.ENTER: if(g.isEditor && !g.editing){ g.startEditing(r, c); e.stopEvent(); return; } break; }; if(newCell){ this.select(newCell[0], newCell[1]); e.stopEvent(); } }, acceptsNav : function(row, col, cm){ return !cm.isHidden(col) && cm.isCellEditable(col, row); }, onEditorKey : function(field, e){ var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor; if(k == e.TAB){ if(e.shiftKey){ newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this); }else{ newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this); } e.stopEvent(); }else if(k == e.ENTER){ ed.completeEdit(); e.stopEvent(); }else if(k == e.ESC){ e.stopEvent(); ed.cancelEdit(); } if(newCell){ g.startEditing(newCell[0], newCell[1]); } } }); Ext.grid.EditorGridPanel = Ext.extend(Ext.grid.GridPanel, { clicksToEdit: 2, isEditor : true, detectEdit: false, autoEncode : false, trackMouseOver: false, initComponent : function(){ Ext.grid.EditorGridPanel.superclass.initComponent.call(this); if(!this.selModel){ this.selModel = new Ext.grid.CellSelectionModel(); } this.activeEditor = null; this.addEvents( "beforeedit", "afteredit", "validateedit" ); }, initEvents : function(){ Ext.grid.EditorGridPanel.superclass.initEvents.call(this); this.on("bodyscroll", this.stopEditing, this, [true]); if(this.clicksToEdit == 1){ this.on("cellclick", this.onCellDblClick, this); }else { if(this.clicksToEdit == 'auto' && this.view.mainBody){ this.view.mainBody.on("mousedown", this.onAutoEditClick, this); } this.on("celldblclick", this.onCellDblClick, this); } this.getGridEl().addClass("xedit-grid"); }, onCellDblClick : function(g, row, col){ this.startEditing(row, col); }, onAutoEditClick : function(e, t){ if(e.button !== 0){ return; } var row = this.view.findRowIndex(t); var col = this.view.findCellIndex(t); if(row !== false && col !== false){ this.stopEditing(); if(this.selModel.getSelectedCell){ var sc = this.selModel.getSelectedCell(); if(sc && sc.cell[0] === row && sc.cell[1] === col){ this.startEditing(row, col); } }else{ if(this.selModel.isSelected(row)){ this.startEditing(row, col); } } } }, onEditComplete : function(ed, value, startValue){ this.editing = false; this.activeEditor = null; ed.un("specialkey", this.selModel.onEditorKey, this.selModel); var r = ed.record; var field = this.colModel.getDataIndex(ed.col); value = this.postEditValue(value, startValue, r, field); if(String(value) !== String(startValue)){ var e = { grid: this, record: r, field: field, originalValue: startValue, value: value, row: ed.row, column: ed.col, cancel:false }; if(this.fireEvent("validateedit", e) !== false && !e.cancel){ r.set(field, e.value); delete e.cancel; this.fireEvent("afteredit", e); } } this.view.focusCell(ed.row, ed.col); }, startEditing : function(row, col){ this.stopEditing(); if(this.colModel.isCellEditable(col, row)){ this.view.ensureVisible(row, col, true); var r = this.store.getAt(row); var field = this.colModel.getDataIndex(col); var e = { grid: this, record: r, field: field, value: r.data[field], row: row, column: col, cancel:false }; if(this.fireEvent("beforeedit", e) !== false && !e.cancel){ this.editing = true; var ed = this.colModel.getCellEditor(col, row); if(!ed.rendered){ ed.render(this.view.getEditorParent(ed)); } (function(){ ed.row = row; ed.col = col; ed.record = r; ed.on("complete", this.onEditComplete, this, {single: true}); ed.on("specialkey", this.selModel.onEditorKey, this.selModel); this.activeEditor = ed; var v = this.preEditValue(r, field); ed.startEdit(this.view.getCell(row, col), v); }).defer(50, this); } } }, preEditValue : function(r, field){ return this.autoEncode && typeof value == 'string' ? Ext.util.Format.htmlDecode(r.data[field]) : r.data[field]; }, postEditValue : function(value, originalValue, r, field){ return this.autoEncode && typeof value == 'string' ? Ext.util.Format.htmlEncode(value) : value; }, stopEditing : function(cancel){ if(this.activeEditor){ this.activeEditor[cancel === true ? 'cancelEdit' : 'completeEdit'](); } this.activeEditor = null; } }); Ext.reg('editorgrid', Ext.grid.EditorGridPanel); Ext.grid.GridEditor = function(field, config){ Ext.grid.GridEditor.superclass.constructor.call(this, field, config); field.monitorTab = false; }; Ext.extend(Ext.grid.GridEditor, Ext.Editor, { alignment: "tl-tl", autoSize: "width", hideEl : false, cls: "x-small-editor x-grid-editor", shim:false, shadow:false }); Ext.grid.PropertyRecord = Ext.data.Record.create([ {name:'name',type:'string'}, 'value' ]); Ext.grid.PropertyStore = function(grid, source){ this.grid = grid; this.store = new Ext.data.Store({ recordType : Ext.grid.PropertyRecord }); this.store.on('update', this.onUpdate, this); if(source){ this.setSource(source); } Ext.grid.PropertyStore.superclass.constructor.call(this); }; Ext.extend(Ext.grid.PropertyStore, Ext.util.Observable, { setSource : function(o){ this.source = o; this.store.removeAll(); var data = []; for(var k in o){ if(this.isEditableValue(o[k])){ data.push(new Ext.grid.PropertyRecord({name: k, value: o[k]}, k)); } } this.store.loadRecords({records: data}, {}, true); }, onUpdate : function(ds, record, type){ if(type == Ext.data.Record.EDIT){ var v = record.data['value']; var oldValue = record.modified['value']; if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){ this.source[record.id] = v; record.commit(); this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue); }else{ record.reject(); } } }, getProperty : function(row){ return this.store.getAt(row); }, isEditableValue: function(val){ if(Ext.isDate(val)){ return true; }else if(typeof val == 'object' || typeof val == 'function'){ return false; } return true; }, setValue : function(prop, value){ this.source[prop] = value; this.store.getById(prop).set('value', value); }, getSource : function(){ return this.source; } }); Ext.grid.PropertyColumnModel = function(grid, store){ this.grid = grid; var g = Ext.grid; g.PropertyColumnModel.superclass.constructor.call(this, [ {header: this.nameText, width:50, sortable: true, dataIndex:'name', id: 'name', menuDisabled:true}, {header: this.valueText, width:50, resizable:false, dataIndex: 'value', id: 'value', menuDisabled:true} ]); this.store = store; this.bselect = Ext.DomHelper.append(document.body, { tag: 'select', cls: 'x-grid-editor x-hide-display', children: [ {tag: 'option', value: 'true', html: 'true'}, {tag: 'option', value: 'false', html: 'false'} ] }); var f = Ext.form; var bfield = new f.Field({ el:this.bselect, bselect : this.bselect, autoShow: true, getValue : function(){ return this.bselect.value == 'true'; } }); this.editors = { 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})), 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})), 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})), 'boolean' : new g.GridEditor(bfield) }; this.renderCellDelegate = this.renderCell.createDelegate(this); this.renderPropDelegate = this.renderProp.createDelegate(this); }; Ext.extend(Ext.grid.PropertyColumnModel, Ext.grid.ColumnModel, { nameText : 'Name', valueText : 'Value', dateFormat : 'm/j/Y', renderDate : function(dateVal){ return dateVal.dateFormat(this.dateFormat); }, renderBool : function(bVal){ return bVal ? 'true' : 'false'; }, isCellEditable : function(colIndex, rowIndex){ return colIndex == 1; }, getRenderer : function(col){ return col == 1 ? this.renderCellDelegate : this.renderPropDelegate; }, renderProp : function(v){ return this.getPropertyName(v); }, renderCell : function(val){ var rv = val; if(Ext.isDate(val)){ rv = this.renderDate(val); }else if(typeof val == 'boolean'){ rv = this.renderBool(val); } return Ext.util.Format.htmlEncode(rv); }, getPropertyName : function(name){ var pn = this.grid.propertyNames; return pn && pn[name] ? pn[name] : name; }, getCellEditor : function(colIndex, rowIndex){ var p = this.store.getProperty(rowIndex); var n = p.data['name'], val = p.data['value']; if(this.grid.customEditors[n]){ return this.grid.customEditors[n]; } if(Ext.isDate(val)){ return this.editors['date']; }else if(typeof val == 'number'){ return this.editors['number']; }else if(typeof val == 'boolean'){ return this.editors['boolean']; }else{ return this.editors['string']; } } }); Ext.grid.PropertyGrid = Ext.extend(Ext.grid.EditorGridPanel, { enableColumnMove:false, stripeRows:false, trackMouseOver: false, clicksToEdit:1, enableHdMenu : false, viewConfig : { forceFit:true }, initComponent : function(){ this.customEditors = this.customEditors || {}; this.lastEditRow = null; var store = new Ext.grid.PropertyStore(this); this.propStore = store; var cm = new Ext.grid.PropertyColumnModel(this, store); store.store.sort('name', 'ASC'); this.addEvents( 'beforepropertychange', 'propertychange' ); this.cm = cm; this.ds = store.store; Ext.grid.PropertyGrid.superclass.initComponent.call(this); this.selModel.on('beforecellselect', function(sm, rowIndex, colIndex){ if(colIndex === 0){ this.startEditing.defer(200, this, [rowIndex, 1]); return false; } }, this); }, onRender : function(){ Ext.grid.PropertyGrid.superclass.onRender.apply(this, arguments); this.getGridEl().addClass('x-props-grid'); }, afterRender: function(){ Ext.grid.PropertyGrid.superclass.afterRender.apply(this, arguments); if(this.source){ this.setSource(this.source); } }, setSource : function(source){ this.propStore.setSource(source); }, getSource : function(){ return this.propStore.getSource(); } }); Ext.grid.RowNumberer = function(config){ Ext.apply(this, config); if(this.rowspan){ this.renderer = this.renderer.createDelegate(this); } }; Ext.grid.RowNumberer.prototype = { header: "", width: 23, sortable: false, fixed:true, menuDisabled:true, dataIndex: '', id: 'numberer', rowspan: undefined, renderer : function(v, p, record, rowIndex){ if(this.rowspan){ p.cellAttr = 'rowspan="'+this.rowspan+'"'; } return rowIndex+1; } }; Ext.grid.CheckboxSelectionModel = Ext.extend(Ext.grid.RowSelectionModel, { header: '<div class="x-grid3-hd-checker">&#160;</div>', width: 20, sortable: false, menuDisabled:true, fixed:true, dataIndex: '', id: 'checker', initEvents : function(){ Ext.grid.CheckboxSelectionModel.superclass.initEvents.call(this); this.grid.on('render', function(){ var view = this.grid.getView(); view.mainBody.on('mousedown', this.onMouseDown, this); Ext.fly(view.innerHd).on('mousedown', this.onHdMouseDown, this); }, this); }, onMouseDown : function(e, t){ if(e.button === 0 && t.className == 'x-grid3-row-checker'){ e.stopEvent(); var row = e.getTarget('.x-grid3-row'); if(row){ var index = row.rowIndex; if(this.isSelected(index)){ this.deselectRow(index); }else{ this.selectRow(index, true); } } } }, onHdMouseDown : function(e, t){ if(t.className == 'x-grid3-hd-checker'){ e.stopEvent(); var hd = Ext.fly(t.parentNode); var isChecked = hd.hasClass('x-grid3-hd-checker-on'); if(isChecked){ hd.removeClass('x-grid3-hd-checker-on'); this.clearSelections(); }else{ hd.addClass('x-grid3-hd-checker-on'); this.selectAll(); } } }, renderer : function(v, p, record){ return '<div class="x-grid3-row-checker">&#160;</div>'; } }); Ext.LoadMask = function(el, config){ this.el = Ext.get(el); Ext.apply(this, config); if(this.store){ this.store.on('beforeload', this.onBeforeLoad, this); this.store.on('load', this.onLoad, this); this.store.on('loadexception', this.onLoad, this); this.removeMask = Ext.value(this.removeMask, false); }else{ var um = this.el.getUpdater(); um.showLoadIndicator = false; um.on('beforeupdate', this.onBeforeLoad, this); um.on('update', this.onLoad, this); um.on('failure', this.onLoad, this); this.removeMask = Ext.value(this.removeMask, true); } }; Ext.LoadMask.prototype = { msg : 'Loading...', msgCls : 'x-mask-loading', disabled: false, disable : function(){ this.disabled = true; }, enable : function(){ this.disabled = false; }, onLoad : function(){ this.el.unmask(this.removeMask); }, onBeforeLoad : function(){ if(!this.disabled){ this.el.mask(this.msg, this.msgCls); } }, show: function(){ this.onBeforeLoad(); }, hide: function(){ this.onLoad(); }, destroy : function(){ if(this.store){ this.store.un('beforeload', this.onBeforeLoad, this); this.store.un('load', this.onLoad, this); this.store.un('loadexception', this.onLoad, this); }else{ var um = this.el.getUpdater(); um.un('beforeupdate', this.onBeforeLoad, this); um.un('update', this.onLoad, this); um.un('failure', this.onLoad, this); } } }; Ext.ProgressBar = Ext.extend(Ext.BoxComponent, { baseCls : 'x-progress', waitTimer : null, initComponent : function(){ Ext.ProgressBar.superclass.initComponent.call(this); this.addEvents( "update" ); }, onRender : function(ct, position){ Ext.ProgressBar.superclass.onRender.call(this, ct, position); var tpl = new Ext.Template( '<div class="{cls}-wrap">', '<div class="{cls}-inner">', '<div class="{cls}-bar">', '<div class="{cls}-text">', '<div>&#160;</div>', '</div>', '</div>', '<div class="{cls}-text {cls}-text-back">', '<div>&#160;</div>', '</div>', '</div>', '</div>' ); if(position){ this.el = tpl.insertBefore(position, {cls: this.baseCls}, true); }else{ this.el = tpl.append(ct, {cls: this.baseCls}, true); } if(this.id){ this.el.dom.id = this.id; } var inner = this.el.dom.firstChild; this.progressBar = Ext.get(inner.firstChild); if(this.textEl){ this.textEl = Ext.get(this.textEl); delete this.textTopEl; }else{ this.textTopEl = Ext.get(this.progressBar.dom.firstChild); var textBackEl = Ext.get(inner.childNodes[1]); this.textTopEl.setStyle("z-index", 99).addClass('x-hidden'); this.textEl = new Ext.CompositeElement([this.textTopEl.dom.firstChild, textBackEl.dom.firstChild]); this.textEl.setWidth(inner.offsetWidth); } if(this.value){ this.updateProgress(this.value, this.text); }else{ this.updateText(this.text); } this.setSize(this.width || 'auto', 'auto'); this.progressBar.setHeight(inner.offsetHeight); }, updateProgress : function(value, text){ this.value = value || 0; if(text){ this.updateText(text); } var w = Math.floor(value*this.el.dom.firstChild.offsetWidth); this.progressBar.setWidth(w); if(this.textTopEl){ this.textTopEl.removeClass('x-hidden').setWidth(w); } this.fireEvent('update', this, value, text); return this; }, wait : function(o){ if(!this.waitTimer){ var scope = this; o = o || {}; this.waitTimer = Ext.TaskMgr.start({ run: function(i){ var inc = o.increment || 10; this.updateProgress(((((i+inc)%inc)+1)*(100/inc))*.01); }, interval: o.interval || 1000, duration: o.duration, onStop: function(){ if(o.fn){ o.fn.apply(o.scope || this); } this.reset(); }, scope: scope }); } return this; }, isWaiting : function(){ return this.waitTimer != null; }, updateText : function(text){ this.text = text || '&#160;'; this.textEl.update(this.text); return this; }, setSize : function(w, h){ Ext.ProgressBar.superclass.setSize.call(this, w, h); if(this.textTopEl){ var inner = this.el.dom.firstChild; this.textEl.setSize(inner.offsetWidth, inner.offsetHeight); } return this; }, reset : function(hide){ this.updateProgress(0); if(this.textTopEl){ this.textTopEl.addClass('x-hidden'); } if(this.waitTimer){ this.waitTimer.onStop = null; Ext.TaskMgr.stop(this.waitTimer); this.waitTimer = null; } if(hide === true){ this.hide(); } return this; } }); Ext.reg('progress', Ext.ProgressBar); Ext.debug = {}; (function(){ var cp; function createConsole(){ var scriptPanel = new Ext.debug.ScriptsPanel(); var logView = new Ext.debug.LogPanel(); var tree = new Ext.debug.DomTree(); var tabs = new Ext.TabPanel({ activeTab: 0, border: false, tabPosition: 'bottom', items: [{ title: 'Debug Console', layout:'border', items: [logView, scriptPanel] },{ title: 'DOM Inspector', layout:'border', items: [tree] }] }); cp = new Ext.Panel({ id: 'x-debug-browser', title: 'Console', collapsible: true, animCollapse: false, style: 'position:absolute;left:0;bottom:0;', height:200, logView: logView, layout: 'fit', tools:[{ id: 'close', handler: function(){ cp.destroy(); cp = null; Ext.EventManager.removeResizeListener(handleResize); } }], items: tabs }); cp.render(document.body); cp.resizer = new Ext.Resizable(cp.el, { minHeight:50, handles: "n", pinned: true, transparent:true, resizeElement : function(){ var box = this.proxy.getBox(); this.proxy.hide(); cp.setHeight(box.height); return box; } }); function handleResize(){ cp.setWidth(Ext.getBody().getViewSize().width); } Ext.EventManager.onWindowResize(handleResize); handleResize(); } Ext.apply(Ext, { log : function(){ if(!cp){ createConsole(); } cp.logView.log.apply(cp.logView, arguments); }, logf : function(format, arg1, arg2, etc){ Ext.log(String.format.apply(String, arguments)); }, dump : function(o){ if(typeof o == 'string' || typeof o == 'number' || typeof o == 'undefined' || Ext.isDate(o)){ Ext.log(o); }else if(!o){ Ext.log("null"); }else if(typeof o != "object"){ Ext.log('Unknown return type'); }else if(Ext.isArray(o)){ Ext.log('['+o.join(',')+']'); }else{ var b = ["{\n"]; for(var key in o){ var to = typeof o[key]; if(to != "function" && to != "object"){ b.push(String.format(" {0}: {1},\n", key, o[key])); } } var s = b.join(""); if(s.length > 3){ s = s.substr(0, s.length-2); } Ext.log(s + "\n}"); } }, _timers : {}, time : function(name){ name = name || "def"; Ext._timers[name] = new Date().getTime(); }, timeEnd : function(name, printResults){ var t = new Date().getTime(); name = name || "def"; var v = String.format("{0} ms", t-Ext._timers[name]); Ext._timers[name] = new Date().getTime(); if(printResults !== false){ Ext.log('Timer ' + (name == "def" ? v : name + ": " + v)); } return v; } }); })(); Ext.debug.ScriptsPanel = Ext.extend(Ext.Panel, { id:'x-debug-scripts', region: 'east', minWidth: 200, split: true, width: 350, border: false, layout:'anchor', style:'border-width:0 0 0 1px;', initComponent : function(){ this.scriptField = new Ext.form.TextArea({ anchor: '100% -26', style:'border-width:0;' }); this.trapBox = new Ext.form.Checkbox({ id: 'console-trap', boxLabel: 'Trap Errors', checked: true }); this.toolbar = new Ext.Toolbar([{ text: 'Run', scope: this, handler: this.evalScript },{ text: 'Clear', scope: this, handler: this.clear }, '->', this.trapBox, ' ', ' ' ]); this.items = [this.toolbar, this.scriptField]; Ext.debug.ScriptsPanel.superclass.initComponent.call(this); }, evalScript : function(){ var s = this.scriptField.getValue(); if(this.trapBox.getValue()){ try{ var rt = eval(s); Ext.dump(rt === undefined? '(no return)' : rt); }catch(e){ Ext.log(e.message || e.descript); } }else{ var rt = eval(s); Ext.dump(rt === undefined? '(no return)' : rt); } }, clear : function(){ this.scriptField.setValue(''); this.scriptField.focus(); } }); Ext.debug.LogPanel = Ext.extend(Ext.Panel, { autoScroll: true, region: 'center', border: false, style:'border-width:0 1px 0 0', log : function(){ var markup = [ '<div style="padding:5px !important;border-bottom:1px solid #ccc;">', Ext.util.Format.htmlEncode(Array.prototype.join.call(arguments, ', ')).replace(/\n/g, '<br />').replace(/\s/g, '&#160;'), '</div>'].join(''); this.body.insertHtml('beforeend', markup); this.body.scrollTo('top', 100000); }, clear : function(){ this.body.update(''); this.body.dom.scrollTop = 0; } }); Ext.debug.DomTree = Ext.extend(Ext.tree.TreePanel, { enableDD:false , lines:false, rootVisible:false, animate:false, hlColor:'ffff9c', autoScroll: true, region:'center', border:false, initComponent : function(){ Ext.debug.DomTree.superclass.initComponent.call(this); var styles = false, hnode; var nonSpace = /^\s*$/; var html = Ext.util.Format.htmlEncode; var ellipsis = Ext.util.Format.ellipsis; var styleRe = /\s?([a-z\-]*)\:([^;]*)(?:[;\s\n\r]*)/gi; function findNode(n){ if(!n || n.nodeType != 1 || n == document.body || n == document){ return false; } var pn = [n], p = n; while((p = p.parentNode) && p.nodeType == 1 && p.tagName.toUpperCase() != 'HTML'){ pn.unshift(p); } var cn = hnode; for(var i = 0, len = pn.length; i < len; i++){ cn.expand(); cn = cn.findChild('htmlNode', pn[i]); if(!cn){ return false; } } cn.select(); var a = cn.ui.anchor; treeEl.dom.scrollTop = Math.max(0 ,a.offsetTop-10); cn.highlight(); return true; } function nodeTitle(n){ var s = n.tagName; if(n.id){ s += '#'+n.id; }else if(n.className){ s += '.'+n.className; } return s; } function onNodeSelect(t, n, last){ return; if(last && last.unframe){ last.unframe(); } var props = {}; if(n && n.htmlNode){ if(frameEl.pressed){ n.frame(); } if(inspecting){ return; } addStyle.enable(); reload.setDisabled(n.leaf); var dom = n.htmlNode; stylePanel.setTitle(nodeTitle(dom)); if(styles && !showAll.pressed){ var s = dom.style ? dom.style.cssText : ''; if(s){ var m; while ((m = styleRe.exec(s)) != null){ props[m[1].toLowerCase()] = m[2]; } } }else if(styles){ var cl = Ext.debug.cssList; var s = dom.style, fly = Ext.fly(dom); if(s){ for(var i = 0, len = cl.length; i<len; i++){ var st = cl[i]; var v = s[st] || fly.getStyle(st); if(v != undefined && v !== null && v !== ''){ props[st] = v; } } } }else{ for(var a in dom){ var v = dom[a]; if((isNaN(a+10)) && v != undefined && v !== null && v !== '' && !(Ext.isGecko && a[0] == a[0].toUpperCase())){ props[a] = v; } } } }else{ if(inspecting){ return; } addStyle.disable(); reload.disabled(); } stylesGrid.setSource(props); stylesGrid.treeNode = n; stylesGrid.view.fitColumns(); } this.loader = new Ext.tree.TreeLoader(); this.loader.load = function(n, cb){ var isBody = n.htmlNode == document.body; var cn = n.htmlNode.childNodes; for(var i = 0, c; c = cn[i]; i++){ if(isBody && c.id == 'x-debug-browser'){ continue; } if(c.nodeType == 1){ n.appendChild(new Ext.debug.HtmlNode(c)); }else if(c.nodeType == 3 && !nonSpace.test(c.nodeValue)){ n.appendChild(new Ext.tree.TreeNode({ text:'<em>' + ellipsis(html(String(c.nodeValue)), 35) + '</em>', cls: 'x-tree-noicon' })); } } cb(); }; this.root = this.setRootNode(new Ext.tree.TreeNode('Ext')); hnode = this.root.appendChild(new Ext.debug.HtmlNode( document.getElementsByTagName('html')[0] )); } }); Ext.debug.HtmlNode = function(){ var html = Ext.util.Format.htmlEncode; var ellipsis = Ext.util.Format.ellipsis; var nonSpace = /^\s*$/; var attrs = [ {n: 'id', v: 'id'}, {n: 'className', v: 'class'}, {n: 'name', v: 'name'}, {n: 'type', v: 'type'}, {n: 'src', v: 'src'}, {n: 'href', v: 'href'} ]; function hasChild(n){ for(var i = 0, c; c = n.childNodes[i]; i++){ if(c.nodeType == 1){ return true; } } return false; } function renderNode(n, leaf){ var tag = n.tagName.toLowerCase(); var s = '&lt;' + tag; for(var i = 0, len = attrs.length; i < len; i++){ var a = attrs[i]; var v = n[a.n]; if(v && !nonSpace.test(v)){ s += ' ' + a.v + '=&quot;<i>' + html(v) +'</i>&quot;'; } } var style = n.style ? n.style.cssText : ''; if(style){ s += ' style=&quot;<i>' + html(style.toLowerCase()) +'</i>&quot;'; } if(leaf && n.childNodes.length > 0){ s+='&gt;<em>' + ellipsis(html(String(n.innerHTML)), 35) + '</em>&lt;/'+tag+'&gt;'; }else if(leaf){ s += ' /&gt;'; }else{ s += '&gt;'; } return s; } var HtmlNode = function(n){ var leaf = !hasChild(n); this.htmlNode = n; this.tagName = n.tagName.toLowerCase(); var attr = { text : renderNode(n, leaf), leaf : leaf, cls: 'x-tree-noicon' }; HtmlNode.superclass.constructor.call(this, attr); this.attributes.htmlNode = n; if(!leaf){ this.on('expand', this.onExpand, this); this.on('collapse', this.onCollapse, this); } }; Ext.extend(HtmlNode, Ext.tree.AsyncTreeNode, { cls: 'x-tree-noicon', preventHScroll: true, refresh : function(highlight){ var leaf = !hasChild(this.htmlNode); this.setText(renderNode(this.htmlNode, leaf)); if(highlight){ Ext.fly(this.ui.textNode).highlight(); } }, onExpand : function(){ if(!this.closeNode && this.parentNode){ this.closeNode = this.parentNode.insertBefore(new Ext.tree.TreeNode({ text:'&lt;/' + this.tagName + '&gt;', cls: 'x-tree-noicon' }), this.nextSibling); }else if(this.closeNode){ this.closeNode.ui.show(); } }, onCollapse : function(){ if(this.closeNode){ this.closeNode.ui.hide(); } }, render : function(bulkRender){ HtmlNode.superclass.render.call(this, bulkRender); }, highlightNode : function(){ }, highlight : function(){ }, frame : function(){ this.htmlNode.style.border = '1px solid #0000ff'; }, unframe : function(){ this.htmlNode.style.border = ''; } }); return HtmlNode; }();
app/containers/HomePageIconListItem/index.js
interra/data-generate
/** * RepoListItem * * Lists the name and the issue count of a repository */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import ListItem from 'components/ListItem'; import Wrapper from './Wrapper'; import StyledLink from './StyledLink'; export class HomePageIconListItem extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { const item = this.props.item; const columnWidth = item.columnWidth; const click = item.click; // Put together the content of the repository const content = ( <StyledLink to="search" onClick={click}> <div data-facet-name={item.title} className={`font-icon-select-1 font-icon-select-1-${item.icon}`}></div> <div data-facet-name={item.title}>{item.title}</div> </StyledLink> ); // Render the content into a list item return ( <Wrapper key={item.ref} className={`col-xs-12 col-sm-6 col-md-${item.columnWidth}`}>{content}</Wrapper> ); } } HomePageIconListItem.propTypes = { item: PropTypes.object, }; export default connect()(HomePageIconListItem);
test/containers/CounterPage.spec.js
merklelabs/SlickIRC
import { expect } from 'chai' import React from 'react' import { renderIntoDocument, scryRenderedDOMComponentsWithTag, findRenderedDOMComponentWithClass, Simulate } from 'react-addons-test-utils' import { Provider } from 'react-redux' import CounterPage from '../../app/containers/CounterPage' import configureStore from '../../app/store/configureStore' function setup(initialState) { const store = configureStore(initialState) const app = renderIntoDocument( <Provider store={store}> <CounterPage /> </Provider> ) return { app: app, buttons: scryRenderedDOMComponentsWithTag(app, 'button').map(button => { return button }), p: findRenderedDOMComponentWithClass(app, 'counter') } } describe('containers', () => { describe('App', () => { it('should display initial count', () => { const { p } = setup() expect(p.textContent).to.match(/^0$/) }) it('should display updated count after increment button click', () => { const { buttons, p } = setup() Simulate.click(buttons[0]) expect(p.textContent).to.match(/^1$/) }) it('should display updated count after descrement button click', () => { const { buttons, p } = setup() Simulate.click(buttons[1]) expect(p.textContent).to.match(/^-1$/) }) it('shouldnt change if even and if odd button clicked', () => { const { buttons, p } = setup() Simulate.click(buttons[2]) expect(p.textContent).to.match(/^0$/) }) it('should change if odd and if odd button clicked', () => { const { buttons, p } = setup({ counter: 1 }) Simulate.click(buttons[2]) expect(p.textContent).to.match(/^2$/) }) }) })
packages/material-ui-icons/src/QueuePlayNext.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h2v-2H3V5h18v8h2V5c0-1.11-.9-2-2-2zm-8 7V7h-2v3H8v2h3v3h2v-3h3v-2h-3zm11 8l-4.5 4.5L18 21l3-3-3-3 1.5-1.5L24 18z" /></g> , 'QueuePlayNext');
ajax/libs/angular-data/0.5.0/angular-data.js
calvinf/cdnjs
/** * @author Jason Dobry <jason.dobry@gmail.com> * @file angular-data.js * @version 0.5.0 - Homepage <http://jmdobry.github.io/angular-data/> * @copyright (c) 2014 Jason Dobry <https://github.com/jmdobry/angular-data> * @license MIT <https://github.com/jmdobry/angular-data/blob/master/LICENSE> * * @overview Data store for Angular.js. */ require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"u+GZEJ":[function(require,module,exports){ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};// Copyright 2012 Google 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(global) { 'use strict'; function detectObjectObserve() { if (typeof Object.observe !== 'function' || typeof Array.observe !== 'function') { return false; } var gotSplice = false; function callback(records) { if (records[0].type === 'splice' && records[1].type === 'splice') gotSplice = true; } var test = [0]; Array.observe(test, callback); test[1] = 1; test.length = 0; Object.deliverChangeRecords(callback); return gotSplice; } var hasObserve = detectObjectObserve(); var hasEval = false; try { var f = new Function('', 'return true;'); hasEval = f(); } catch (ex) { } function isObject(obj) { return obj === Object(obj); } var numberIsNaN = global.Number.isNaN || function isNaN(value) { return typeof value === 'number' && global.isNaN(value); } var createObject = ('__proto__' in {}) ? function(obj) { return obj; } : function(obj) { var proto = obj.__proto__; if (!proto) return obj; var newObject = Object.create(proto); Object.getOwnPropertyNames(obj).forEach(function(name) { Object.defineProperty(newObject, name, Object.getOwnPropertyDescriptor(obj, name)); }); return newObject; }; var MAX_DIRTY_CHECK_CYCLES = 1000; function dirtyCheck(observer) { var cycles = 0; while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check()) { observer.report(); cycles++; } } function objectIsEmpty(object) { for (var prop in object) return false; return true; } function diffIsEmpty(diff) { return objectIsEmpty(diff.added) && objectIsEmpty(diff.removed) && objectIsEmpty(diff.changed); } function diffObjectFromOldObject(object, oldObject) { var added = {}; var removed = {}; var changed = {}; var oldObjectHas = {}; for (var prop in oldObject) { var newValue = object[prop]; if (newValue !== undefined && newValue === oldObject[prop]) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop in object) { if (prop in oldObject) continue; added[prop] = object[prop]; } if (Array.isArray(object) && object.length !== oldObject.length) changed.length = object.length; return { added: added, removed: removed, changed: changed }; } function copyObject(object, opt_copy) { var copy = opt_copy || (Array.isArray(object) ? [] : {}); for (var prop in object) { copy[prop] = object[prop]; }; if (Array.isArray(object)) copy.length = object.length; return copy; } function Observer(object, callback, target, token) { this.closed = false; this.object = object; this.callback = callback; // TODO(rafaelw): Hold this.target weakly when WeakRef is available. this.target = target; this.token = token; this.reporting = true; if (hasObserve) { var self = this; this.boundInternalCallback = function(records) { self.internalCallback(records); }; } addToAll(this); this.connect(); this.sync(true); } Observer.prototype = { internalCallback: function(records) { if (this.closed) return; if (this.reporting && this.check(records)) { this.report(); if (this.testingResults) this.testingResults.anyChanged = true; } }, close: function() { if (this.closed) return; if (this.object && typeof this.object.unobserved === 'function') this.object.unobserved(); this.disconnect(); this.object = undefined; this.closed = true; }, deliver: function(testingResults) { if (this.closed) return; if (hasObserve) { this.testingResults = testingResults; Object.deliverChangeRecords(this.boundInternalCallback); this.testingResults = undefined; } else { dirtyCheck(this); } }, report: function() { if (!this.reporting) return; this.sync(false); this.reportArgs.push(this.token); this.invokeCallback(this.reportArgs); this.reportArgs = undefined; }, invokeCallback: function(args) { try { this.callback.apply(this.target, args); } catch (ex) { Observer._errorThrownDuringCallback = true; console.error('Exception caught during observer callback: ' + ex); } }, reset: function() { if (this.closed) return; if (hasObserve) { this.reporting = false; Object.deliverChangeRecords(this.boundInternalCallback); this.reporting = true; } this.sync(true); } } var collectObservers = !hasObserve || global.forceCollectObservers; var allObservers; Observer._allObserversCount = 0; if (collectObservers) { allObservers = []; } function addToAll(observer) { if (!collectObservers) return; allObservers.push(observer); Observer._allObserversCount++; } var runningMicrotaskCheckpoint = false; var hasDebugForceFullDelivery = typeof Object.deliverAllChangeRecords == 'function'; global.Platform = global.Platform || {}; global.Platform.performMicrotaskCheckpoint = function() { if (runningMicrotaskCheckpoint) return; if (hasDebugForceFullDelivery) { Object.deliverAllChangeRecords(); return; } if (!collectObservers) return; runningMicrotaskCheckpoint = true; var cycles = 0; var results = {}; do { cycles++; var toCheck = allObservers; allObservers = []; results.anyChanged = false; for (var i = 0; i < toCheck.length; i++) { var observer = toCheck[i]; if (observer.closed) continue; if (hasObserve) { observer.deliver(results); } else if (observer.check()) { results.anyChanged = true; observer.report(); } allObservers.push(observer); } } while (cycles < MAX_DIRTY_CHECK_CYCLES && results.anyChanged); Observer._allObserversCount = allObservers.length; runningMicrotaskCheckpoint = false; }; if (collectObservers) { global.Platform.clearObservers = function() { allObservers = []; }; } function ObjectObserver(object, callback, target, token) { Observer.call(this, object, callback, target, token); } ObjectObserver.prototype = createObject({ __proto__: Observer.prototype, connect: function() { if (hasObserve) Object.observe(this.object, this.boundInternalCallback); }, sync: function(hard) { if (!hasObserve) this.oldObject = copyObject(this.object); }, check: function(changeRecords) { var diff; var oldValues; if (hasObserve) { if (!changeRecords) return false; oldValues = {}; diff = diffObjectFromChangeRecords(this.object, changeRecords, oldValues); } else { oldValues = this.oldObject; diff = diffObjectFromOldObject(this.object, this.oldObject); } if (diffIsEmpty(diff)) return false; this.reportArgs = [diff.added || {}, diff.removed || {}, diff.changed || {}]; this.reportArgs.push(function(property) { return oldValues[property]; }); return true; }, disconnect: function() { if (!hasObserve) this.oldObject = undefined; else if (this.object) Object.unobserve(this.object, this.boundInternalCallback); } }); function ObservedSet(callback) { this.arr = []; this.callback = callback; this.isObserved = true; } var objProto = Object.getPrototypeOf({}); var arrayProto = Object.getPrototypeOf([]); ObservedSet.prototype = { reset: function() { this.isObserved = !this.isObserved; }, observe: function(obj) { if (!isObject(obj) || obj === objProto || obj === arrayProto) return; var i = this.arr.indexOf(obj); if (i >= 0 && this.arr[i+1] === this.isObserved) return; if (i < 0) { i = this.arr.length; this.arr[i] = obj; Object.observe(obj, this.callback); } this.arr[i+1] = this.isObserved; this.observe(Object.getPrototypeOf(obj)); }, cleanup: function() { var i = 0, j = 0; var isObserved = this.isObserved; while(j < this.arr.length) { var obj = this.arr[j]; if (this.arr[j + 1] == isObserved) { if (i < j) { this.arr[i] = obj; this.arr[i + 1] = isObserved; } i += 2; } else { Object.unobserve(obj, this.callback); } j += 2; } this.arr.length = i; } }; var knownRecordTypes = { 'new': true, 'updated': true, 'deleted': true }; function diffObjectFromChangeRecords(object, changeRecords, oldValues) { var added = {}; var removed = {}; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; if (!knownRecordTypes[record.type]) { console.error('Unknown changeRecord type: ' + record.type); console.error(record); continue; } if (!(record.name in oldValues)) oldValues[record.name] = record.oldValue; if (record.type == 'updated') continue; if (record.type == 'new') { if (record.name in removed) delete removed[record.name]; else added[record.name] = true; continue; } // type = 'deleted' if (record.name in added) { delete added[record.name]; delete oldValues[record.name]; } else { removed[record.name] = true; } } for (var prop in added) added[prop] = object[prop]; for (var prop in removed) removed[prop] = undefined; var changed = {}; for (var prop in oldValues) { if (prop in added || prop in removed) continue; var newValue = object[prop]; if (oldValues[prop] !== newValue) changed[prop] = newValue; } return { added: added, removed: removed, changed: changed }; } global.Observer = Observer; global.Observer.hasObjectObserve = hasObserve; global.ObjectObserver = ObjectObserver; })((exports.Number = { isNaN: window.isNaN }) ? exports : exports); },{}],"observejs":[function(require,module,exports){ module.exports=require('u+GZEJ'); },{}],3:[function(require,module,exports){ var indexOf = require('./indexOf'); /** * If array contains values. */ function contains(arr, val) { return indexOf(arr, val) !== -1; } module.exports = contains; },{"./indexOf":5}],4:[function(require,module,exports){ var makeIterator = require('../function/makeIterator_'); /** * Array filter */ function filter(arr, callback, thisObj) { callback = makeIterator(callback, thisObj); var results = []; if (arr == null) { return results; } var i = -1, len = arr.length, value; while (++i < len) { value = arr[i]; if (callback(value, i, arr)) { results.push(value); } } return results; } module.exports = filter; },{"../function/makeIterator_":11}],5:[function(require,module,exports){ /** * Array.indexOf */ function indexOf(arr, item, fromIndex) { fromIndex = fromIndex || 0; if (arr == null) { return -1; } var len = arr.length, i = fromIndex < 0 ? len + fromIndex : fromIndex; while (i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if (arr[i] === item) { return i; } i++; } return -1; } module.exports = indexOf; },{}],6:[function(require,module,exports){ var filter = require('./filter'); function isValidString(val) { return (val != null && val !== ''); } /** * Joins strings with the specified separator inserted between each value. * Null values and empty strings will be excluded. */ function join(items, separator) { separator = separator || ''; return filter(items, isValidString).join(separator); } module.exports = join; },{"./filter":4}],7:[function(require,module,exports){ var arrSlice = Array.prototype.slice; /** * Create slice of source array or array-like object */ function slice(arr, start, end){ return arrSlice.call(arr, start, end); } module.exports = slice; },{}],8:[function(require,module,exports){ /** * Merge sort (http://en.wikipedia.org/wiki/Merge_sort) */ function mergeSort(arr, compareFn) { if (arr == null) { return []; } else if (arr.length < 2) { return arr; } if (compareFn == null) { compareFn = defaultCompare; } var mid, left, right; mid = ~~(arr.length / 2); left = mergeSort( arr.slice(0, mid), compareFn ); right = mergeSort( arr.slice(mid, arr.length), compareFn ); return merge(left, right, compareFn); } function defaultCompare(a, b) { return a < b ? -1 : (a > b? 1 : 0); } function merge(left, right, compareFn) { var result = []; while (left.length && right.length) { if (compareFn(left[0], right[0]) <= 0) { // if 0 it should preserve same order (stable) result.push(left.shift()); } else { result.push(right.shift()); } } if (left.length) { result.push.apply(result, left); } if (right.length) { result.push.apply(result, right); } return result; } module.exports = mergeSort; },{}],9:[function(require,module,exports){ var isFunction = require('../lang/isFunction'); /** * Creates an object that holds a lookup for the objects in the array. */ function toLookup(arr, key) { var result = {}; if (arr == null) { return result; } var i = -1, len = arr.length, value; if (isFunction(key)) { while (++i < len) { value = arr[i]; result[key(value)] = value; } } else { while (++i < len) { value = arr[i]; result[value[key]] = value; } } return result; } module.exports = toLookup; },{"../lang/isFunction":15}],10:[function(require,module,exports){ /** * Returns the first argument provided to it. */ function identity(val){ return val; } module.exports = identity; },{}],11:[function(require,module,exports){ var identity = require('./identity'); var prop = require('./prop'); var deepMatches = require('../object/deepMatches'); /** * Converts argument into a valid iterator. * Used internally on most array/object/collection methods that receives a * callback/iterator providing a shortcut syntax. */ function makeIterator(src, thisObj){ if (src == null) { return identity; } switch(typeof src) { case 'function': // function is the first to improve perf (most common case) // also avoid using `Function#call` if not needed, which boosts // perf a lot in some cases return (typeof thisObj !== 'undefined')? function(val, i, arr){ return src.call(thisObj, val, i, arr); } : src; case 'object': return function(val){ return deepMatches(val, src); }; case 'string': case 'number': return prop(src); } } module.exports = makeIterator; },{"../object/deepMatches":20,"./identity":10,"./prop":12}],12:[function(require,module,exports){ /** * Returns a function that gets a property of the passed object */ function prop(name){ return function(obj){ return obj[name]; }; } module.exports = prop; },{}],13:[function(require,module,exports){ var isKind = require('./isKind'); /** */ var isArray = Array.isArray || function (val) { return isKind(val, 'Array'); }; module.exports = isArray; },{"./isKind":16}],14:[function(require,module,exports){ var forOwn = require('../object/forOwn'); var isArray = require('./isArray'); function isEmpty(val){ if (val == null) { // typeof null == 'object' so we check it first return false; } else if ( typeof val === 'string' || isArray(val) ) { return !val.length; } else if ( typeof val === 'object' || typeof val === 'function' ) { var result = true; forOwn(val, function(){ result = false; return false; // break loop }); return result; } else { return false; } } module.exports = isEmpty; },{"../object/forOwn":23,"./isArray":13}],15:[function(require,module,exports){ var isKind = require('./isKind'); /** */ function isFunction(val) { return isKind(val, 'Function'); } module.exports = isFunction; },{"./isKind":16}],16:[function(require,module,exports){ var kindOf = require('./kindOf'); /** * Check if value is from a specific "kind". */ function isKind(val, kind){ return kindOf(val) === kind; } module.exports = isKind; },{"./kindOf":18}],17:[function(require,module,exports){ /** * Checks if the value is created by the `Object` constructor. */ function isPlainObject(value) { return (!!value && typeof value === 'object' && value.constructor === Object); } module.exports = isPlainObject; },{}],18:[function(require,module,exports){ var _rKind = /^\[object (.*)\]$/, _toString = Object.prototype.toString, UNDEF; /** * Gets the "kind" of value. (e.g. "String", "Number", etc) */ function kindOf(val) { if (val === null) { return 'Null'; } else if (val === UNDEF) { return 'Undefined'; } else { return _rKind.exec( _toString.call(val) )[1]; } } module.exports = kindOf; },{}],19:[function(require,module,exports){ /** * Typecast a value to a String, using an empty string value for null or * undefined. */ function toString(val){ return val == null ? '' : val.toString(); } module.exports = toString; },{}],20:[function(require,module,exports){ var forOwn = require('./forOwn'); var isArray = require('../lang/isArray'); function containsMatch(array, pattern) { var i = -1, length = array.length; while (++i < length) { if (deepMatches(array[i], pattern)) { return true; } } return false; } function matchArray(target, pattern) { var i = -1, patternLength = pattern.length; while (++i < patternLength) { if (!containsMatch(target, pattern[i])) { return false; } } return true; } function matchObject(target, pattern) { var result = true; forOwn(pattern, function(val, key) { if (!deepMatches(target[key], val)) { // Return false to break out of forOwn early return (result = false); } }); return result; } /** * Recursively check if the objects match. */ function deepMatches(target, pattern){ if (target && typeof target === 'object') { if (isArray(target) && isArray(pattern)) { return matchArray(target, pattern); } else { return matchObject(target, pattern); } } else { return target === pattern; } } module.exports = deepMatches; },{"../lang/isArray":13,"./forOwn":23}],21:[function(require,module,exports){ var forOwn = require('./forOwn'); var isPlainObject = require('../lang/isPlainObject'); /** * Mixes objects into the target object, recursively mixing existing child * objects. */ function deepMixIn(target, objects) { var i = 0, n = arguments.length, obj; while(++i < n){ obj = arguments[i]; if (obj) { forOwn(obj, copyProp, target); } } return target; } function copyProp(val, key) { var existing = this[key]; if (isPlainObject(val) && isPlainObject(existing)) { deepMixIn(existing, val); } else { this[key] = val; } } module.exports = deepMixIn; },{"../lang/isPlainObject":17,"./forOwn":23}],22:[function(require,module,exports){ var _hasDontEnumBug, _dontEnums; function checkDontEnum(){ _dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; _hasDontEnumBug = true; for (var key in {'toString': null}) { _hasDontEnumBug = false; } } /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forIn(obj, fn, thisObj){ var key, i = 0; // no need to check if argument is a real object that way we can use // it for arrays, functions, date, etc. //post-pone check till needed if (_hasDontEnumBug == null) checkDontEnum(); for (key in obj) { if (exec(fn, obj, key, thisObj) === false) { break; } } if (_hasDontEnumBug) { while (key = _dontEnums[i++]) { // since we aren't using hasOwn check we need to make sure the // property was overwritten if (obj[key] !== Object.prototype[key]) { if (exec(fn, obj, key, thisObj) === false) { break; } } } } } function exec(fn, obj, key, thisObj){ return fn.call(thisObj, obj[key], key, obj); } module.exports = forIn; },{}],23:[function(require,module,exports){ var hasOwn = require('./hasOwn'); var forIn = require('./forIn'); /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forOwn(obj, fn, thisObj){ forIn(obj, function(val, key){ if (hasOwn(obj, key)) { return fn.call(thisObj, obj[key], key, obj); } }); } module.exports = forOwn; },{"./forIn":22,"./hasOwn":24}],24:[function(require,module,exports){ /** * Safer Object.hasOwnProperty */ function hasOwn(obj, prop){ return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = hasOwn; },{}],25:[function(require,module,exports){ var join = require('../array/join'); var slice = require('../array/slice'); /** * Group arguments as path segments, if any of the args is `null` or an * empty string it will be ignored from resulting path. */ function makePath(var_args){ var result = join(slice(arguments), '/'); // need to disconsider duplicate '/' after protocol (eg: 'http://') return result.replace(/([^:\/]|^)\/{2,}/g, '$1/'); } module.exports = makePath; },{"../array/join":6,"../array/slice":7}],26:[function(require,module,exports){ var toString = require('../lang/toString'); /** * "Safer" String.toUpperCase() */ function upperCase(str){ str = toString(str); return str.toUpperCase(); } module.exports = upperCase; },{"../lang/toString":19}],"clHM+W":[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'); function _$http(deferred, config) { var start = new Date().getTime(); services.$http(config).success(function (data, status, headers, config) { services.$log.debug(config.method + ' request:' + config.url + ' Time taken: ' + (new Date().getTime() - start) + 'ms', arguments); deferred.resolve(data); }).error(function (data, status, headers, config) { services.$log.error(arguments); deferred.reject(data); }); } /** * @doc method * @id DS.async_methods:HTTP * @name HTTP * @description * Wrapper for `$http()`. * * ## Signature: * ```js * DS.HTTP(config) * ``` * * ## Example: * * ```js * works the same as $http() * ``` * * @param {object} config Configuration for the request. * @returns {Promise} Promise produced by the `$q` service. */ function HTTP(config) { var deferred = services.$q.defer(); try { if (!services.$rootScope.$$phase) { services.$rootScope.$apply(function () { _$http(deferred, config); }); } else { _$http(deferred, config); } } catch (err) { deferred.reject(new errors.UnhandledError(err)); } return deferred.promise; } /** * @doc method * @id DS.async_methods:GET * @name GET * @description * Wrapper for `$http.get()`. * * ## Signature: * ```js * DS.GET(url[, config]) * ``` * * ## Example: * * ```js * Works the same as $http.get() * ``` * * @param {string} url The url of the request. * @param {object=} config Configuration for the request. * @returns {Promise} Promise produced by the `$q` service. */ function GET(url, config) { config = config || {}; return HTTP(utils.deepMixIn(config, { url: url, method: 'GET' })); } /** * @doc method * @id DS.async_methods:PUT * @name PUT * @description * Wrapper for `$http.put()`. * * ## Signature: * ```js * DS.PUT(url[, attrs][, config]) * ``` * * ## Example: * * ```js * Works the same as $http.put() * ``` * * @param {string} url The url of the request. * @param {object=} attrs Request payload. * @param {object=} config Configuration for the request. * @returns {Promise} Promise produced by the `$q` service. */ function PUT(url, attrs, config) { config = config || {}; return HTTP(utils.deepMixIn(config, { url: url, data: attrs, method: 'PUT' })); } /** * @doc method * @id DS.async_methods:POST * @name POST * @description * Wrapper for `$http.post()`. * * ## Signature: * ```js * DS.POST(url[, attrs][, config]) * ``` * * ## Example: * * ```js * Works the same as $http.post() * ``` * * @param {string} url The url of the request. * @param {object=} attrs Request payload. * @param {object=} config Configuration for the request. * @returns {Promise} Promise produced by the `$q` service. */ function POST(url, attrs, config) { config = config || {}; return HTTP(utils.deepMixIn(config, { url: url, data: attrs, method: 'POST' })); } /** * @doc method * @id DS.async_methods:DEL * @name DEL * @description * Wrapper for `$http.delete()`. * * ## Signature: * ```js * DS.DEL(url[, config]) * ``` * * ## Example: * * ```js * Works the same as $http.delete * ``` * * @param {string} url The url of the request. * @param {object} config Configuration for the request. * @returns {Promise} Promise produced by the `$q` service. */ function DEL(url, config) { config = config || {}; return HTTP(utils.deepMixIn(config, { url: url, method: 'DELETE' })); } module.exports = { /** * @doc method * @id DS.async_methods:HTTP * @name HTTP * @methodOf DS * @description * See [DS.HTTP](/documentation/api/api/DS.async_methods:HTTP). */ HTTP: HTTP, /** * @doc method * @id DS.async_methods:GET * @name GET * @methodOf DS * @description * See [DS.GET](/documentation/api/api/DS.async_methods:GET). */ GET: GET, /** * @doc method * @id DS.async_methods:POST * @name POST * @methodOf DS * @description * See [DS.POST](/documentation/api/api/DS.async_methods:POST). */ POST: POST, /** * @doc method * @id DS.async_methods:PUT * @name PUT * @methodOf DS * @description * See [DS.PUT](/documentation/api/api/DS.async_methods:PUT). */ PUT: PUT, /** * @doc method * @id DS.async_methods:DEL * @name DEL * @methodOf DS * @description * See [DS.DEL](/documentation/api/api/DS.async_methods:DEL). */ DEL: DEL }; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],"HttpAdapter":[function(require,module,exports){ module.exports=require('clHM+W'); },{}],29:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.create(resourceName, attrs): '; /** * @doc method * @id DS.async_methods:create * @name create * @description * Create a new resource and save it to the server. * * ## Signature: * ```js * DS.create(resourceName, attrs) * ``` * * ## Example: * * ```js * DS.create('document', { author: 'John Anderson' }) * .then(function (document) { * document; // { id: 'aab7ff66-e21e-46e2-8be8-264d82aee535', author: 'John Anderson' } * * // The new document is already in the data store * DS.get('document', document.id); // { id: 'aab7ff66-e21e-46e2-8be8-264d82aee535', author: 'John Anderson' } * }, function (err) { * // handle error * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object} attrs The attributes with which to update the item of the type specified by `resourceName` that has * the primary key specified by `id`. * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{object}` - `item` - A reference to the newly created item. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` */ function create(resourceName, attrs) { var deferred = services.$q.defer(), promise = deferred.promise; if (!services.store[resourceName]) { deferred.reject(new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!')); } else if (!utils.isObject(attrs)) { deferred.reject(new errors.IllegalArgumentError(errorPrefix + 'attrs: Must be an object!', { attrs: { actual: typeof attrs, expected: 'object' } })); } else { try { var resource = services.store[resourceName], _this = this; promise = promise .then(function (attrs) { return services.$q.promisify(resource.beforeValidate)(resourceName, attrs); }) .then(function (attrs) { return services.$q.promisify(resource.validate)(resourceName, attrs); }) .then(function (attrs) { return services.$q.promisify(resource.afterValidate)(resourceName, attrs); }) .then(function (attrs) { return services.$q.promisify(resource.beforeCreate)(resourceName, attrs); }) .then(function (attrs) { return services.adapters[resource.defaultAdapter].POST.apply(_this, [utils.makePath(resource.baseUrl, resource.endpoint), attrs, null]); }) .then(function (data) { return services.$q.promisify(resource.afterCreate)(resourceName, data); }) .then(function (data) { return _this.inject(resource.name, data); }); deferred.resolve(attrs); } catch (err) { deferred.reject(new errors.UnhandledError(err)); } } return promise; } module.exports = create; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],30:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.destroy(resourceName, id): '; /** * @doc method * @id DS.async_methods:destroy * @name destroy * @description * Delete the item of the type specified by `resourceName` with the primary key specified by `id` from the data store * and the server. * * ## Signature: * ```js * DS.destroy(resourceName, id); * ``` * * ## Example: * * ```js * DS.destroy('document', 'aab7ff66-e21e-46e2-8be8-264d82aee535') * .then(function (id) { * id; // 'aab7ff66-e21e-46e2-8be8-264d82aee535' * * // The document is gone * DS.get('document', 'aab7ff66-e21e-46e2-8be8-264d82aee535'); // undefined * }, function (err) { * // Handle error * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to remove. * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{string|number}` - `id` - The primary key of the destroyed item. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` */ function destroy(resourceName, id) { var deferred = services.$q.defer(), promise = deferred.promise; if (!services.store[resourceName]) { deferred.reject(new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!')); } else if (!utils.isString(id) && !utils.isNumber(id)) { deferred.reject(new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } })); } else { var resource = services.store[resourceName], _this = this; promise = promise .then(function (attrs) { return services.$q.promisify(resource.beforeDestroy)(resourceName, attrs); }) .then(function () { return services.adapters[resource.defaultAdapter].DEL(utils.makePath(resource.baseUrl, resource.endpoint, id), null); }) .then(function () { return services.$q.promisify(resource.afterDestroy)(resourceName, resource.index[id]); }) .then(function () { _this.eject(resourceName, id); return id; }); deferred.resolve(resource.index[id]); } return promise; } module.exports = destroy; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],31:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.find(resourceName, id[, options]): '; /** * @doc method * @id DS.async_methods:find * @name find * @description * Asynchronously return the resource with the given id from the server. The result will be added to the data * store when it returns from the server. * * ## Signature: * ```js * DS.find(resourceName, id[, options]) * ``` * * ## Example: * * ```js * DS.get('document', 5); // undefined * DS.find('document', 5).then(function (document) { * document; // { id: 5, author: 'John Anderson' } * * DS.get('document', 5); // { id: 5, author: 'John Anderson' } * }, function (err) { * // Handled errors * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to retrieve. * @param {object=} options Optional configuration. Properties: * - `{boolean=}` - `bypassCache` - Bypass the cache. Default: `false`. * - `{string=}` - `mergeStrategy` - If `findAll` is called, specify the merge strategy that should be used when the new * items are injected into the data store. Default: `"mergeWithExisting"`. * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{object}` - `item` - The item with the primary key specified by `id`. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` */ function find(resourceName, id, options) { var deferred = services.$q.defer(), promise = deferred.promise; options = options || {}; if (!services.store[resourceName]) { deferred.reject(new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!')); } else if (!utils.isString(id) && !utils.isNumber(id)) { deferred.reject(new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } })); } else if (!utils.isObject(options)) { deferred.reject(new errors.IllegalArgumentError(errorPrefix + 'options: Must be an object!', { options: { actual: typeof options, expected: 'object' } })); } else { try { var resource = services.store[resourceName], _this = this; if (options.bypassCache) { delete resource.completedQueries[id]; } if (!(id in resource.completedQueries)) { if (!(id in resource.pendingQueries)) { promise = resource.pendingQueries[id] = services.adapters[resource.defaultAdapter].GET(utils.makePath(resource.baseUrl, resource.endpoint, id), null) .then(function (data) { // Query is no longer pending delete resource.pendingQueries[id]; resource.completedQueries[id] = new Date().getTime(); return _this.inject(resourceName, data); }); } return resource.pendingQueries[id]; } else { deferred.resolve(_this.get(resourceName, id)); } } catch (err) { deferred.reject(err); } } return promise; } module.exports = find; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],32:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.findAll(resourceName, params[, options]): '; function processResults(data, resourceName, queryHash) { var resource = services.store[resourceName]; data = data || []; // Query is no longer pending delete resource.pendingQueries[queryHash]; resource.completedQueries[queryHash] = new Date().getTime(); // Merge the new values into the cache for (var i = 0; i < data.length; i++) { this.inject(resourceName, data[i]); } // Update the data store's index for this resource resource.index = utils.toLookup(resource.collection, resource.idAttribute); // Update modified timestamp of collection resource.collectionModified = utils.updateTimestamp(resource.collectionModified); return data; } function _findAll(resourceName, params, options) { var resource = services.store[resourceName], _this = this, queryHash = utils.toJson(params); if (options.bypassCache) { delete resource.completedQueries[queryHash]; } if (!(queryHash in resource.completedQueries)) { // This particular query has never been completed if (!(queryHash in resource.pendingQueries)) { // This particular query has never even been made resource.pendingQueries[queryHash] = services.adapters[resource.defaultAdapter].GET(utils.makePath(resource.baseUrl, resource.endpoint), { params: params }) .then(function (data) { try { return processResults.apply(_this, [data, resourceName, queryHash]); } catch (err) { throw new errors.UnhandledError(err); } }); } return resource.pendingQueries[queryHash]; } else { return this.filter(resourceName, params, options); } } /** * @doc method * @id DS.async_methods:findAll * @name findAll * @description * Asynchronously return the resource from the server filtered by the query. The results will be added to the data * store when it returns from the server. * * ## Signature: * ```js * DS.findAll(resourceName, params[, options]) * ``` * * ## Example: * * ```js * var query = { * where: { * author: { * '==': 'John Anderson' * } * } * }; * * DS.findAll('document', { * query: query * }).then(function (documents) { * documents; // [{ id: 'aab7ff66-e21e-46e2-8be8-264d82aee535', author: 'John Anderson', title: 'How to cook' }, * // { id: 'ee7f3f4d-98d5-4934-9e5a-6a559b08479f', author: 'John Anderson', title: 'How NOT to cook' }] * * // The documents are now in the data store * DS.filter('document', { * query: query * }); // [{ id: 'aab7ff66-e21e-46e2-8be8-264d82aee535', author: 'John Anderson', title: 'How to cook' }, * // { id: 'ee7f3f4d-98d5-4934-9e5a-6a559b08479f', author: 'John Anderson', title: 'How NOT to cook' }] * * }, function (err) { * // handle error * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object} params Parameter object that is serialized into the query string. Properties: * * - `{object=}` - `query` - The query object by which to filter items of the type specified by `resourceName`. Properties: * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{skip=}` - `skip` - Skip clause. * - `{orderBy=}` - `orderBy` - OrderBy clause. * * @param {object=} options Optional configuration. Properties: * - `{boolean=}` - `bypassCache` - Bypass the cache. Default: `false`. * - `{string=}` - `mergeStrategy` - If `findAll` is called, specify the merge strategy that should be used when the new * items are injected into the data store. Default `"mergeWithExisting"`. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{array}` - `items` - The collection of items returned by the server. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` */ function findAll(resourceName, params, options) { var deferred = services.$q.defer(), promise = deferred.promise, _this = this; options = options || {}; if (!services.store[resourceName]) { deferred.reject(new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!')); } else if (!utils.isObject(params)) { deferred.reject(new errors.IllegalArgumentError(errorPrefix + 'params: Must be an object!', { params: { actual: typeof params, expected: 'object' } })); } else if (!utils.isObject(options)) { deferred.reject(new errors.IllegalArgumentError(errorPrefix + 'options: Must be an object!', { options: { actual: typeof options, expected: 'object' } })); } else { try { promise = promise.then(function () { return _findAll.apply(_this, [resourceName, params, options]); }); deferred.resolve(); } catch (err) { deferred.reject(new errors.UnhandledError(err)); } } return promise; } module.exports = findAll; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],33:[function(require,module,exports){ module.exports = { /** * @doc method * @id DS.async_methods:create * @name create * @methodOf DS * @description * See [DS.create](/documentation/api/api/DS.async_methods:create). */ create: require('./create'), /** * @doc method * @id DS.async_methods:destroy * @name destroy * @methodOf DS * @description * See [DS.destroy](/documentation/api/api/DS.async_methods:destroy). */ destroy: require('./destroy'), /** * @doc method * @id DS.async_methods:find * @name find * @methodOf DS * @description * See [DS.find](/documentation/api/api/DS.async_methods:find). */ find: require('./find'), /** * @doc method * @id DS.async_methods:findAll * @name findAll * @methodOf DS * @description * See [DS.findAll](/documentation/api/api/DS.async_methods:findAll). */ findAll: require('./findAll'), /** * @doc method * @id DS.async_methods:refresh * @name refresh * @methodOf DS * @description * See [DS.refresh](/documentation/api/api/DS.async_methods:refresh). */ refresh: require('./refresh'), /** * @doc method * @id DS.async_methods:save * @name save * @methodOf DS * @description * See [DS.save](/documentation/api/api/DS.async_methods:save). */ save: require('./save') }; },{"./create":29,"./destroy":30,"./find":31,"./findAll":32,"./refresh":34,"./save":35}],34:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.refresh(resourceName, id[, options]): '; /** * @doc method * @id DS.async_methods:refresh * @name refresh * @description * Like find(), except the resource is only refreshed from the server if it already exists in the data store. * * ## Signature: * ```js * DS.refresh(resourceName, id) * ``` * ## Example: * * ```js * // Exists in the data store, but we want a fresh copy * DS.get('document', 'ee7f3f4d-98d5-4934-9e5a-6a559b08479f'); * * DS.refresh('document', 'ee7f3f4d-98d5-4934-9e5a-6a559b08479f') * .then(function (document) { * document; // The fresh copy * }); * * // Does not exist in the data store * DS.get('document', 'aab7ff66-e21e-46e2-8be8-264d82aee535'); * * DS.refresh('document', 'aab7ff66-e21e-46e2-8be8-264d82aee535'); // false * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to refresh from the server. * @param {object=} options Optional configuration. Properties: * - `{string=}` - `mergeStrategy` - Specify what merge strategy is to be used when the fresh item returns from the * server and needs to be inserted into the data store. Default `"mergeWithExisting"`. * @returns {false|Promise} `false` if the item doesn't already exist in the data store. A `Promise` if the item does * exist in the data store and is being refreshed. * * ## Resolves with: * * - `{object}` - `item` - A reference to the refreshed item. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` */ function refresh(resourceName, id, options) { options = options || {}; if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (!utils.isString(id) && !utils.isNumber(id)) { throw new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } }); } else if (!utils.isObject(options)) { throw new errors.IllegalArgumentError(errorPrefix + 'options: Must be an object!', { options: { actual: typeof options, expected: 'object' } }); } else { options.bypassCache = true; if (id in services.store[resourceName].index) { return this.find(resourceName, id, options); } else { return false; } } } module.exports = refresh; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],35:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.save(resourceName, id[, options]): '; /** * @doc method * @id DS.async_methods:save * @name save * @description * Save the item of the type specified by `resourceName` that has the primary key specified by `id`. * * ## Signature: * ```js * DS.save(resourceName, id[, options]) * ``` * * ## Example: * * ```js * var document = DS.get('document', 'ee7f3f4d-98d5-4934-9e5a-6a559b08479f'); * * document.title = 'How to cook in style'; * * DS.save('document', 'ee7f3f4d-98d5-4934-9e5a-6a559b08479f') * .then(function (document) { * document; // A reference to the document that's been saved to the server * }); * ``` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to retrieve. * @param {object=} options Optional configuration. Properties: * - `{string=}` - `mergeStrategy` - When the updated item returns from the server, specify the merge strategy that * should be used when the updated item is injected into the data store. Default: `"mergeWithExisting"`. * * @returns {Promise} Promise produced by the `$q` service. * * ## Resolves with: * * - `{object}` - `item` - A reference to the newly saved item. * * ## Rejects with: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` */ function save(resourceName, id, options) { var deferred = services.$q.defer(), promise = deferred.promise; options = options || {}; if (!services.store[resourceName]) { deferred.reject(new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!')); } else if (!utils.isString(id) && !utils.isNumber(id)) { deferred.reject(new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } })); } else if (!utils.isObject(options)) { deferred.reject(new errors.IllegalArgumentError(errorPrefix + 'options: Must be an object!', { options: { actual: typeof options, expected: 'object' } })); } else if (!(id in services.store[resourceName].index)) { deferred.reject(new errors.RuntimeError(errorPrefix + 'id: "' + id + '" not found!')); } else { var resource = services.store[resourceName], _this = this; promise = promise .then(function (attrs) { return services.$q.promisify(resource.beforeValidate)(resourceName, attrs); }) .then(function (attrs) { return services.$q.promisify(resource.validate)(resourceName, attrs); }) .then(function (attrs) { return services.$q.promisify(resource.afterValidate)(resourceName, attrs); }) .then(function (attrs) { return services.$q.promisify(resource.beforeUpdate)(resourceName, attrs); }) .then(function (attrs) { return services.adapters[resource.defaultAdapter].PUT(utils.makePath(resource.baseUrl, resource.endpoint, id), attrs, null); }) .then(function (data) { return services.$q.promisify(resource.afterUpdate)(resourceName, data); }) .then(function (data) { var saved = _this.inject(resource.name, data, options); resource.previous_attributes[id] = utils.deepMixIn({}, data); resource.saved[id] = utils.updateTimestamp(resource.saved[id]); return saved; }); deferred.resolve(resource.index[id]); } return promise; } module.exports = save; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],36:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), HttpAdapter = require('HttpAdapter'), configErrorPrefix = 'DSProvider.config(options): ', registerAdapterErrorPrefix = 'DSProvider.registerAdapter(name, adapter): '; /** * @doc method * @id DSProvider.methods:config * @name config * @description * Configure the DS service. * * ## Signature: * ```js * DSProvider.config(options) * ``` * * ## Example: * ```js * DSProvider.config({ * baseUrl: 'http://myapp.com/api', * idAttribute: '_id', * validate: function (resourceName, attrs, cb) { * console.log('looks good to me'); * cb(null, attrs); * } * }); * ``` * * ## Throws: * * - `{IllegalArgumentError}` * * @param {object} options Global configuration for the data store. Properties: * - `{string=}` - `baseUrl` - The default base url to be used by the data store. Can be overridden via `DS.defineResource`. * - `{string=}` - `idAttribute` - The default property that specifies the primary key of an object. Default: `"id"`. * - `{function=}` - `beforeValidate` - Global lifecycle hook. Signature: `beforeValidate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `validate` - Global lifecycle hook. Signature: `validate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterValidate` - Global lifecycle hook. Signature: `afterValidate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeCreate` - Global lifecycle hook. Signature: `beforeCreate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterCreate` - Global lifecycle hook. Signature: `afterCreate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeUpdate` - Global lifecycle hook. Signature: `beforeUpdate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterUpdate` - Global lifecycle hook. Signature: `afterUpdate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeDestroy` - Global lifecycle hook. Signature: `beforeDestroy(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterDestroy` - Global lifecycle hook. Signature: `afterDestroy(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. */ function config(options) { options = options || {}; if (!utils.isObject(options)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options: Must be an object!', { actual: typeof options, expected: 'object' }); } else if ('baseUrl' in options && !utils.isString(options.baseUrl)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.baseUrl: Must be a string!', { baseUrl: { actual: typeof options.baseUrl, expected: 'string' } }); } else if ('idAttribute' in options && !utils.isString(options.idAttribute)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.idAttribute: Must be a string!', { idAttribute: { actual: typeof options.idAttribute, expected: 'string' } }); } else if ('mergeStrategy' in options && !utils.isString(options.mergeStrategy)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.mergeStrategy: Must be a string!', { mergeStrategy: { actual: typeof options.mergeStrategy, expected: 'string' } }); } else if ('beforeValidate' in options && !utils.isFunction(options.beforeValidate)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.beforeValidate: Must be a function!', { beforeValidate: { actual: typeof options.beforeValidate, expected: 'function' } }); } else if ('validate' in options && !utils.isFunction(options.validate)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.validate: Must be a function!', { validate: { actual: typeof options.validate, expected: 'function' } }); } else if ('afterValidate' in options && !utils.isFunction(options.afterValidate)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.afterValidate: Must be a function!', { afterValidate: { actual: typeof options.afterValidate, expected: 'function' } }); } else if ('beforeCreate' in options && !utils.isFunction(options.beforeCreate)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.beforeCreate: Must be a function!', { beforeCreate: { actual: typeof options.beforeCreate, expected: 'function' } }); } else if ('afterCreate' in options && !utils.isFunction(options.afterCreate)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.afterCreate: Must be a function!', { afterCreate: { actual: typeof options.afterCreate, expected: 'function' } }); } else if ('beforeUpdate' in options && !utils.isFunction(options.beforeUpdate)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.beforeUpdate: Must be a function!', { beforeUpdate: { actual: typeof options.beforeUpdate, expected: 'function' } }); } else if ('afterUpdate' in options && !utils.isFunction(options.afterUpdate)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.afterUpdate: Must be a function!', { afterUpdate: { actual: typeof options.afterUpdate, expected: 'function' } }); } else if ('beforeDestroy' in options && !utils.isFunction(options.beforeDestroy)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.beforeDestroy: Must be a function!', { beforeDestroy: { actual: typeof options.beforeDestroy, expected: 'function' } }); } else if ('afterDestroy' in options && !utils.isFunction(options.afterDestroy)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.afterDestroy: Must be a function!', { afterDestroy: { actual: typeof options.afterDestroy, expected: 'function' } }); } else if ('defaultAdapter' in options && !utils.isString(options.defaultAdapter)) { throw new errors.IllegalArgumentError(configErrorPrefix + 'options.defaultAdapter: Must be a function!', { defaultAdapter: { actual: typeof options.defaultAdapter, expected: 'string' } }); } services.config = new services.BaseConfig(options); } /** * @doc method * @id DSProvider.methods:registerAdapter * @name registerAdapter * @description * Register a new adapter. * * ## Signature: * ```js * DSProvider.registerAdapter(name, adapter); * ``` * * ## Example: * ```js * DSProvider.registerAdapter('IndexedDBAdapter', {...}); * ``` * * ## Throws: * * - `{IllegalArgumentError}` * - `{RuntimeError}` * * @param {string} name The name of the new adapter. * @param {object} adapter New adapter. */ function registerAdapter(name, adapter) { if (!utils.isString(name)) { throw new errors.IllegalArgumentError(registerAdapterErrorPrefix + 'name: Must be a string!', { actual: typeof name, expected: 'string' }); } else if (!utils.isObject(adapter)) { throw new errors.IllegalArgumentError(registerAdapterErrorPrefix + 'adapter: Must be an object!', { actual: typeof adapter, expected: 'object' }); } else if (services.adapters[name]) { throw new errors.RuntimeError(registerAdapterErrorPrefix + name + ' is already registered!'); } services.adapters[name] = adapter; } /** * @doc interface * @id DSProvider * @name DSProvider */ function DSProvider() { /** * @doc method * @id DSProvider.methods:config * @name config * @methodOf DSProvider * @description * See [DSProvider.config](/documentation/api/api/DSProvider.methods:config). */ this.config = config; config({}); /** * @doc method * @id DSProvider.methods:registerAdapter * @name config * @methodOf DSProvider * @description * See [DSProvider.registerAdapter](/documentation/api/api/DSProvider.methods:registerAdapter). */ this.registerAdapter = registerAdapter; this.$get = ['$rootScope', '$log', '$http', '$q', function ($rootScope, $log, $http, $q) { services.$rootScope = $rootScope; services.$log = $log; services.$http = $http; services.$q = $q; services.store = {}; services.adapters = {}; registerAdapter('HttpAdapter', HttpAdapter); /** * @doc interface * @id DS * @name DS * @description * Data store */ var DS = { HttpAdapter: HttpAdapter, errors: errors }; utils.deepMixIn(DS, require('./sync_methods')); utils.deepMixIn(DS, require('./async_methods')); utils.deepFreeze(DS); var $dirtyCheckScope = $rootScope.$new(); $dirtyCheckScope.$watch(function () { // Throttle angular-data's digest loop to tenths of a second return new Date().getTime() / 100 | 0; }, function () { DS.digest(); }); return DS; }]; } module.exports = DSProvider; },{"./async_methods":33,"./sync_methods":46,"HttpAdapter":"clHM+W","errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],"cX8q+p":[function(require,module,exports){ function lifecycleNoop(resourceName, attrs, cb) { cb(null, attrs); } var services = module.exports = { store: {}, BaseConfig: function (options) { if ('idAttribute' in options) { this.idAttribute = options.idAttribute; } if ('baseUrl' in options) { this.baseUrl = options.baseUrl; } if ('beforeValidate' in options) { this.beforeValidate = options.beforeValidate; } if ('validate' in options) { this.validate = options.validate; } if ('afterValidate' in options) { this.afterValidate = options.afterValidate; } if ('beforeCreate' in options) { this.beforeCreate = options.beforeCreate; } if ('afterCreate' in options) { this.afterCreate = options.afterCreate; } if ('beforeUpdate' in options) { this.beforeUpdate = options.beforeUpdate; } if ('afterUpdate' in options) { this.afterUpdate = options.afterUpdate; } if ('beforeDestroy' in options) { this.beforeDestroy = options.beforeDestroy; } if ('afterDestroy' in options) { this.afterDestroy = options.afterDestroy; } if ('defaultAdapter' in options) { this.defaultAdapter = options.defaultAdapter; } } }; services.BaseConfig.prototype.idAttribute = 'id'; services.BaseConfig.prototype.defaultAdapter = 'HttpAdapter'; services.BaseConfig.prototype.baseUrl = ''; services.BaseConfig.prototype.endpoint = ''; services.BaseConfig.prototype.beforeValidate = lifecycleNoop; services.BaseConfig.prototype.validate = lifecycleNoop; services.BaseConfig.prototype.afterValidate = lifecycleNoop; services.BaseConfig.prototype.beforeCreate = lifecycleNoop; services.BaseConfig.prototype.afterCreate = lifecycleNoop; services.BaseConfig.prototype.beforeUpdate = lifecycleNoop; services.BaseConfig.prototype.afterUpdate = lifecycleNoop; services.BaseConfig.prototype.beforeDestroy = lifecycleNoop; services.BaseConfig.prototype.afterDestroy = lifecycleNoop; },{}],"services":[function(require,module,exports){ module.exports=require('cX8q+p'); },{}],39:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.changes(resourceName, id): '; /** * @doc method * @id DS.sync_methods:changes * @name changes * @description * Synchronously return the changes object of the item of the type specified by `resourceName` that has the primary key * specified by `id`. This object represents the diff between the item in its current state and the state of the item * the last time it was saved via an async adapter. * * ## Signature: * ```js * DS.changes(resourceName, id) * ``` * * ## Example: * * ```js * var d = DS.get('document', 5); // { author: 'John Anderson', id: 5 } * * d.author = 'Sally'; * * DS.changes('document', 5); // {...} Object describing changes * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item of the changes to retrieve. * @returns {object} The changes of the item of the type specified by `resourceName` with the primary key specified by `id`. */ function changes(resourceName, id) { if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (!utils.isString(id) && !utils.isNumber(id)) { throw new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } }); } try { return angular.copy(services.store[resourceName].changes[id]); } catch (err) { throw new errors.UnhandledError(err); } } module.exports = changes; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],40:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.defineResource(definition): '; function Resource(options) { services.BaseConfig.apply(this, [options]); if ('name' in options) { this.name = options.name; } if ('endpoint' in options) { this.endpoint = options.endpoint; } else { this.endpoint = this.name; } this.collection = []; this.completedQueries = {}; this.pendingQueries = {}; this.index = {}; this.modified = {}; this.changes = {}; this.previous_attributes = {}; this.saved = {}; this.observers = {}; this.collectionModified = 0; } Resource.prototype = services.config; /** * @doc method * @id DS.sync_methods:defineResource * @name defineResource * @description * Define a resource and register it with the data store. * * ## Signature: * ```js * DS.defineResource(definition) * ``` * * ## Example: * * ```js * DS.defineResource({ * name: 'document', * idAttribute: '_id', * endpoint: '/documents * baseUrl: 'http://myapp.com/api', * beforeDestroy: function (resourceName attrs, cb) { * console.log('looks good to me'); * cb(null, attrs); * } * }); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string|object} definition Name of resource or resource definition object: Properties: * * - `{string}` - `name` - The name by which this resource will be identified. * - `{string="id"}` - `idAttribute` - The attribute that specifies the primary key for this resource. * - `{string=}` - `endpoint` - The attribute that specifies the primary key for this resource. Default is the value of `name`. * - `{string=}` - `baseUrl` - The url relative to which all AJAX requests will be made. * - `{function=}` - `beforeValidate` - Lifecycle hook. Overrides global. Signature: `beforeValidate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `validate` - Lifecycle hook. Overrides global. Signature: `validate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterValidate` - Lifecycle hook. Overrides global. Signature: `afterValidate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeCreate` - Lifecycle hook. Overrides global. Signature: `beforeCreate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterCreate` - Lifecycle hook. Overrides global. Signature: `afterCreate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeUpdate` - Lifecycle hook. Overrides global. Signature: `beforeUpdate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterUpdate` - Lifecycle hook. Overrides global. Signature: `afterUpdate(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `beforeDestroy` - Lifecycle hook. Overrides global. Signature: `beforeDestroy(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. * - `{function=}` - `afterDestroy` - Lifecycle hook. Overrides global. Signature: `afterDestroy(resourceName, attrs, cb)`. Callback signature: `cb(err, attrs)`. */ function defineResource(definition) { if (utils.isString(definition)) { definition = { name: definition }; } if (!utils.isObject(definition)) { throw new errors.IllegalArgumentError(errorPrefix + 'definition: Must be an object!', { definition: { actual: typeof definition, expected: 'object' } }); } else if (!utils.isString(definition.name)) { throw new errors.IllegalArgumentError(errorPrefix + 'definition.name: Must be a string!', { definition: { name: { actual: typeof definition.name, expected: 'string' } } }); } else if (definition.idAttribute && !utils.isString(definition.idAttribute)) { throw new errors.IllegalArgumentError(errorPrefix + 'definition.idAttribute: Must be a string!', { definition: { idAttribute: { actual: typeof definition.idAttribute, expected: 'string' } } }); } else if (definition.endpoint && !utils.isString(definition.endpoint)) { throw new errors.IllegalArgumentError(errorPrefix + 'definition.endpoint: Must be a string!', { definition: { endpoint: { actual: typeof definition.endpoint, expected: 'string' } } }); } else if (services.store[definition.name]) { throw new errors.RuntimeError(errorPrefix + definition.name + ' is already registered!'); } try { services.store[definition.name] = new Resource(definition); } catch (err) { delete services.store[definition.name]; throw new errors.UnhandledError(err); } } module.exports = defineResource; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],41:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), observe = require('observejs'); /** * @doc method * @id DS.sync_methods:digest * @name digest * @description * Trigger a digest loop that checks for changes and updates the `lastModified` timestamp if an object has changed. * Anything $watching `DS.lastModified(...)` will detect the updated timestamp and execute the callback function. * * ## Signature: * ```js * DS.digest() * ``` * * ## Example: * * ```js * Works like $scope.$apply() * ``` * * ## Throws * * - `{UnhandledError}` */ function digest() { try { if (!services.$rootScope.$$phase) { services.$rootScope.$apply(function () { observe.Platform.performMicrotaskCheckpoint(); }); } else { observe.Platform.performMicrotaskCheckpoint(); } } catch (err) { throw new errors.UnhandledError(err); } } module.exports = digest; },{"errors":"hIh4e1","observejs":"u+GZEJ","services":"cX8q+p","utils":"uE/lJt"}],42:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.eject(resourceName, id): '; function _eject(resource, id) { if (id) { var found = false; for (var i = 0; i < resource.collection.length; i++) { if (resource.collection[i][resource.idAttribute] == id) { found = true; break; } } if (found) { resource.collection.splice(i, 1); resource.observers[id].close(); delete resource.observers[id]; delete resource.index[id]; delete resource.changes[id]; delete resource.previous_attributes[id]; delete resource.modified[id]; delete resource.saved[id]; } } else { resource.collection = []; resource.index = {}; resource.modified = {}; resource.saved = {}; resource.changes = {}; resource.previous_attributes = {}; } resource.collectionModified = utils.updateTimestamp(resource.collectionModified); } /** * @doc method * @id DS.sync_methods:eject * @name eject * @description * Eject the item of the specified type that has the given primary key from the data store. If no primary key is * provided, eject all items of the specified type from the data store. Ejection only removes items from the data store * and does not attempt to delete items on the server. * * ## Signature: * ```js * DS.eject(resourceName[, id]) * ``` * * ## Examples: * * ```js * DS.get('document', 45); // { title: 'How to Cook', id: 45 } * * DS.eject('document', 45); * * DS.get('document', 45); // undefined * ``` * * Eject all items of the specified type from the data store. * * ```js * DS.filter('document'); // [ { title: 'How to Cook', id: 45 }, { title: 'How to Eat', id: 46 } ] * * DS.eject('document'); * * DS.filter('document'); // [ ] * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number=} id The primary key of the item to eject. */ function eject(resourceName, id) { if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (id && !utils.isString(id) && !utils.isNumber(id)) { throw new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } }); } try { if (!services.$rootScope.$$phase) { services.$rootScope.$apply(function () { _eject(services.store[resourceName], id); }); } else { _eject(services.store[resourceName], id); } } catch (err) { throw new errors.UnhandledError(err); } } module.exports = eject; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],43:[function(require,module,exports){ /* jshint loopfunc: true */ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.filter(resourceName, params[, options]): '; /** * @doc method * @id DS.sync_methods:filter * @name filter * @description * Synchronously filter items in the data store of the type specified by `resourceName`. * * ## Signature: * ```js * DS.filter(resourceName, params[, options]) * ``` * * ## Example: * * ```js * TODO: filter(resourceName, params[, options]) example * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object} params Parameter object that is serialized into the query string. Properties: * * - `{object=}` - `query` - The query object by which to filter items of the type specified by `resourceName`. Properties: * - `{object=}` - `where` - Where clause. * - `{number=}` - `limit` - Limit clause. * - `{skip=}` - `skip` - Skip clause. * - `{orderBy=}` - `orderBy` - OrderBy clause. * * @param {object=} options Optional configuration. Properties: * - `{boolean=}` - `loadFromServer` - Send the query to server if it has not been sent yet. Default: `false`. * - `{string=}` - `mergeStrategy` - If `findAll` is called, specify the merge strategy that should be used when the new * items are injected into the data store. Default: `"mergeWithExisting"`. * * @returns {array} The filtered collection of items of the type specified by `resourceName`. */ function filter(resourceName, params, options) { options = options || {}; if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (!utils.isObject(params)) { throw new errors.IllegalArgumentError(errorPrefix + 'params: Must be an object!', { params: { actual: typeof params, expected: 'object' } }); } else if (!utils.isObject(options)) { throw new errors.IllegalArgumentError(errorPrefix + 'options: Must be an object!', { options: { actual: typeof options, expected: 'object' } }); } try { var resource = services.store[resourceName]; // Protect against null params.query = params.query || {}; var queryHash = utils.toJson(params); if (!(queryHash in resource.completedQueries) && options.loadFromServer) { // This particular query has never been completed if (!resource.pendingQueries[queryHash]) { // This particular query has never even been started this.findAll(resourceName, params, options); } } // The query has been completed, so hit the cache with the query var filtered = utils.filter(resource.collection, function (value) { var keep = true; // Apply 'where' clauses if (params.query.where) { if (!utils.isObject(params.query.where)) { throw new errors.IllegalArgumentError(errorPrefix + 'params.query.where: Must be an object!', { params: { query: { where: { actual: typeof params.query.where, expected: 'object' } } } }); } utils.forOwn(params.query.where, function (value2, key2) { if (utils.isString(value2)) { value2 = { '===': value2 }; } if ('==' in value2) { keep = keep && (value[key2] == value2['==']); } else if ('===' in value2) { keep = keep && (value[key2] === value2['===']); } else if ('!=' in value2) { keep = keep && (value[key2] != value2['!=']); } else if ('>' in value2) { keep = keep && (value[key2] > value2['>']); } else if ('>=' in value2) { keep = keep && (value[key2] >= value2['>=']); } else if ('<' in value2) { keep = keep && (value[key2] < value2['<']); } else if ('<=' in value2) { keep = keep && (value[key2] <= value2['<=']); } else if ('in' in value2) { keep = keep && utils.contains(value2['in'], value[key2]); } }); } return keep; }); // Apply 'orderBy' if (params.query.orderBy) { if (utils.isString(params.query.orderBy)) { params.query.orderBy = [ [params.query.orderBy, 'ASC'] ]; } if (utils.isArray(params.query.orderBy)) { for (var i = 0; i < params.query.orderBy.length; i++) { if (utils.isString(params.query.orderBy[i])) { params.query.orderBy[i] = [params.query.orderBy[i], 'ASC']; } else if (!utils.isArray(params.query.orderBy[i])) { throw new errors.IllegalArgumentError(errorPrefix + 'params.query.orderBy[' + i + ']: Must be a string or an array!', { params: { query: { 'orderBy[i]': { actual: typeof params.query.orderBy[i], expected: 'string|array' } } } }); } filtered = utils.sort(filtered, function (a, b) { var cA = a[params.query.orderBy[i][0]], cB = b[params.query.orderBy[i][0]]; if (utils.isString(cA)) { cA = utils.upperCase(cA); } if (utils.isString(cB)) { cB = utils.upperCase(cB); } if (params.query.orderBy[i][1] === 'DESC') { if (cB < cA) { return -1; } else if (cB > cA) { return 1; } else { return 0; } } else { if (cA < cB) { return -1; } else if (cA > cB) { return 1; } else { return 0; } } }); } } else { throw new errors.IllegalArgumentError(errorPrefix + 'params.query.orderBy: Must be a string or an array!', { params: { query: { orderBy: { actual: typeof params.query.orderBy, expected: 'string|array' } } } }); } } // Apply 'limit' and 'skip' if (utils.isNumber(params.query.limit) && utils.isNumber(params.query.skip)) { filtered = utils.slice(filtered, params.query.skip, params.query.skip + params.query.limit); } else if (utils.isNumber(params.query.limit)) { filtered = utils.slice(filtered, 0, params.query.limit); } else if (utils.isNumber(params.query.skip)) { filtered = utils.slice(filtered, params.query.skip); } return filtered; } catch (err) { if (err instanceof errors.IllegalArgumentError) { throw err; } else { throw new errors.UnhandledError(err); } } } module.exports = filter; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],44:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.get(resourceName, id[, options]): '; /** * @doc method * @id DS.sync_methods:get * @name get * @description * Synchronously return the resource with the given id. The data store will forward the request to the server if the * item is not in the cache and `loadFromServer` is set to `true` in the options hash. * * ## Signature: * ```js * DS.get(resourceName, id[, options]) * ``` * * ## Example: * * ```js * DS.get('document', 5'); // { author: 'John Anderson', id: 5 } * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item to retrieve. * @param {object=} options Optional configuration. Properties: * - `{boolean=}` - `loadFromServer` - Send the query to server if it has not been sent yet. Default: `false`. * @returns {object} The item of the type specified by `resourceName` with the primary key specified by `id`. */ function get(resourceName, id, options) { options = options || {}; if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (!utils.isString(id) && !utils.isNumber(id)) { throw new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } }); } else if (!utils.isObject(options)) { throw new errors.IllegalArgumentError(errorPrefix + 'options: Must be an object!', { options: { actual: typeof options, expected: 'object' } }); } try { // cache miss, request resource from server if (!(id in services.store[resourceName].index) && options.loadFromServer) { this.find(resourceName, id).then(null, function (err) { throw err; }); } // return resource from cache return services.store[resourceName].index[id]; } catch (err) { throw new errors.UnhandledError(err); } } module.exports = get; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],45:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.hasChanges(resourceName, id): '; function diffIsEmpty(diff) { return !(utils.isEmpty(diff.added) && utils.isEmpty(diff.removed) && utils.isEmpty(diff.changed)); } /** * @doc method * @id DS.sync_methods:hasChanges * @name hasChanges * @description * Synchronously return whether object of the item of the type specified by `resourceName` that has the primary key * specified by `id` has changes. * * ## Signature: * ```js * DS.hasChanges(resourceName, id) * ``` * * ## Example: * * ```js * var d = DS.get('document', 5); // { author: 'John Anderson', id: 5 } * * d.author = 'Sally'; * * DS.hasChanges('document', 5); // true * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item. * @returns {boolean} Whether the item of the type specified by `resourceName` with the primary key specified by `id` has changes. */ function hasChanges(resourceName, id) { if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (!utils.isString(id) && !utils.isNumber(id)) { throw new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } }); } try { // return resource from cache if (id in services.store[resourceName].changes) { return diffIsEmpty(services.store[resourceName].changes[id]); } else { return false; } } catch (err) { throw new errors.UnhandledError(err); } } module.exports = hasChanges; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],46:[function(require,module,exports){ module.exports = { /** * @doc method * @id DS.sync_methods:defineResource * @name defineResource * @methodOf DS * @description * See [DS.defineResource](/documentation/api/api/DS.sync_methods:defineResource). */ defineResource: require('./defineResource'), /** * @doc method * @id DS.sync_methods:eject * @name eject * @methodOf DS * @description * See [DS.eject](/documentation/api/api/DS.sync_methods:eject). */ eject: require('./eject'), /** * @doc method * @id DS.sync_methods:filter * @name filter * @methodOf DS * @description * See [DS.filter](/documentation/api/api/DS.sync_methods:filter). */ filter: require('./filter'), /** * @doc method * @id DS.sync_methods:get * @name get * @methodOf DS * @description * See [DS.get](/documentation/api/api/DS.sync_methods:get). */ get: require('./get'), /** * @doc method * @id DS.sync_methods:inject * @name inject * @description * See [DS.inject](/documentation/api/api/DS.sync_methods:inject). */ inject: require('./inject'), /** * @doc method * @id DS.sync_methods:lastModified * @name lastModified * @methodOf DS * @description * See [DS.lastModified](/documentation/api/api/DS.sync_methods:lastModified). */ lastModified: require('./lastModified'), /** * @doc method * @id DS.sync_methods:lastSaved * @name lastSaved * @methodOf DS * @description * See [DS.lastSaved](/documentation/api/api/DS.sync_methods:lastSaved). */ lastSaved: require('./lastSaved'), /** * @doc method * @id DS.sync_methods:digest * @name digest * @methodOf DS * @description * See [DS.digest](/documentation/api/api/DS.sync_methods:digest). */ digest: require('./digest'), /** * @doc method * @id DS.sync_methods:changes * @name changes * @methodOf DS * @description * See [DS.changes](/documentation/api/api/DS.sync_methods:changes). */ changes: require('./changes'), /** * @doc method * @id DS.sync_methods:previous * @name previous * @methodOf DS * @description * See [DS.previous](/documentation/api/api/DS.sync_methods:previous). */ previous: require('./previous'), /** * @doc method * @id DS.sync_methods:hasChanges * @name hasChanges * @methodOf DS * @description * See [DS.hasChanges](/documentation/api/api/DS.sync_methods:hasChanges). */ hasChanges: require('./hasChanges') }; },{"./changes":39,"./defineResource":40,"./digest":41,"./eject":42,"./filter":43,"./get":44,"./hasChanges":45,"./inject":47,"./lastModified":48,"./lastSaved":49,"./previous":50}],47:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), observe = require('observejs'), errorPrefix = 'DS.inject(resourceName, attrs[, options]): '; function _inject(resource, attrs) { var _this = this; function _react(added, removed, changed, getOldValueFn) { try { var innerId = getOldValueFn(resource.idAttribute); resource.changes[innerId] = utils.diffObjectFromOldObject(resource.index[innerId], resource.previous_attributes[innerId]); resource.modified[innerId] = utils.updateTimestamp(resource.modified[innerId]); resource.collectionModified = utils.updateTimestamp(resource.collectionModified); if (resource.idAttribute in changed) { services.$log.error('Doh! You just changed the primary key of an object! ' + 'I don\'t know how to handle this yet, so your data for the "' + resource.name + '" resource is now in an undefined (probably broken) state.'); } } catch (err) { throw new errors.UnhandledError(err); } } if (utils.isArray(attrs)) { for (var i = 0; i < attrs.length; i++) { _inject.call(_this, resource, attrs[i]); } } else { if (!(resource.idAttribute in attrs)) { throw new errors.RuntimeError(errorPrefix + 'attrs: Must contain the property specified by `idAttribute`!'); } else { var id = attrs[resource.idAttribute]; if (!(id in resource.index)) { resource.index[id] = {}; resource.previous_attributes[id] = {}; utils.deepMixIn(resource.index[id], attrs); utils.deepMixIn(resource.previous_attributes[id], attrs); resource.collection.push(resource.index[id]); resource.observers[id] = new observe.ObjectObserver(resource.index[id], _react); _react({}, {}, {}, function () { return id; }); } else { utils.deepMixIn(resource.index[id], attrs); resource.observers[id].deliver(); } } } } /** * @doc method * @id DS.sync_methods:inject * @name inject * @description * Inject the given item into the data store as the specified type. If `attrs` is an array, inject each item into the * data store. Injecting an item into the data store does not save it to the server. * * ## Signature: * ```js * DS.inject(resourceName, attrs[, options]) * ``` * * ## Examples: * * ```js * DS.get('document', 45); // undefined * * DS.inject('document', { title: 'How to Cook', id: 45 }); * * DS.get('document', 45); // { title: 'How to Cook', id: 45 } * ``` * * Inject a collection into the data store: * * ```js * DS.filter('document'); // [ ] * * DS.inject('document', [ { title: 'How to Cook', id: 45 }, { title: 'How to Eat', id: 46 } ]); * * DS.filter('document'); // [ { title: 'How to Cook', id: 45 }, { title: 'How to Eat', id: 46 } ] * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {object|array} attrs The item or collection of items to inject into the data store. * @param {object=} options Optional configuration. Properties: * - `{string=}` - `mergeStrategy` - Specify the merge strategy to use if the item is already in the cache. Default: `"mergeWithExisting"`. * @returns {object|array} A reference to the item that was injected into the data store or an array of references to * the items that were injected into the data store. */ function inject(resourceName, attrs, options) { options = options || {}; if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (!utils.isObject(attrs) && !utils.isArray(attrs)) { throw new errors.IllegalArgumentError(errorPrefix + 'attrs: Must be an object or an array!', { attrs: { actual: typeof attrs, expected: 'object|array' } }); } else if (!utils.isObject(options)) { throw new errors.IllegalArgumentError(errorPrefix + 'options: Must be an object!', { options: { actual: typeof options, expected: 'object' } }); } var resource = services.store[resourceName], _this = this; try { if (!services.$rootScope.$$phase) { services.$rootScope.$apply(function () { _inject.apply(_this, [services.store[resourceName], attrs]); }); } else { _inject.apply(_this, [services.store[resourceName], attrs]); } return attrs; } catch (err) { if (!(err instanceof errors.RuntimeError)) { throw new errors.UnhandledError(err); } else { throw err; } } } module.exports = inject; },{"errors":"hIh4e1","observejs":"u+GZEJ","services":"cX8q+p","utils":"uE/lJt"}],48:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.lastModified(resourceName[, id]): '; /** * @doc method * @id DS.sync_methods:lastModified * @name lastModified * @description * Return the timestamp of the last time either the collection for `resourceName` or the item of type `resourceName` * with the given primary key was modified. * * ## Signature: * ```js * DS.lastModified(resourceName[, id]) * ``` * * ## Example: * * ```js * DS.lastModified('document', 5); // undefined * * DS.find('document', 5).then(function (document) { * DS.lastModified('document', 5); // 1234235825494 * }); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number=} id The primary key of the item to remove. * @returns {number} The timestamp of the last time either the collection for `resourceName` or the item of type * `resourceName` with the given primary key was modified. */ function lastModified(resourceName, id) { if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (id && !utils.isString(id) && !utils.isNumber(id)) { throw new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } }); } try { if (id) { if (!(id in services.store[resourceName].modified)) { services.store[resourceName].modified[id] = 0; } return services.store[resourceName].modified[id]; } return services.store[resourceName].collectionModified; } catch (err) { throw new errors.UnhandledError(err); } } module.exports = lastModified; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],49:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.lastSaved(resourceName[, id]): '; /** * @doc method * @id DS.sync_methods:lastSaved * @name lastSaved * @description * Return the timestamp of the last time either the collection for `resourceName` or the item of type `resourceName` * with the given primary key was saved via an async adapter. * * ## Signature: * ```js * DS.lastSaved(resourceName[, id]) * ``` * * ## Example: * * ```js * DS.lastModified('document', 5); // undefined * DS.lastSaved('document', 5); // undefined * * DS.find('document', 5).then(function (document) { * DS.lastModified('document', 5); // 1234235825494 * DS.lastSaved('document', 5); // 1234235825494 * * document.author = 'Sally'; * * DS.lastModified('document', 5); // 1234304985344 - something different * DS.lastSaved('document', 5); // 1234235825494 - still the same * }); * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number=} id The primary key of the item to remove. * @returns {number} The timestamp of the last time either the collection for `resourceName` or the item of type * `resourceName` with the given primary key was modified. */ function lastSaved(resourceName, id) { if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (id && !utils.isString(id) && !utils.isNumber(id)) { throw new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } }); } try { if (id) { if (!(id in services.store[resourceName].saved)) { services.store[resourceName].saved[id] = 0; } return services.store[resourceName].saved[id]; } return services.store[resourceName].collectionModified; } catch (err) { throw new errors.UnhandledError(err); } } module.exports = lastSaved; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],50:[function(require,module,exports){ var utils = require('utils'), errors = require('errors'), services = require('services'), errorPrefix = 'DS.previous(resourceName, id): '; /** * @doc method * @id DS.sync_methods:previous * @name previous * @description * Synchronously return the previous attributes of the item of the type specified by `resourceName` that has the primary key * specified by `id`. This object represents the state of the item the last time it was saved via an async adapter. * * ## Signature: * ```js * DS.previous(resourceName, id) * ``` * * ## Example: * * ```js * var d = DS.get('document', 5); // { author: 'John Anderson', id: 5 } * * d.author = 'Sally'; * * d; // { author: 'Sally', id: 5 } * * DS.previous('document', 5); // { author: 'John Anderson', id: 5 } * ``` * * ## Throws * * - `{IllegalArgumentError}` * - `{RuntimeError}` * - `{UnhandledError}` * * @param {string} resourceName The resource type, e.g. 'user', 'comment', etc. * @param {string|number} id The primary key of the item whose previous attributes are to be retrieved. * @returns {object} The previous attributes of the item of the type specified by `resourceName` with the primary key specified by `id`. */ function previous(resourceName, id) { if (!services.store[resourceName]) { throw new errors.RuntimeError(errorPrefix + resourceName + ' is not a registered resource!'); } else if (!utils.isString(id) && !utils.isNumber(id)) { throw new errors.IllegalArgumentError(errorPrefix + 'id: Must be a string or a number!', { id: { actual: typeof id, expected: 'string|number' } }); } try { // return resource from cache return angular.copy(services.store[resourceName].previous_attributes[id]); } catch (err) { throw new errors.UnhandledError(err); } } module.exports = previous; },{"errors":"hIh4e1","services":"cX8q+p","utils":"uE/lJt"}],"errors":[function(require,module,exports){ module.exports=require('hIh4e1'); },{}],"hIh4e1":[function(require,module,exports){ /** * @doc function * @id errors.types:UnhandledError * @name UnhandledError * @description Error that is thrown/returned when Reheat encounters an uncaught/unknown exception. * @param {Error} error The originally thrown error. * @returns {UnhandledError} A new instance of `UnhandledError`. */ function UnhandledError(error) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } error = error || {}; /** * @doc property * @id errors.types:UnhandledError.type * @name type * @propertyOf errors.types:UnhandledError * @description Name of error type. Default: `"UnhandledError"`. */ this.type = this.constructor.name; /** * @doc property * @id errors.types:UnhandledError.originalError * @name originalError * @propertyOf errors.types:UnhandledError * @description A reference to the original error that was thrown. */ this.originalError = error; /** * @doc property * @id errors.types:UnhandledError.message * @name message * @propertyOf errors.types:UnhandledError * @description Message and stack trace. Same as `UnhandledError#stack`. */ this.message = 'UnhandledError: This is an uncaught exception. Please consider submitting an issue at https://github.com/jmdobry/angular-data/issues.\n\n' + 'Original Uncaught Exception:\n' + (error.stack ? error.stack.toString() : error.stack); /** * @doc property * @id errors.types:UnhandledError.stack * @name stack * @propertyOf errors.types:UnhandledError * @description Message and stack trace. Same as `UnhandledError#message`. */ this.stack = this.message; } UnhandledError.prototype = Object.create(Error.prototype); UnhandledError.prototype.constructor = UnhandledError; /** * @doc function * @id errors.types:IllegalArgumentError * @name IllegalArgumentError * @description Error that is thrown/returned when a caller does not honor the pre-conditions of a method/function. * @param {string=} message Error message. Default: `"Illegal Argument!"`. * @param {object=} errors Object containing information about the error. * @returns {IllegalArgumentError} A new instance of `IllegalArgumentError`. */ function IllegalArgumentError(message, errors) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } /** * @doc property * @id errors.types:IllegalArgumentError.type * @name type * @propertyOf errors.types:IllegalArgumentError * @description Name of error type. Default: `"IllegalArgumentError"`. */ this.type = this.constructor.name; /** * @doc property * @id errors.types:IllegalArgumentError.errors * @name errors * @propertyOf errors.types:IllegalArgumentError * @description Object containing information about the error. */ this.errors = errors || {}; /** * @doc property * @id errors.types:IllegalArgumentError.message * @name message * @propertyOf errors.types:IllegalArgumentError * @description Error message. Default: `"Illegal Argument!"`. */ this.message = message || 'Illegal Argument!'; } IllegalArgumentError.prototype = Object.create(Error.prototype); IllegalArgumentError.prototype.constructor = IllegalArgumentError; /** * @doc function * @id errors.types:ValidationError * @name ValidationError * @description Error that is thrown/returned when validation of a schema fails. * @param {string=} message Error message. Default: `"Validation Error!"`. * @param {object=} errors Object containing information about the error. * @returns {ValidationError} A new instance of `ValidationError`. */ function ValidationError(message, errors) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } /** * @doc property * @id errors.types:ValidationError.type * @name type * @propertyOf errors.types:ValidationError * @description Name of error type. Default: `"ValidationError"`. */ this.type = this.constructor.name; /** * @doc property * @id errors.types:ValidationError.errors * @name errors * @propertyOf errors.types:ValidationError * @description Object containing information about the error. */ this.errors = errors || {}; /** * @doc property * @id errors.types:ValidationError.message * @name message * @propertyOf errors.types:ValidationError * @description Error message. Default: `"Validation Error!"`. */ this.message = message || 'Validation Error!'; } ValidationError.prototype = Object.create(Error.prototype); ValidationError.prototype.constructor = ValidationError; /** * @doc function * @id errors.types:RuntimeError * @name RuntimeError * @description Error that is thrown/returned for invalid state during runtime. * @param {string=} message Error message. Default: `"Runtime Error!"`. * @param {object=} errors Object containing information about the error. * @returns {RuntimeError} A new instance of `RuntimeError`. */ function RuntimeError(message, errors) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } /** * @doc property * @id errors.types:RuntimeError.type * @name type * @propertyOf errors.types:RuntimeError * @description Name of error type. Default: `"RuntimeError"`. */ this.type = this.constructor.name; /** * @doc property * @id errors.types:RuntimeError.errors * @name errors * @propertyOf errors.types:RuntimeError * @description Object containing information about the error. */ this.errors = errors || {}; /** * @doc property * @id errors.types:RuntimeError.message * @name message * @propertyOf errors.types:RuntimeError * @description Error message. Default: `"Runtime Error!"`. */ this.message = message || 'RuntimeError Error!'; } RuntimeError.prototype = Object.create(Error.prototype); RuntimeError.prototype.constructor = RuntimeError; /** * @doc interface * @id errors * @name angular-data error types * @description * `UnhandledError`, `IllegalArgumentError`, `RuntimeError` and `ValidationError`. * * References to the constructor functions of these errors can be found at `DS.errors`. */ module.exports = { UnhandledError: UnhandledError, IllegalArgumentError: IllegalArgumentError, ValidationError: ValidationError, RuntimeError: RuntimeError }; },{}],53:[function(require,module,exports){ (function (window, angular, undefined) { 'use strict'; // angular.module('jmdobry.binary-heap', []); // // /** // * @doc interface // * @id BinaryHeapProvider // * @name BinaryHeapProvider // */ // function BinaryHeapProvider() { // // var defaults = require('./binaryHeap/defaults'); // // /** // * @doc method // * @id BinaryHeapProvider.methods:setDefaultWeightFunction // * @name setDefaultWeightFunction // * @param {function} weightFunc New default weight function. // */ // function setDefaultWeightFunction(weightFunc) { // if (!angular.isFunction(weightFunc)) { // throw new Error('BinaryHeapProvider.setDefaultWeightFunction(weightFunc): weightFunc: Must be a function!'); // } // defaults.userProvidedDefaultWeightFunc = weightFunc; // } // // /** // * @doc method // * @id BinaryHeapProvider.methods:setDefaultWeightFunction // * @name setDefaultWeightFunction // * @methodOf BinaryHeapProvider // * @param {function} weightFunc New default weight function. // */ // this.setDefaultWeightFunction = setDefaultWeightFunction; // // this.$get = function () { // return require('./binaryHeap'); // }; // } // angular.module('jmdobry.binary-heap').provider('BinaryHeap', BinaryHeapProvider); angular.module('jmdobry.angular-data', ['ng'/*, 'jmdobry.binary-heap'*/]).config(['$provide', function ($provide) { $provide.decorator('$q', function ($delegate) { // do whatever you you want $delegate.promisify = function (fn, target) { var _this = this; return function () { var deferred = _this.defer(), args = Array.prototype.slice.apply(arguments); args.push(function (err, result) { if (err) { deferred.reject(err); } else { deferred.resolve(result); } }); try { fn.apply(target || this, args); } catch (err) { deferred.reject(err); } return deferred.promise; }; }; return $delegate; }); }]); angular.module('jmdobry.angular-data').provider('DS', require('./datastore')); })(window, window.angular); },{"./datastore":36}],"uE/lJt":[function(require,module,exports){ module.exports = { isString: angular.isString, isArray: angular.isArray, isObject: angular.isObject, isNumber: angular.isNumber, isFunction: angular.isFunction, isEmpty: require('mout/lang/isEmpty'), toJson: angular.toJson, makePath: require('mout/string/makePath'), upperCase: require('mout/string/upperCase'), deepMixIn: require('mout/object/deepMixIn'), forOwn: require('mout/object/forOwn'), contains: require('mout/array/contains'), filter: require('mout/array/filter'), toLookup: require('mout/array/toLookup'), slice: require('mout/array/slice'), sort: require('mout/array/sort'), updateTimestamp: function (timestamp) { var newTimestamp = typeof Date.now === 'function' ? Date.now() : new Date().getTime(); if (timestamp && newTimestamp <= timestamp) { return timestamp + 1; } else { return newTimestamp; } }, deepFreeze: function deepFreeze(o) { if (typeof Object.freeze === 'function') { var prop, propKey; Object.freeze(o); // First freeze the object. for (propKey in o) { prop = o[propKey]; if (!o.hasOwnProperty(propKey) || typeof prop !== 'object' || Object.isFrozen(prop)) { // If the object is on the prototype, not an object, or is already frozen, // skip it. Note that this might leave an unfrozen reference somewhere in the // object if there is an already frozen object containing an unfrozen object. continue; } deepFreeze(prop); // Recursively call deepFreeze. } } }, diffObjectFromOldObject: function (object, oldObject) { var added = {}; var removed = {}; var changed = {}; for (var prop in oldObject) { var newValue = object[prop]; if (newValue !== undefined && newValue === oldObject[prop]) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop2 in object) { if (prop2 in oldObject) continue; added[prop2] = object[prop2]; } return { added: added, removed: removed, changed: changed }; } }; },{"mout/array/contains":3,"mout/array/filter":4,"mout/array/slice":7,"mout/array/sort":8,"mout/array/toLookup":9,"mout/lang/isEmpty":14,"mout/object/deepMixIn":21,"mout/object/forOwn":23,"mout/string/makePath":25,"mout/string/upperCase":26}],"utils":[function(require,module,exports){ module.exports=require('uE/lJt'); },{}]},{},[53])
src/components/ContentDropdown/spec.js
quran/quran.com-frontend
import React from 'react'; import { mountWithIntl } from '../../../tests/helpers/intl-enzyme-test-helper.js'; import ContentDropdown, { slugs } from './index'; let wrapper; let onOptionChange = sinon.stub(); const defaultOption = 19; describe('<ContentDropdown />', () => { beforeEach(() => { onOptionChange = sinon.stub(); wrapper = mountWithIntl( <ContentDropdown content={[defaultOption]} onOptionChange={onOptionChange} /> ); }); it('should render', () => { expect(wrapper).to.be.ok; // eslint-disable-line }); it('should contain all the content options', () => { slugs.filter(slug => slug.language !== 'ar').forEach((slug) => { expect(wrapper.text()).to.contain(slug.name); }); }); it('should show chosen content option', () => { expect(wrapper.find(`#${defaultOption}en`).prop('checked')).to.equal(defaultOption); }); it('should add option when clicked', () => { const id = 18; wrapper.find(`#${id}en`).simulate('change'); expect(onOptionChange).to.have.been.called; // eslint-disable-line expect(onOptionChange).to.have.been.calledWith({ content: [defaultOption, id] }); }); it('should remove option when clicked', () => { wrapper.find(`#${defaultOption}en`).simulate('change'); expect(onOptionChange).to.have.been.called; // eslint-disable-line expect(onOptionChange).to.have.been.calledWith({ content: [] }); }); it('should remove all content', () => { const removeAll = wrapper.find('a'); expect(removeAll.html()).to.contain('Remove all'); removeAll.simulate('click'); expect(onOptionChange).to.have.been.called; // eslint-disable-line expect(onOptionChange).to.have.been.calledWith({ content: [] }); }); });
static/goview/js/pygal-tooltips.js
fridex/gofed-web
// Generated by CoffeeScript 1.6.3 (function() { var get_translation, init, padding, r_translation, tooltip_timeout; padding = 5; tooltip_timeout = 0; r_translation = /translate\((\d+)[ ,]+(\d+)\)/; get_translation = function($elt) { return (r_translation.exec($elt.attr('transform')) || []).slice(1); }; init = function(ctx) { var tooltip, untooltip; $vg('.text-overlay .series', ctx).hide(); $vg('.reactive', ctx).hover((function() { return $vg(this).addClass('active'); }), (function() { return $vg(this).removeClass('active'); })); $vg('.activate-serie', ctx).hover((function() { var num; num = this.id.replace('activate-serie-', ''); $vg('.text-overlay .serie-' + num, ctx).show(); return $vg('.serie-' + num + ' .reactive', ctx).addClass('active'); }), function() { var num; num = this.id.replace('activate-serie-', ''); $vg('.text-overlay .serie-' + num, ctx).hide(); return $vg('.serie-' + num + ' .reactive', ctx).removeClass('active'); }); $vg('.tooltip-trigger', ctx).hover((function() { return tooltip($vg(this)); }), (function() { return untooltip(); })); tooltip = function($elt) { var $label, $rect, $text, $tooltip, $value, current_x, current_y, h, target, w, x, x_elt, xlink, y, y_elt, _ref; clearTimeout(tooltip_timeout); $tooltip = $vg('#tooltip,.tooltip', ctx).css({ opacity: 1 }).show(); $text = $tooltip.find('text'); $label = $tooltip.find('tspan.label'); $value = $tooltip.find('tspan.value'); $rect = $tooltip.find('rect'); if ($elt.siblings('.tooltip').size()) { $label.text($elt.siblings('.tooltip').text()); $value.text(''); } else { $label.text($elt.siblings('.label').text()); $value.text($elt.siblings('.value').text()); } xlink = $elt.siblings('.xlink').text() || null; target = $elt.parent().attr('target'); if (xlink) { $tooltip.find('a').attr('href', xlink).attr('target', target); } $text.attr('x', padding); $text.attr('y', padding + this.config.tooltip_font_size); $value.attr('x', padding); $value.attr('dy', $label.text() ? this.config.tooltip_font_size + padding : 0); w = $text.width() + 2 * padding; h = $text.height() + 2 * padding; $rect.attr('width', w); $rect.attr('height', h); x_elt = $elt.siblings('.x'); y_elt = $elt.siblings('.y'); x = parseInt(x_elt.text()); if (x_elt.hasClass('centered')) { x -= w / 2; } else if (x_elt.hasClass('left')) { x -= w; } y = parseInt(y_elt.text()); if (y_elt.hasClass('centered')) { y -= h / 2; } else if (y_elt.hasClass('top')) { y -= h; } _ref = get_translation($tooltip), current_x = _ref[0], current_y = _ref[1]; if (current_x === x && current_y === y) { return; } return $tooltip.attr('transform', "translate(" + x + " " + y + ")"); }; return untooltip = function() { return tooltip_timeout = setTimeout((function() { return $vg('#tooltip,.tooltip', ctx).hide().css({ opacity: 0 }); }), 1000); }; }; this.init_svg = function(ctx) { if (navigator.userAgent.indexOf('Trident') > -1 || navigator.userAgent.indexOf('MSIE') > -1) { $vg('.tooltip a').children().unwrap(); } return init($vg(ctx)); }; $vg(function() { var $charts; $charts = $vg('.pygal-chart'); if ($charts.size()) { return $charts.each(function() { return init_svg(this); }); } else { return init(); } }); }).call(this);
packages/core/src/mixins/renderToLayer.js
iCHEF/gypcrete
import React, { Component } from 'react'; import { createPortal } from 'react-dom'; import prefixClass from '../utils/prefixClass'; import getComponentName from '../utils/getComponentName'; import randId from '../utils/randId'; import '../styles/RenderToLayer.scss'; const COMPONENT_NAME = prefixClass('base-layer'); const LAYER_ID_PREFIX = 'layer'; export function createLayer() { const layer = document.createElement('div'); layer.className = COMPONENT_NAME; layer.id = randId({ prefix: LAYER_ID_PREFIX }); return layer; } /** * renderToLayer() HOC mixin * ========================= * Render a component to an node outside of React root, * using `React.createPortal()`. * * @param {React.ComponentType<any>} WrappedComponent * * @example * const ExternalComponent = renderToLayer(Component); */ function renderToLayer(WrappedComponent) { const componentName = getComponentName(WrappedComponent); class RenderToLayer extends Component { static displayName = `renderToLayer(${componentName})`; state = { inDOM: false, }; constructor(props) { super(props); this.baseLayer = createLayer(); } componentDidMount() { document.body.appendChild(this.baseLayer); /** * Render null before base layer is put in DOM for 'renderToLayer()' mixin. * * This is the current behavior of v1.x. * It prevents an issue with 'anchored()' mixin where it can retrieve * incorrect rects from self DOM node when calculating its own position, * due to its parent node (the layer) isn't inserted to DOM yet. */ this.setState({ inDOM: true }); } componentWillUnmount() { document.body.removeChild(this.baseLayer); } render() { const { inDOM } = this.state; return inDOM && createPortal( <WrappedComponent {...this.props} />, this.baseLayer, ); } } return RenderToLayer; } export default renderToLayer;
src/blog/flux/views/components/widgets/Header.js
exseed/exseed-boilerplate
import React from 'react'; export default class Header extends React.Component { render() { const { value } = this.props; const level = Number(value.level); if (1 <= level && level <= 5) { const subheader = value.subheader !== '' && <div className="sub header">{value.subheader}</div>; return React.createElement( `h${level}`, { className: 'ui header' }, value.header, subheader); } else { return ( <span>Cannot render header</span> ); } } };
src/svg-icons/action/zoom-out.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionZoomOut = (props) => ( <SvgIcon {...props}> <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14zM7 9h5v1H7z"/> </SvgIcon> ); ActionZoomOut = pure(ActionZoomOut); ActionZoomOut.displayName = 'ActionZoomOut'; ActionZoomOut.muiName = 'SvgIcon'; export default ActionZoomOut;
app/routes/user/IndexRoute.js
ryrudnev/dss-wm
import React from 'react'; import Helmet from 'react-helmet'; import { Route } from '../../core/router'; import { Collection as Users } from '../../entities/User'; import { PageHeader, Row, Col } from 'react-bootstrap'; import NavLink from '../../components/NavLink'; import GridContainer from '../../components/GridContainer'; import Progress from 'react-progress-2'; import radio from 'backbone.radio'; const session = radio.channel('session'); export default class MethodTypeIndexRoute extends Route { breadcrumb = 'Просмотр пользователей' authorize() { return session.request('currentUser').get('role') === 'admin'; } fetch() { this.users = new Users; return this.users.fetch(); } render() { const actions = props => ( <div> <NavLink to={`/users/${props.rowData.id}`} style={{ marginRight: '15px' }}> <i className="fa fa-eye" aria-hidden="true" /> </NavLink> <NavLink to={`/users/${props.rowData.id}/edit`} style={{ marginRight: '15px' }}> <i className="fa fa-pencil" aria-hidden="true" /> </NavLink> <a href="javascript:;" onClick={() => { Progress.show(); const model = this.users.findWhere({ id: props.rowData.id }); model.destroy({ wait: true, success: () => Progress.hide() }); }} > <i className="fa fa-ban" aria-hidden="true" /> </a> </div> ); return ( <div> <Helmet title="Пользователи" /> <PageHeader>Пользователи</PageHeader> <ul className="nav menu-nav-pills"> <li> <NavLink to="/users/new"> <i className="fa fa-plus-square" aria-hidden="true" /> Зарегистрировать </NavLink> </li> </ul> <Row> <Col md={12}> <GridContainer collection={this.users} columns={['id', 'username', 'role']} columnMetadata={[ { columnName: 'username', order: 1, displayName: 'Логин' }, { columnName: 'role', order: 2, displayName: 'Роль' }, { columnName: 'subjects', order: 3, displayName: 'Компании', visible: false }, { order: 4, displayName: 'Действия', columnName: 'id', sortable: false, customComponent: actions, }, ]} /> </Col> </Row> </div> ); } }
pages/utils/popovers.js
cherniavskii/material-ui
import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from 'docs/src/pages/utils/popovers/popovers.md'; function Page() { return ( <MarkdownDocs markdown={markdown} demos={{ 'pages/utils/popovers/AnchorPlayground.js': { js: require('docs/src/pages/utils/popovers/AnchorPlayground').default, raw: preval` module.exports = require('fs') .readFileSync(require.resolve('docs/src/pages/utils/popovers/AnchorPlayground'), 'utf8') `, }, 'pages/utils/popovers/MouseOverPopover.js': { js: require('docs/src/pages/utils/popovers/MouseOverPopover').default, raw: preval` module.exports = require('fs') .readFileSync(require.resolve('docs/src/pages/utils/popovers/MouseOverPopover'), 'utf8') `, }, }} /> ); } export default withRoot(Page);
examples/huge-apps/routes/Course/routes/Assignments/routes/Assignment/components/Assignment.js
brandonlilly/react-router
import React from 'react'; class Assignment extends React.Component { render () { var { courseId, assignmentId } = this.props.params; var { title, body } = COURSES[courseId].assignments[assignmentId] return ( <div> <h4>{title}</h4> <p>{body}</p> </div> ); } } export default Assignment;
internals/scripts/dependencies.js
Honyrik/my_msg
// No need to build the DLL in production if (process.env.NODE_ENV === 'production') { process.exit(0); } require('shelljs/global'); const path = require('path'); const fs = require('fs'); const exists = fs.existsSync; const writeFile = fs.writeFileSync; const defaults = require('lodash/defaultsDeep'); const pkg = require(path.join(process.cwd(), 'package.json')); const config = require('../config'); const dllConfig = defaults(pkg.dllPlugin, config.dllPlugin.defaults); const outputPath = path.join(process.cwd(), dllConfig.path); const dllManifestPath = path.join(outputPath, 'package.json'); /** * I use node_modules/react-boilerplate-dlls by default just because * it isn't going to be version controlled and babel wont try to parse it. */ mkdir('-p', outputPath); echo('Building the Webpack DLL...'); /** * Create a manifest so npm install doesn't warn us */ if (!exists(dllManifestPath)) { writeFile( dllManifestPath, JSON.stringify(defaults({ name: 'react-boilerplate-dlls', private: true, author: pkg.author, repository: pkg.repository, version: pkg.version, }), null, 2), 'utf8' ); } // the BUILDING_DLL env var is set to avoid confusing the development environment exec('cross-env BUILDING_DLL=true webpack --display-chunks --color --config internals/webpack/webpack.dll.babel.js');
packages/material-ui-icons/src/RingVolume.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0z" /><path d="M23.71 16.67C20.66 13.78 16.54 12 12 12 7.46 12 3.34 13.78.29 16.67c-.18.18-.29.43-.29.71 0 .28.11.53.29.71l2.48 2.48c.18.18.43.29.71.29.27 0 .52-.11.7-.28.79-.74 1.69-1.36 2.66-1.85.33-.16.56-.5.56-.9v-3.1c1.45-.48 3-.73 4.6-.73s3.15.25 4.6.72v3.1c0 .39.23.74.56.9.98.49 1.87 1.12 2.66 1.85.18.18.43.28.7.28.28 0 .53-.11.71-.29l2.48-2.48c.18-.18.29-.43.29-.71 0-.27-.11-.52-.29-.7zM21.16 6.26l-1.41-1.41-3.56 3.55 1.41 1.41s3.45-3.52 3.56-3.55zM13 2h-2v5h2V2zM6.4 9.81L7.81 8.4 4.26 4.84 2.84 6.26c.11.03 3.56 3.55 3.56 3.55z" /></React.Fragment> , 'RingVolume');
src/app/views/userProfile.js
benigeri/soapee-ui
import _ from 'lodash'; import React from 'react'; import Reflux from 'reflux'; import { State, Link } from 'react-router'; import { Button } from 'react-bootstrap'; import userActions from 'actions/user'; import meActions from 'actions/me'; import userProfileStore from 'stores/userProfile'; import userRecipesStore from 'stores/userRecipes'; import userFriendsStore from 'stores/userFriends'; import authStore from 'stores/auth'; import UserAvatar from 'components/userAvatar'; import MarkedDisplay from 'components/markedDisplay'; import RecipesLinkTable from 'components/recipesLinkTable'; import Spinner from 'components/spinner'; export default React.createClass( { statics: { willTransitionTo: function ( transition, params ) { userActions.getProfile( params.id ); } }, mixins: [ State, Reflux.connect( userProfileStore, 'user' ), Reflux.connect( userRecipesStore, 'recipes' ), Reflux.connect( userFriendsStore, 'friends' ) ], getInitialState() { return { display: { addFriend: true } }; }, render() { return ( <div id="user-profile"> { this.renderLoading() } { this.renderUserProfile() } </div> ); }, renderUserProfile() { let user = this.state.user; if ( this.pageIsForUser() ) { return ( <div className="user-profile"> <legend>{ user.name } Public Profile</legend> <div className="profile-avatar"> <UserAvatar user={ user } /> </div> { user.about && <div className="jumbotron compact"> <MarkedDisplay content={ user.about } /> </div> } { this.renderFriends() } { this.renderUserRecipes() } </div> ); } }, renderFriends() { let addFriendButton; let willRender; function renderFriend( user ) { return ( <Link className="friend-profile-link" to="userProfile" params={ { id: user.id } }> <UserAvatar user={ user } showTooltip={ true } /> </Link> ); } if ( this.state.display.addFriend && this.isNotMe() && userFriendsStore.iAmNotFriendOfUser() ) { if ( authStore.isAuthenticated() ) { addFriendButton = ( <Button bsStyle="primary" onClick={ this.addFriend } className="button-add-friend" > <i className="fa fa-smile-o"> Add Friend</i> </Button> ); } } willRender = typeof addFriendButton !== 'undefined' || this.state.friends.length > 0; return ( <div className="friends clearfix"> { willRender && <legend>Friends</legend> } { addFriendButton } { _.map( this.state.friends, renderFriend, this ) } </div> ); }, renderUserRecipes() { if ( this.state.recipes.length ) { return ( <div className="user-recipes"> <legend>Public Recipes</legend> <RecipesLinkTable recipes={ this.state.recipes } /> </div> ); } }, renderLoading() { if ( !(this.pageIsForUser()) ) { return <Spinner />; } }, pageIsForUser() { let requested = Number( this.getParams().id ); let got = Number( _.get( this.state.user, 'id' ) ); return requested === got; }, isNotMe() { return !(authStore.isMyId( _.get( this.state.user, 'id' ) )); }, addFriend() { meActions.addFriend( this.state.user ) .then( this.hideAddFriend ) .then( this.notifySent ) .catch( this.showError ); }, hideAddFriend() { this.setState( { display: { addFriend: false } } ); }, notifySent() { $.bootstrapGrowl( `Friend Request Sent to ${this.state.user.name}`, { type: 'warning', delay: 5000 } ); }, showError( e ) { if ( e.status === 422 ) { $.bootstrapGrowl( `Friend Request has already been sent to ${this.state.user.name}`, { type: 'danger', delay: 5000 } ); } else { $.bootstrapGrowl( 'Unknown error has occurred. Please contact us on our Facebook Page or sub-Reddit; links are in the home page', { type: 'danger', delay: 5000 } ); } } } );
ajax/libs/yui/3.3.0/event-custom/event-custom-base.js
pazguille/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: {}, /** * Execute the supplied method before the specified function * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * Execute the supplied method after the specified function * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method after the specified function * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription * @method detach * @param handle {string} the subscription handle */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property Do.originalRetVal * @static * @since 2.3.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property Do.currentRetVal * @static * @since 2.3.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { delete this.before[sid]; delete this.after[sid]; }; /** * Execute the wrapped method * @method exec */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. An example would be a service that scrubs * out illegal characters prior to executing the core business logic. * @class Do.AlterArgs */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller * @class Do.AlterReturn */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. * @class Do.Halt */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute * @class Do.Prevent */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * @type CustomEvent */ this.evt = evt; /** * The subscriber object * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber {} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; this.subCount = 0; this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { hasSubs: function(when) { var s = this.subCount, a = this.afterCount, sib = this.sibling; if (sib) { s += sib.subCount; a += sib.afterCount; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = Y.Array(arguments, 0, true); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling; if (sib) { Y.mix(s, sib.subscribers); Y.mix(a, sib.afters); } return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this.afters[s.id] = s; this.afterCount++; } else { this.subscribers[s.id] = s; this.subCount++; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; if (this.host) { this.host._monitor('attach', this.type, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = Y.merge(this.subscribers, this.afters); for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @private */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { // this._procSubs(Y.merge(this.subscribers, this.afters), args); var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { args[0] = args[0] || {}; return this.fireSimple(args); }, _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * @method _delete * @param subscriber object. * @private */ _delete: function(s) { if (s) { if (this.subscribers[s.id]) { delete this.subscribers[s.id]; this.subCount--; } if (this.afters[s.id]) { delete this.afters[s.id]; this.afterCount--; } } if (this.host) { this.host._monitor('detach', this.type, { ce: this, sub: s }); } if (s) { // delete s.fn; // delete s.context; s.deleted = true; } } }; ///////////////////////////////////////////////////////////////////// /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {string} the prefix to apply to non-prefixed event names * @config chain {boolean} if true, on/after/detach return the host to allow * chaining, otherwise they return an EventHandle (default false) */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', YArray = Y.Array, _wildType = Y.cached(function(type) { return type.replace(/(.*)(:)(.*)/, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {string} type the type * @param {string} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe to a custom event hosted by this object * @method on * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ on: function(type, fn, context) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = YArray(arguments, 0, true); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = YArray(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = YArray(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? YArray(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = YArray(arguments, 0, true); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = YArray(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {string} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {string} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {string} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; type = (pre) ? _getType(type, pre) : type; this._monitor('publish', type, { args: arguments }); if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } events = edata.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.merge(defaults, opts) : defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @private */ _monitor: function(what, type, o) { var monitorevt, ce = this.getEvent(type); if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, ret, pre = this._yuievt.config.prefix, ce2, args = (typeIncluded) ? YArray(arguments, 1, true) : arguments; t = (pre) ? _getType(t, pre) : t; this._monitor('fire', t, { args: args }); ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (this._yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {string} the type, or name of the event * @param prefixed {string} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * @method after * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ after: function(type, fn) { var a = YArray(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype, false, false, { bubbles: false }); ET.call(Y); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** * <code>YUI</code>'s <code>on</code> method is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, DOM events, and * function events. <code>detach</code> is also provided to remove listeners * serviced by this function. * * The signature that <code>on</code> accepts varies depending on the type * of event being consumed. Refer to the specific methods that will * service a specific request for additional information about subscribing * to that type of event. * * <ul> * <li>Custom events. These events are defined by various * modules in the library. This type of event is delegated to * <code>EventTarget</code>'s <code>on</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('drag:drophit', function() { // start work });</code> * </li> * <li>DOM events. These are moments reported by the browser related * to browser functionality and user interaction. * This type of event is delegated to <code>Event</code>'s * <code>attach</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>The specification for the Node(s) to attach the listener * to. This can be a selector, collections, or Node/Element * refereces.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('click', function(e) { // something was clicked }, '#someelement');</code> * </li> * <li>Function events. These events can be used to react before or after a * function is executed. This type of event is delegated to <code>Event.Do</code>'s * <code>before</code> method. * <ul> * <li>The callback to execute</li> * <li>The object that has the function that will be listened for.</li> * <li>The name of the function to listen for.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example <code>Y.on(function(arg1, arg2, etc) { // obj.methodname was executed }, obj 'methodname');</code> * </li> * </ul> * * <code>on</code> corresponds to the moment before any default behavior of * the event. <code>after</code> works the same way, but these listeners * execute after the event's default behavior. <code>before</code> is an * alias for <code>on</code>. * * @method on * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * Listen for an event one time. Equivalent to <code>on</code>, except that * the listener is immediately detached when executed. * @see on * @method once * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * after() is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, * DOM events, and AOP events. This works the same way as * the on() function, only it operates after any default * behavior for the event has executed. @see <code>on</code> for more * information. * @method after * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ }, '@VERSION@' ,{requires:['oop']});
ajax/libs/core-js/0.4.8/library.js
taydakov/cdnjs
/** * Core.js 0.4.8 * https://github.com/zloirock/core-js * License: http://rock.mit-license.org * © 2015 Denis Pushkarev */ !function(global, framework, undefined){ 'use strict'; /****************************************************************************** * Module : common * ******************************************************************************/ // Shortcuts for [[Class]] & property names 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' // Aliases global objects and prototypes , Function = global[FUNCTION] , Object = global[OBJECT] , Array = global[ARRAY] , String = global[STRING] , Number = global[NUMBER] , RegExp = global[REGEXP] , Date = global[DATE] , Map = global[MAP] , Set = global[SET] , WeakMap = global[WEAKMAP] , WeakSet = global[WEAKSET] , Symbol = global[SYMBOL] , Math = global[MATH] , TypeError = global.TypeError , setTimeout = global.setTimeout , 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 = '.'; // http://jsperf.com/core-js-isobject function isObject(it){ return it != null && (typeof it == 'object' || typeof it == 'function'); } function isFunction(it){ return typeof it == 'function'; } // Native function? var isNative = ctx(/./.test, /\[native code\]\s*\}\s*$/, 1); // Object internal [[Class]] or toStringTag // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring var 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; } // Function var call = FunctionProto.call , apply = FunctionProto.apply , REFERENCE_GET; // Partial apply function part(/* ...args */){ 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(/* ...args */){ 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); } } // Optional / simple context binding function ctx(fn, that, length){ assertFunction(fn); if(~length && that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); } case 2: return function(a, b){ return fn.call(that, a, b); } case 3: return function(a, b, c){ return fn.call(that, a, b, c); } } return function(/* ...args */){ return fn.apply(that, arguments); } } // Fast apply // http://jsperf.lnkit.com/fast-apply/5 function invoke(fn, args, that){ var un = that === undefined; switch(args.length | 0){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); case 5: return un ? fn(args[0], args[1], args[2], args[3], args[4]) : fn.call(that, args[0], args[1], args[2], args[3], args[4]); } return fn.apply(that, args); } function construct(target, argumentsList /*, newTarget*/){ 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; } // Object: 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) // Dummy, fix for not array-like ES3 string in es5 module , 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); } // 19.1.2.1 Object.assign(target, source, ...) 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; } // Array // array('str1,str2,str3') => ['str1', 'str2', 'str3'] function array(it){ return String(it).split(','); } var push = ArrayProto.push , unshift = ArrayProto.unshift , slice = ArrayProto.slice , splice = ArrayProto.splice , indexOf = ArrayProto.indexOf , forEach = ArrayProto[FOR_EACH]; /* * 0 -> forEach * 1 -> map * 2 -> filter * 3 -> some * 4 -> every * 5 -> find * 6 -> findIndex */ function createArrayMethod(type){ var isMap = type == 1 , isFilter = type == 2 , isSome = type == 3 , isEvery = type == 4 , isFindIndex = type == 6 , noholes = type == 5 || isFindIndex; return function(callbackfn/*, that = undefined */){ var 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; // map else if(res)switch(type){ case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if(isEvery)return false; // every } } return isFindIndex ? -1 : isSome || isEvery ? isEvery : result; } } function createArrayContains(isContains){ return function(el /*, fromIndex = 0 */){ var O = 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){ // strange IE quirks mode bug -> use typeof vs isFunction return typeof A == 'function' ? A : B; } // Math var MAX_SAFE_INTEGER = 0x1fffffffffffff // pow(2, 53) - 1 == 9007199254740991 , ceil = Math.ceil , floor = Math.floor , max = Math.max , min = Math.min , random = Math.random , trunc = Math.trunc || function(it){ return (it > 0 ? floor : ceil)(it); } // 20.1.2.4 Number.isNaN(number) function sameNaN(number){ return number != number; } // 7.1.4 ToInteger function toInteger(it){ return isNaN(it) ? 0 : trunc(it); } // 7.1.15 ToLength function toLength(it){ return it > 0 ? min(toInteger(it), MAX_SAFE_INTEGER) : 0; } function 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 < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? toString ? s.charAt(i) : a : toString ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; } } // Assertion & errors var REDUCE_ERROR = 'Reduce of empty object with no initial value'; function assert(condition, msg1, msg2){ if(!condition)throw TypeError(msg2 ? msg1 + msg2 : msg1); } function 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!"); } // Property descriptors & Symbol function descriptor(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value } } function simpleSet(object, key, value){ object[key] = value; return object; } function createDefiner(bitmap){ return DESC ? function(object, key, value){ return defineProperty(object, key, descriptor(bitmap, value)); } : simpleSet; } function uid(key){ return SYMBOL + '(' + key + ')_' + (++sid + random())[TO_STRING](36); } function getWellKnownSymbol(name, setter){ return (Symbol && Symbol[name]) || (setter ? Symbol : safeSymbol)(SYMBOL + DOT + name); } // The engine works fine with descriptors? Thank's IE8 for his funny defineProperty. 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 }); } // Iterators 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 // Safari define byggy iterators w/o `next` , BUGGY_ITERATORS = 'keys' in ArrayProto && !('next' in [].keys()); // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() setIterator(IteratorPrototype, returnThis); function setIterator(O, value){ hidden(O, SYMBOL_ITERATOR, value); // Add iterator for FF iterator protocol SUPPORT_FF_ITER && hidden(O, FF_ITERATOR, value); } function createIterator(Constructor, NAME, next, proto){ Constructor[PROTOTYPE] = create(proto || IteratorPrototype, {next: descriptor(1, next)}); 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){ // Define iterator setIterator(proto, iter); if(iter !== value){ var iterProto = getPrototypeOf(iter.call(new Constructor)); // Set @@toStringTag to native iterators setToStringTag(iterProto, NAME + ' Iterator', true); // FF fix has(proto, FF_ITERATOR) && setIterator(iterProto, returnThis); } } // Plug for library Iterators[NAME] = iter; // FF & v8 fix 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; } // core var NODE = cof(process) == PROCESS , core = {} , path = framework ? global : core , old = global.core , exportGlobal // type bitmap , FORCED = 1 , GLOBAL = 2 , STATIC = 4 , PROTO = 8 , BIND = 16 , WRAP = 32; function $define(type, name, source){ var key, own, out, exp , isGlobal = type & GLOBAL , target = isGlobal ? global : (type & STATIC) ? global[name] : (global[name] || ObjectProto)[PROTOTYPE] , exports = isGlobal ? core : core[name] || (core[name] = {}); if(isGlobal)source = name; for(key in source){ // there is a similar native own = !(type & FORCED) && target && key in target && (!isFunction(target[key]) || isNative(target[key])); // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context if(type & BIND && own)exp = ctx(out, global); // wrap global constructors for prevent change them in library else if(type & WRAP && !framework && target[key] == out){ exp = function(param){ return this instanceof out ? new out(param) : out(param); } exp[PROTOTYPE] = out[PROTOTYPE]; } else exp = type & PROTO && isFunction(out) ? ctx(call, out) : out; // export if(exports[key] != out)hidden(exports, key, exp); // extend global if(framework && target && !own){ if(isGlobal)target[key] = out; else delete target[key] && hidden(target, key, out); } } } // CommonJS export if(typeof module != 'undefined' && module.exports)module.exports = core; // RequireJS export else if(isFunction(define) && define.amd)define(function(){return core}); // Export to global object else exportGlobal = true; if(exportGlobal || framework){ core.noConflict = function(){ global.core = old; return core; } global.core = core; } /****************************************************************************** * Module : es5 * ******************************************************************************/ // ECMAScript 5 shim !function(IS_ENUMERABLE, Empty, _classof, $PROTO){ if(!DESC){ getOwnDescriptor = function(O, P){ if(has(O, P))return descriptor(!ObjectProto[IS_ENUMERABLE].call(O, P), O[P]); }; defineProperty = function(O, P, Attributes){ if('value' in Attributes)assertObject(O)[P] = Attributes.value; return O; }; defineProperties = function(O, Properties){ assertObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P, Attributes; while(length > i){ P = keys[i++]; Attributes = Properties[P]; if('value' in Attributes)O[P] = Attributes.value; } return O; }; } $define(STATIC + FORCED * !DESC, OBJECT, { // 19.1.2.6 / 15.2.3.3 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: getOwnDescriptor, // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) defineProperty: defineProperty, // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) defineProperties: defineProperties }); // IE 8- don't enum bug keys var keys1 = [CONSTRUCTOR, HAS_OWN, 'isPrototypeOf', IS_ENUMERABLE, TO_LOCALE, TO_STRING, 'valueOf'] // Additional keys for getOwnPropertyNames , keys2 = keys1.concat('length', PROTOTYPE) , keysLen1 = keys1.length; // Create object with `null` prototype: use iframe Object with cleared prototype function createDict(){ // Thrash, waste and sodomy: IE GC bug var iframe = document[CREATE_ELEMENT]('iframe') , i = keysLen1 , iframeDocument; iframe.style.display = 'none'; html.appendChild(iframe); iframe.src = 'javascript:'; // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write('<script>document.F=Object</script>'); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][keys1[i]]; return createDict(); } function createGetKeys(names, length, isNames){ return function(object){ var O = toObject(object) , i = 0 , result = [] , key; for(key in O)if(key != $PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(length > i)if(has(O, key = names[i++])){ ~indexOf.call(result, key) || result.push(key); } return result; } } function isPrimitive(it){ return !isObject(it) } $define(STATIC, OBJECT, { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) getPrototypeOf: getPrototypeOf = getPrototypeOf || function(O){ O = Object(assertDefined(O)); if(has(O, $PROTO))return O[$PROTO]; if(isFunction(O[CONSTRUCTOR]) && O instanceof O[CONSTRUCTOR]){ return O[CONSTRUCTOR][PROTOTYPE]; } return O instanceof Object ? ObjectProto : null; }, // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) getOwnPropertyNames: getNames = getNames || createGetKeys(keys2, keys2.length, true), // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) create: create = create || function(O, /*?*/Properties){ var result if(O !== null){ Empty[PROTOTYPE] = assertObject(O); result = new Empty(); Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf shim if(result[CONSTRUCTOR][PROTOTYPE] !== O)result[$PROTO] = O; } else result = createDict(); return Properties === undefined ? result : defineProperties(result, Properties); }, // 19.1.2.14 / 15.2.3.14 Object.keys(O) keys: getKeys = getKeys || createGetKeys(keys1, keysLen1, false), // 19.1.2.17 / 15.2.3.8 Object.seal(O) seal: returnIt, // <- cap // 19.1.2.5 / 15.2.3.9 Object.freeze(O) freeze: returnIt, // <- cap // 19.1.2.15 / 15.2.3.10 Object.preventExtensions(O) preventExtensions: returnIt, // <- cap // 19.1.2.13 / 15.2.3.11 Object.isSealed(O) isSealed: isPrimitive, // <- cap // 19.1.2.12 / 15.2.3.12 Object.isFrozen(O) isFrozen: isFrozen = isFrozen || isPrimitive, // <- cap // 19.1.2.11 / 15.2.3.13 Object.isExtensible(O) isExtensible: isObject // <- cap }); // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) $define(PROTO, FUNCTION, { bind: function(that /*, args... */){ var fn = assertFunction(this) , partArgs = slice.call(arguments, 1); function bound(/* args... */){ var args = partArgs.concat(slice.call(arguments)); return this instanceof bound ? construct(fn, args) : invoke(fn, args, that); } return bound; } }); // Fix for not array-like ES3 string function arrayMethodFix(fn){ return function(){ return fn.apply(ES5Object(this), arguments); } } if(!(0 in Object(DOT) && DOT[0] == DOT)){ ES5Object = function(it){ return cof(it) == STRING ? it.split('') : Object(it); } slice = arrayMethodFix(slice); } $define(PROTO + FORCED * (ES5Object != Object), ARRAY, { slice: slice, join: arrayMethodFix(ArrayProto.join) }); // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) $define(STATIC, ARRAY, { isArray: function(arg){ return cof(arg) == ARRAY } }); function createArrayReduce(isRight){ return function(callbackfn, memo){ assertFunction(callbackfn); var O = toObject(this) , length = toLength(O.length) , index = isRight ? length - 1 : 0 , i = isRight ? -1 : 1; if(2 > arguments.length)for(;;){ if(index in O){ memo = O[index]; index += i; break; } index += i; assert(isRight ? index >= 0 : length > index, REDUCE_ERROR); } for(;isRight ? index >= 0 : length > index; index += i)if(index in O){ memo = callbackfn(memo, O[index], index, this); } return memo; } } $define(PROTO, ARRAY, { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: forEach = forEach || createArrayMethod(0), // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: createArrayMethod(1), // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: createArrayMethod(2), // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: createArrayMethod(3), // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) every: createArrayMethod(4), // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) reduce: createArrayReduce(false), // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) reduceRight: createArrayReduce(true), // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) indexOf: indexOf = indexOf || createArrayContains(false), // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) lastIndexOf: function(el, fromIndex /* = @[*-1] */){ var O = toObject(this) , length = toLength(O.length) , index = length - 1; if(arguments.length > 1)index = min(index, toInteger(fromIndex)); if(index < 0)index = toLength(length + index); for(;index >= 0; index--)if(index in O)if(O[index] === el)return index; return -1; } }); // 21.1.3.25 / 15.5.4.20 String.prototype.trim() $define(PROTO, STRING, {trim: createReplacer(/^\s*([\s\S]*\S)?\s*$/, '$1')}); // 20.3.3.1 / 15.9.4.4 Date.now() $define(STATIC, DATE, {now: function(){ return +new Date; }}); if(_classof(function(){return arguments}()) == OBJECT)classof = function(it){ var cof = _classof(it); return cof == OBJECT && isFunction(it.callee) ? ARGUMENTS : cof; } }('propertyIsEnumerable', function(){}, classof, safeSymbol(PROTOTYPE)); /****************************************************************************** * Module : global * ******************************************************************************/ $define(GLOBAL + FORCED, {global: global}); /****************************************************************************** * Module : es6_symbol * ******************************************************************************/ // ECMAScript 6 symbols shim !function(TAG, SymbolRegistry, AllSymbols, setter){ // 19.4.1.1 Symbol([description]) if(!isNative(Symbol)){ Symbol = function(description){ assert(!(this instanceof Symbol), SYMBOL + ' is not a ' + CONSTRUCTOR); var tag = uid(description); 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 = { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = Symbol(key); }, // 19.4.2.4 Symbol.iterator iterator: SYMBOL_ITERATOR, // 19.4.2.5 Symbol.keyFor(sym) keyFor: part.call(keyOf, SymbolRegistry), // 19.4.2.10 Symbol.species species: SYMBOL_SPECIES, // 19.4.2.13 Symbol.toStringTag toStringTag: SYMBOL_TAG = getWellKnownSymbol(TO_STRING_TAG, true), // 19.4.2.14 Symbol.unscopables unscopables: SYMBOL_UNSCOPABLES, pure: safeSymbol, set: set, useSetter: function(){setter = true}, useSimple: function(){setter = false} }; // 19.4.2.2 Symbol.hasInstance // 19.4.2.3 Symbol.isConcatSpreadable // 19.4.2.6 Symbol.match // 19.4.2.8 Symbol.replace // 19.4.2.9 Symbol.search // 19.4.2.11 Symbol.split // 19.4.2.12 Symbol.toPrimitive 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, { // 19.1.2.7 Object.getOwnPropertyNames(O) 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; }, // 19.1.2.8 Object.getOwnPropertySymbols(O) 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); /****************************************************************************** * Module : es6 * ******************************************************************************/ // ECMAScript 6 shim !function(RegExpProto, isFinite, tmp, NAME){ var RangeError = global.RangeError // 20.1.2.3 Number.isInteger(number) , isInteger = Number.isInteger || function(it){ return !isObject(it) && isFinite(it) && floor(it) === it; } // 20.2.2.28 Math.sign(x) , 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 = { // 19.1.3.1 Object.assign(target, source) assign: assign, // 19.1.3.10 Object.is(value1, value2) is: function(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; } }; // 19.1.3.19 Object.setPrototypeOf(O, proto) // Works with __proto__ only. Old v8 can't works with null proto objects. '__proto__' in ObjectProto && function(buggy, set){ try { set = ctx(call, getOwnDescriptor(ObjectProto, '__proto__').set, 2); set({}, ArrayProto); } catch(e){ buggy = true } 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); // 20.2.2.5 Math.asinh(x) function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log(x + sqrt(x * x + 1)); } // 20.2.2.14 Math.expm1(x) function expm1(x){ return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : exp(x) - 1; } $define(STATIC, NUMBER, { // 20.1.2.1 Number.EPSILON EPSILON: pow(2, -52), // 20.1.2.2 Number.isFinite(number) isFinite: function(it){ return typeof it == 'number' && isFinite(it); }, // 20.1.2.3 Number.isInteger(number) isInteger: isInteger, // 20.1.2.4 Number.isNaN(number) isNaN: sameNaN, // 20.1.2.5 Number.isSafeInteger(number) isSafeInteger: function(number){ return isInteger(number) && abs(number) <= MAX_SAFE_INTEGER; }, // 20.1.2.6 Number.MAX_SAFE_INTEGER MAX_SAFE_INTEGER: MAX_SAFE_INTEGER, // 20.1.2.10 Number.MIN_SAFE_INTEGER MIN_SAFE_INTEGER: -MAX_SAFE_INTEGER, // 20.1.2.12 Number.parseFloat(string) parseFloat: parseFloat, // 20.1.2.13 Number.parseInt(string, radix) parseInt: parseInt }); $define(STATIC, MATH, { // 20.2.2.3 Math.acosh(x) acosh: function(x){ return (x = +x) < 1 ? NaN : isFinite(x) ? log(x / E + sqrt(x + 1) * sqrt(x - 1) / E) + 1 : x; }, // 20.2.2.5 Math.asinh(x) asinh: asinh, // 20.2.2.7 Math.atanh(x) atanh: function(x){ return (x = +x) == 0 ? x : log((1 + x) / (1 - x)) / 2; }, // 20.2.2.9 Math.cbrt(x) cbrt: function(x){ return sign(x = +x) * pow(abs(x), 1 / 3); }, // 20.2.2.11 Math.clz32(x) clz32: function(x){ return (x >>>= 0) ? 32 - x[TO_STRING](2).length : 32; }, // 20.2.2.12 Math.cosh(x) cosh: function(x){ return (exp(x = +x) + exp(-x)) / 2; }, // 20.2.2.14 Math.expm1(x) expm1: expm1, // 20.2.2.16 Math.fround(x) // TODO: fallback for IE9- fround: function(x){ return new Float32Array([x])[0]; }, // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) 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); }, // 20.2.2.18 Math.imul(x, y) imul: function(x, y){ var UInt16 = 0xffff , xn = +x , yn = +y , xl = UInt16 & xn , yl = UInt16 & yn; return 0 | xl * yl + ((UInt16 & xn >>> 16) * yl + xl * (UInt16 & yn >>> 16) << 16 >>> 0); }, // 20.2.2.20 Math.log1p(x) log1p: function(x){ return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : log(1 + x); }, // 20.2.2.21 Math.log10(x) log10: function(x){ return log(x) / Math.LN10; }, // 20.2.2.22 Math.log2(x) log2: function(x){ return log(x) / Math.LN2; }, // 20.2.2.28 Math.sign(x) sign: sign, // 20.2.2.30 Math.sinh(x) sinh: function(x){ return (abs(x = +x) < 1) ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (E / 2); }, // 20.2.2.33 Math.tanh(x) tanh: function(x){ var a = expm1(x = +x) , b = expm1(-x); return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); }, // 20.2.2.34 Math.trunc(x) trunc: trunc }); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, MATH, true); function assertNotRegExp(it){ if(cof(it) == REGEXP)throw TypeError(); } $define(STATIC, STRING, { // 21.1.2.2 String.fromCodePoint(...codePoints) fromCodePoint: function(x){ var res = [] , len = arguments.length , i = 0 , code while(len > i){ code = +arguments[i++]; if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point'); res.push(code < 0x10000 ? fcc(code) : fcc(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) ); } return res.join(''); }, // 21.1.2.4 String.raw(callSite, ...substitutions) 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, { // 21.1.3.3 String.prototype.codePointAt(pos) codePointAt: createPointAt(false), // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) endsWith: function(searchString /*, endPosition = @length */){ 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; }, // 21.1.3.7 String.prototype.includes(searchString, position = 0) includes: function(searchString /*, position = 0 */){ assertNotRegExp(searchString); return !!~String(assertDefined(this)).indexOf(searchString, arguments[1]); }, // 21.1.3.13 String.prototype.repeat(count) 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; }, // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) startsWith: function(searchString /*, position = 0 */){ assertNotRegExp(searchString); var that = String(assertDefined(this)) , index = toLength(min(arguments[1], that.length)); searchString += ''; return that.slice(index, index + searchString.length) === searchString; } }); // 21.1.3.27 String.prototype[@@iterator]() defineStdIterators(String, STRING, function(iterated){ set(this, ITER, {o: String(iterated), i: 0}); // 21.1.5.2.1 %StringIteratorPrototype%.next() }, 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, { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ 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; }, // 22.1.2.3 Array.of( ...items) of: function(/* ...args */){ var index = 0 , length = arguments.length , result = new (generic(this, Array))(length); while(length > index)result[index] = arguments[index++]; result.length = length; return result; } }); $define(PROTO, ARRAY, { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) copyWithin: function(target /* = 0 */, start /* = 0, end = @length */){ 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; }, // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) fill: function(value /*, start = 0, end = @length */){ 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; }, // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) find: createArrayMethod(5), // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) findIndex: createArrayMethod(6) }); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() defineStdIterators(Array, ARRAY, function(iterated, kind){ set(this, ITER, {o: toObject(iterated), i: 0, k: kind}); // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, 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); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators[ARGUMENTS] = Iterators[ARRAY]; // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); // Object static methods accept primitives 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){ // 19.1.3.6 Object.prototype.toString() tmp[SYMBOL_TAG] = DOT; if(cof(tmp) != DOT)hidden(ObjectProto, TO_STRING, function(){ return '[object ' + classof(this) + ']'; }); // 19.2.4.2 name 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)); } }); // RegExp allows a regex with flags as the pattern 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); } // 21.2.5.3 get RegExp.prototype.flags() if(/./g.flags != 'g')defineProperty(RegExpProto, 'flags', { configurable: true, get: createReplacer(/^.*\/(\w*)$/, '$1') }); // 22.1.3.31 Array.prototype[@@unscopables] 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'); /****************************************************************************** * Module : immediate * ******************************************************************************/ // setImmediate shim // Node.js 0.9+ & IE10+ has setImmediate, else: isFunction(setImmediate) && isFunction(clearImmediate) || function(ONREADYSTATECHANGE){ var postMessage = global.postMessage , addEventListener = global.addEventListener , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , defer, channel, port; setImmediate = function(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(isFunction(fn) ? fn : Function(fn), args); } defer(counter); return counter; } clearImmediate = function(id){ delete queue[id]; } function run(id){ if(has(queue, id)){ var fn = queue[id]; delete queue[id]; fn(); } } function listner(event){ run(event.data); } // Node.js 0.8- if(NODE){ defer = function(id){ nextTick(part.call(run, id)); } // Modern browsers, skip implementation for WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is object } else if(addEventListener && isFunction(postMessage) && !global.importScripts){ defer = function(id){ postMessage(id, '*'); } addEventListener('message', listner, false); // WebWorkers } else if(isFunction(MessageChannel)){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listner; defer = ctx(port.postMessage, port, 1); // IE8- } else if(document && ONREADYSTATECHANGE in document[CREATE_ELEMENT]('script')){ defer = function(id){ html.appendChild(document[CREATE_ELEMENT]('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run(id); } } // Rest old browsers } else { defer = function(id){ setTimeout(part.call(run, id), 0); } } }('onreadystatechange'); $define(GLOBAL + BIND, { setImmediate: setImmediate, clearImmediate: clearImmediate }); /****************************************************************************** * Module : es6_promise * ******************************************************************************/ // ES6 promises shim // Based on https://github.com/getify/native-promise-only/ !function(Promise, test){ isFunction(Promise) && isFunction(Promise.resolve) && Promise.resolve(test = new Promise(function(){})) == test || function(asap, DEF){ function isThenable(o){ var then; if(isObject(o))then = o.then; return isFunction(then) ? then : false; } function notify(def){ var chain = def.chain; chain.length && asap(function(){ var msg = def.msg , ok = def.state == 1 , i = 0; while(chain.length > i)!function(react){ var cb = ok ? react.ok : react.fail , ret, then; try { if(cb){ ret = cb === true ? msg : cb(msg); if(ret === react.P){ react.rej(TypeError(PROMISE + '-chain cycle')); } else if(then = isThenable(ret)){ then.call(ret, react.res, react.rej); } else react.res(ret); } else react.rej(msg); } catch(err){ react.rej(err); } }(chain[i++]); chain.length = 0; }); } function resolve(msg){ var def = this , then, wrapper; if(def.done)return; def.done = true; def = def.def || def; // unwrap try { if(then = isThenable(msg)){ wrapper = {def: def, done: false}; // wrap then.call(msg, ctx(resolve, wrapper, 1), ctx(reject, wrapper, 1)); } else { def.msg = msg; def.state = 1; notify(def); } } catch(err){ reject.call(wrapper || {def: def, done: false}, err); // wrap } } function reject(msg){ var def = this; if(def.done)return; def.done = true; def = def.def || def; // unwrap def.msg = msg; def.state = 2; notify(def); } function getConstructor(C){ var S = assertObject(C)[SYMBOL_SPECIES]; return S != undefined ? S : C; } // 25.4.3.1 Promise(executor) Promise = function(executor){ assertFunction(executor); assertInstance(this, Promise, PROMISE); var def = {chain: [], state: 0, done: false, msg: undefined}; hidden(this, DEF, def); try { executor(ctx(resolve, def, 1), ctx(reject, def, 1)); } catch(err){ reject.call(def, err); } } assignHidden(Promise[PROTOTYPE], { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) 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; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); assignHidden(Promise, { // 25.4.4.1 Promise.all(iterable) 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); }); }, // 25.4.4.4 Promise.race(iterable) race: function(iterable){ var Promise = getConstructor(this); return new Promise(function(resolve, reject){ forOf(iterable, false, function(promise){ Promise.resolve(promise).then(resolve, reject); }); }); }, // 25.4.4.5 Promise.reject(r) reject: function(r){ return new (getConstructor(this))(function(resolve, reject){ reject(r); }); }, // 25.4.4.6 Promise.resolve(x) 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]); /****************************************************************************** * Module : es6_collections * ******************************************************************************/ // ECMAScript 6 collections shim !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]; framework && hidden(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, 'entries')))){ // create collection constructor 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; // wrap to init collections from iterable if(!NATIVE_ITERATORS || !C.length){ C = function(iterable){ assertInstance(this, C, NAME); return initFromIterable(new Native, iterable); } C[PROTOTYPE] = proto; } isWeak || inst[FOR_EACH](function(val, key){ buggyZero = 1 / key === -Infinity; }); // fix converting -0 key to +0 if(buggyZero){ fixSVZ('delete'); fixSVZ('has'); isMap && fixSVZ('get'); } // + fix .add & .set for chaining if(buggyZero || chain !== inst)fixSVZ(ADDER, true); } setToStringTag(C, NAME); setSpecies(C); O[NAME] = C; $define(GLOBAL + WRAP + FORCED * !isNative(C), O); // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 isWeak || defineStdIterators(C, NAME, function(iterated, kind){ set(this, ITER, {o: iterated, k: kind}); }, function(){ var iter = this[ITER] , O = iter.o , kind = iter.k , entry = iter.l; while(entry && entry.r)entry = entry.p; if(!O || !(iter.l = entry = entry ? entry.n : 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){ // return it with 'S' prefix if it's string or with 'P' prefix for over primitives if(!isObject(it))return (typeof it == 'string' ? 'S' : 'P') + it; if(isFrozen(it))return 'F'; // if it hasn't object id - add next if(!has(it, UID)){ if(create)hidden(it, UID, ++uid); else return 'E'; } // return object id with 'O' prefix 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) , previous, index; if(entry)entry.v = value; else { that[LAST] = entry = { i: index = fastKey(key, true), // <- index k: key, // <- key v: value, // <- value p: previous = that[LAST], // <- previous entry n: undefined, // <- next entry r: false // <- removed }; if(!that[FIRST])that[FIRST] = entry; if(previous)previous.n = entry; that[SIZE]++; if(index != 'F')that[O1][index] = entry; } return that; } var collectionMethods = { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() 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; }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function(key){ var that = this , entry = getEntry(that, key); if(entry){ var next = entry.n , prev = entry.p; delete that[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; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function(callbackfn /*, that = undefined */){ var f = ctx(callbackfn, arguments[1], 3) , entry; while(entry = entry ? entry.n : this[FIRST]){ f(entry.v, entry.k, this); while(entry && entry.r)entry = entry.p; } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function(key){ return !!getEntry(this, key); } } // 23.1 Map Objects Map = getCollection(Map, MAP, { // 23.1.3.6 Map.prototype.get(key) get: function(key){ var entry = getEntry(this, key); return entry && entry.v; }, // 23.1.3.9 Map.prototype.set(key, value) set: function(key, value){ return def(this, key === 0 ? 0 : key, value); } }, collectionMethods, true); // 23.2 Set Objects Set = getCollection(Set, SET, { // 23.2.3.1 Set.prototype.add(value) 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 = { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) '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]]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) 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]); } }; // 23.3 WeakMap Objects WeakMap = getCollection(WeakMap, WEAKMAP, { // 23.3.3.3 WeakMap.prototype.get(key) get: function(key){ if(isObject(key)){ if(isFrozen(key))return leakStore(this).get(key); if(has(key, WEAK))return key[WEAK][this[UID]]; } }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function(key, value){ return defWeak(this, key, value); } }, weakMethods, true, true); // IE11 WeakMap frozen keys fix 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]; hidden(WeakMap[PROTOTYPE], key, function(a, b){ if(isObject(a) && isFrozen(a))return leakStore(this)[key](a, b); return method.call(this, a, b); }); }); } // 23.4 WeakSet Objects WeakSet = getCollection(WeakSet, WEAKSET, { // 23.4.3.1 WeakSet.prototype.add(value) add: function(value){ return defWeak(this, value, true); } }, weakMethods, false, true); }(); /****************************************************************************** * Module : es6_reflect * ******************************************************************************/ !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/*, receiver*/){ 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/*, receiver*/){ 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 = { // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) apply: ctx(call, apply, 3), // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) construct: construct, // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) defineProperty: wrap(defineProperty), // 26.1.4 Reflect.deleteProperty(target, propertyKey) deleteProperty: function(target, propertyKey){ var desc = getOwnDescriptor(assertObject(target), propertyKey); return desc && !desc.configurable ? false : delete target[propertyKey]; }, // 26.1.5 Reflect.enumerate(target) enumerate: function(target){ return new Enumerate(assertObject(target)); }, // 26.1.6 Reflect.get(target, propertyKey [, receiver]) get: reflectGet, // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) getOwnPropertyDescriptor: function(target, propertyKey){ return getOwnDescriptor(assertObject(target), propertyKey); }, // 26.1.8 Reflect.getPrototypeOf(target) getPrototypeOf: function(target){ return getPrototypeOf(assertObject(target)); }, // 26.1.9 Reflect.has(target, propertyKey) has: function(target, propertyKey){ return propertyKey in target; }, // 26.1.10 Reflect.isExtensible(target) isExtensible: function(target){ return !!isExtensible(assertObject(target)); }, // 26.1.11 Reflect.ownKeys(target) ownKeys: ownKeys, // 26.1.12 Reflect.preventExtensions(target) preventExtensions: wrap(Object.preventExtensions || returnIt), // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) set: reflectSet } // 26.1.14 Reflect.setPrototypeOf(target, proto) if(setPrototypeOf)reflect.setPrototypeOf = function(target, proto){ return setPrototypeOf(assertObject(target), proto), true; }; $define(GLOBAL, {Reflect: {}}); $define(STATIC, 'Reflect', reflect); }(); /****************************************************************************** * Module : es7 * ******************************************************************************/ !function(){ $define(PROTO, ARRAY, { // https://github.com/domenic/Array.prototype.includes includes: createArrayContains(true) }); $define(PROTO, STRING, { // https://github.com/mathiasbynens/String.prototype.at 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, { // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-04/apr-9.md#51-objectentries-objectvalues values: createObjectToArray(false), entries: createObjectToArray(true) }); $define(STATIC, REGEXP, { // https://gist.github.com/kangax/9698100 escape: createReplacer(/([\\\-[\]{}()*+?.,^$|])/g, '\\$1', true) }); }(); /****************************************************************************** * Module : es7_refs * ******************************************************************************/ // https://github.com/zenparsing/es-abstract-refs !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'); /****************************************************************************** * Module : dom_itarable * ******************************************************************************/ !function(NodeList){ if(framework && NodeList && !(SYMBOL_ITERATOR in NodeList[PROTOTYPE])){ hidden(NodeList[PROTOTYPE], SYMBOL_ITERATOR, Iterators[ARRAY]); } Iterators.NodeList = Iterators[ARRAY]; }(global.NodeList); /****************************************************************************** * Module : dict * ******************************************************************************/ !function(DICT){ Dict = function(iterable){ var dict = create(null); if(iterable != undefined){ if(isIterable(iterable)){ for(var iter = getIterator(iterable), step, value; !(step = iter.next()).done;){ value = step.value; dict[value[0]] = value[1]; } } else assign(dict, iterable); } return dict; } Dict[PROTOTYPE] = null; function DictIterator(iterated, kind){ set(this, ITER, {o: toObject(iterated), a: getKeys(iterated), i: 0, k: kind}); } createIterator(DictIterator, DICT, function(){ var iter = this[ITER] , O = iter.o , keys = iter.a , kind = iter.k , key; do { if(iter.i >= keys.length)return iterResult(1); } while(!has(O, key = keys[iter.i++])); if(kind == KEY) return iterResult(0, key); if(kind == VALUE)return iterResult(0, O[key]); return iterResult(0, [key, O[key]]); }); function createDictIter(kind){ return function(it){ return new DictIterator(it, kind); } } /* * 0 -> forEach * 1 -> map * 2 -> filter * 3 -> some * 4 -> every * 5 -> find * 6 -> findKey * 7 -> mapPairs */ function createDictMethod(type){ var isMap = type == 1 , isEvery = type == 4; return function(object, callbackfn, that /* = undefined */){ var f = ctx(callbackfn, that, 3) , O = toObject(object) , result = isMap || type == 7 || type == 2 ? new (generic(this, Dict)) : undefined , key, val, res; for(key in O)if(has(O, key)){ val = O[key]; res = f(val, key, object); if(type){ if(isMap)result[key] = res; // map else if(res)switch(type){ case 2: result[key] = val; break // filter case 3: return true; // some case 5: return val; // find case 6: return key; // findKey case 7: result[res[0]] = res[1]; // mapPairs } else if(isEvery)return false; // every } } return type == 3 || isEvery ? isEvery : result; } } function createDictReduce(isTurn){ return function(object, mapfn, init){ assertFunction(mapfn); var O = toObject(object) , keys = getKeys(O) , length = keys.length , i = 0 , memo, key, result; if(isTurn)memo = init == undefined ? new (generic(this, Dict)) : Object(init); else if(arguments.length < 3){ assert(length, REDUCE_ERROR); memo = O[keys[i++]]; } else memo = Object(init); while(length > i)if(has(O, key = keys[i++])){ result = mapfn(memo, O[key], key, object); if(isTurn){ if(result === false)break; } else memo = result; } return memo; } } var findKey = createDictMethod(6); function includes(object, el){ return (el == el ? keyOf(object, el) : findKey(object, sameNaN)) !== undefined; } var dictMethods = { keys: createDictIter(KEY), values: createDictIter(VALUE), entries: createDictIter(KEY+VALUE), forEach: createDictMethod(0), map: createDictMethod(1), filter: createDictMethod(2), some: createDictMethod(3), every: createDictMethod(4), find: createDictMethod(5), findKey: findKey, mapPairs:createDictMethod(7), reduce: createDictReduce(false), turn: createDictReduce(true), keyOf: keyOf, includes:includes, // Has / get / set own property has: has, get: get, set: createDefiner(0), isDict: function(it){ return isObject(it) && getPrototypeOf(it) === Dict[PROTOTYPE]; } }; if(REFERENCE_GET)for(var key in dictMethods)!function(fn){ function method(){ for(var args = [this], i = 0; i < arguments.length;)args.push(arguments[i++]); return invoke(fn, args); } fn[REFERENCE_GET] = function(){ return method; } }(dictMethods[key]); $define(GLOBAL + FORCED, {Dict: assignHidden(Dict, dictMethods)}); }('Dict'); /****************************************************************************** * Module : $for * ******************************************************************************/ !function(ENTRIES, FN){ function $for(iterable, entries){ if(!(this instanceof $for))return new $for(iterable, entries); this[ITER] = getIterator(iterable); this[ENTRIES] = !!entries; } createIterator($for, 'Wrapper', function(){ return this[ITER].next(); }); var $forProto = $for[PROTOTYPE]; setIterator($forProto, function(){ return this[ITER]; // unwrap }); function createChainIterator(next){ function Iter(I, fn, that){ this[ITER] = getIterator(I); this[ENTRIES] = I[ENTRIES]; this[FN] = ctx(fn, that, I[ENTRIES] ? 2 : 1); } createIterator(Iter, 'Chain', next, $forProto); setIterator(Iter[PROTOTYPE], returnThis); // override $forProto iterator return Iter; } var MapIter = createChainIterator(function(){ var step = this[ITER].next(); return step.done ? step : iterResult(0, stepCall(this[FN], step.value, this[ENTRIES])); }); var FilterIter = createChainIterator(function(){ for(;;){ var step = this[ITER].next(); if(step.done || stepCall(this[FN], step.value, this[ENTRIES]))return step; } }); assignHidden($forProto, { of: function(fn, that){ forOf(this, this[ENTRIES], fn, that); }, array: function(fn, that){ var result = []; forOf(fn != undefined ? this.map(fn, that) : this, false, push, result); return result; }, filter: function(fn, that){ return new FilterIter(this, fn, that); }, map: function(fn, that){ return new MapIter(this, fn, that); } }); $for.isIterable = isIterable; $for.getIterator = getIterator; $define(GLOBAL + FORCED, {$for: $for}); }('entries', safeSymbol('fn')); /****************************************************************************** * Module : timers * ******************************************************************************/ // ie9- setTimeout & setInterval additional parameters fix !function(MSIE){ function wrap(set){ return MSIE ? function(fn, time /*, ...args */){ return set(invoke(part, slice.call(arguments, 2), isFunction(fn) ? fn : Function(fn)), time); } : set; } $define(GLOBAL + BIND + FORCED * MSIE, { setTimeout: setTimeout = wrap(setTimeout), setInterval: wrap(setInterval) }); // ie9- dirty check }(!!navigator && /MSIE .\./.test(navigator.userAgent)); /****************************************************************************** * Module : binding * ******************************************************************************/ !function(_, toLocaleString){ // Placeholder core._ = path._ = path._ || {}; $define(PROTO + FORCED, FUNCTION, { part: part, only: function(numberArguments, that /* = @ */){ var fn = assertFunction(this) , n = toLength(numberArguments) , isThat = arguments.length > 1; return function(/* ...args */){ var length = min(n, arguments.length) , args = Array(length) , i = 0; while(length > i)args[i] = arguments[i++]; return invoke(fn, args, isThat ? that : this); } } }); function tie(key){ var that = this , bound = {}; return hidden(that, _, function(key){ if(key === undefined || !(key in that))return toLocaleString.call(that); return has(bound, key) ? bound[key] : (bound[key] = ctx(that[key], that, -1)); })[_](key); } hidden(path._, TO_STRING, function(){ return _; }); hidden(ObjectProto, _, tie); DESC || hidden(ArrayProto, _, tie); // IE8- dirty hack - redefined toLocaleString is not enumerable }(DESC ? uid('tie') : TO_LOCALE, ObjectProto[TO_LOCALE]); /****************************************************************************** * Module : object * ******************************************************************************/ !function(){ function define(target, mixin){ var keys = ownKeys(toObject(mixin)) , length = keys.length , i = 0, key; while(length > i)defineProperty(target, key = keys[i++], getOwnDescriptor(mixin, key)); return target; }; $define(STATIC + FORCED, OBJECT, { isObject: isObject, classof: classof, define: define, make: function(proto, mixin){ return define(create(proto), mixin); } }); }(); /****************************************************************************** * Module : array * ******************************************************************************/ $define(PROTO + FORCED, ARRAY, { turn: function(fn, target /* = [] */){ assertFunction(fn); var memo = target == undefined ? [] : Object(target) , O = ES5Object(this) , length = toLength(O.length) , index = 0; while(length > index)if(fn(memo, O[index], index++, this) === false)break; return memo; } }); if(framework)ArrayUnscopables.turn = true; /****************************************************************************** * Module : array_statics * ******************************************************************************/ // JavaScript 1.6 / Strawman array statics shim !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); }({}); /****************************************************************************** * Module : number * ******************************************************************************/ !function(numberMethods){ function NumberIterator(iterated){ set(this, ITER, {l: toLength(iterated), i: 0}); } createIterator(NumberIterator, NUMBER, function(){ var iter = this[ITER] , i = iter.i++; return i < iter.l ? iterResult(0, i) : iterResult(1); }); defineIterator(Number, NUMBER, function(){ return new NumberIterator(this); }); numberMethods.random = function(lim /* = 0 */){ var a = +this , b = lim == undefined ? 0 : +lim , m = min(a, b); return random() * (max(a, b) - m) + m; }; forEach.call(array( // ES3: 'round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,' + // ES6: 'acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc' ), function(key){ var fn = Math[key]; if(fn)numberMethods[key] = function(/* ...args */){ // ie9- dont support strict mode & convert `this` to object -> convert it to number var args = [+this] , i = 0; while(arguments.length > i)args.push(arguments[i++]); return invoke(fn, args); } } ); $define(PROTO + FORCED, NUMBER, numberMethods); }({}); /****************************************************************************** * Module : string * ******************************************************************************/ !function(){ var escapeHTMLDict = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' }, unescapeHTMLDict = {}, key; for(key in escapeHTMLDict)unescapeHTMLDict[escapeHTMLDict[key]] = key; $define(PROTO + FORCED, STRING, { escapeHTML: createReplacer(/[&<>"']/g, escapeHTMLDict), unescapeHTML: createReplacer(/&(?:amp|lt|gt|quot|apos);/g, unescapeHTMLDict) }); }(); /****************************************************************************** * Module : date * ******************************************************************************/ !function(formatRegExp, flexioRegExp, locales, current, SECONDS, MINUTES, HOURS, MONTH, YEAR){ function createFormat(prefix){ return function(template, locale /* = current */){ var that = this , dict = locales[has(locales, locale) ? locale : current]; function get(unit){ return that[prefix + unit](); } return String(template).replace(formatRegExp, function(part){ switch(part){ case 's' : return get(SECONDS); // Seconds : 0-59 case 'ss' : return lz(get(SECONDS)); // Seconds : 00-59 case 'm' : return get(MINUTES); // Minutes : 0-59 case 'mm' : return lz(get(MINUTES)); // Minutes : 00-59 case 'h' : return get(HOURS); // Hours : 0-23 case 'hh' : return lz(get(HOURS)); // Hours : 00-23 case 'D' : return get(DATE); // Date : 1-31 case 'DD' : return lz(get(DATE)); // Date : 01-31 case 'W' : return dict[0][get('Day')]; // Day : Понедельник case 'N' : return get(MONTH) + 1; // Month : 1-12 case 'NN' : return lz(get(MONTH) + 1); // Month : 01-12 case 'M' : return dict[2][get(MONTH)]; // Month : Январь case 'MM' : return dict[1][get(MONTH)]; // Month : Января case 'Y' : return get(YEAR); // Year : 2014 case 'YY' : return lz(get(YEAR) % 100); // Year : 14 } return part; }); } } function lz(num){ return num > 9 ? num : '0' + num; } function addLocale(lang, locale){ function split(index){ var result = []; forEach.call(array(locale.months), function(it){ result.push(it.replace(flexioRegExp, '$' + index)); }); return result; } locales[lang] = [array(locale.weekdays), split(1), split(2)]; return core; } $define(PROTO + FORCED, DATE, { format: createFormat('get'), formatUTC: createFormat('getUTC') }); addLocale(current, { weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday', months: 'January,February,March,April,May,June,July,August,September,October,November,December' }); addLocale('ru', { weekdays: 'Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота', months: 'Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,' + 'Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь' }); core.locale = function(locale){ return has(locales, locale) ? current = locale : current; }; core.addLocale = addLocale; }(/\b\w\w?\b/g, /:(.*)\|(.*)$/, {}, 'en', 'Seconds', 'Minutes', 'Hours', 'Month', 'FullYear'); /****************************************************************************** * Module : console * ******************************************************************************/ !function(console, enabled){ var _console = { enable: function(){ enabled = true }, disable: function(){ enabled = false } }; // Methods from: // https://github.com/DeveloperToolsWG/console-object/blob/master/api.md // https://developer.mozilla.org/en-US/docs/Web/API/console forEach.call(array('assert,clear,count,debug,dir,dirxml,error,exception,group,' + 'groupCollapsed,groupEnd,info,isIndependentlyComposed,log,markTimeline,profile,' + 'profileEnd,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn'), function(key){ var fn = console[key]; _console[key] = function(){ if(enabled && fn)return apply.call(fn, console, arguments); }; } ); // console methods in some browsers are not configurable try { framework && delete global.console; } catch(e){} $define(GLOBAL + FORCED, {console: _console}); }(global.console || {}, true); }(typeof self != 'undefined' && self.Math === Math ? self : Function('return this')(), false);
src/component/board.js
heroinedor/tictactoe
import React from 'react'; import ReactDOM from 'react-dom'; import calculateWinner from '../util/func' function Square(props) { return ( <button className="square" onClick={() => props.onClick()}> {props.value} </button> ); } export default class Board extends React.Component { renderSquare(i) { return <Square value={this.props.squares[i]} onClick={() => this.props.onClick(i)} />; } render() { const winner = calculateWinner(this.props.squares); let status; if (winner){ status= 'The winner is : ' + winner; }else{ status = 'Next player: ' + (this.props.xIsNext ? 'X' : 'O'); } return ( <div> <div className="status">{status}</div> <div className="board-row"> {this.renderSquare(0)} {this.renderSquare(1)} {this.renderSquare(2)} </div> <div className="board-row"> {this.renderSquare(3)} {this.renderSquare(4)} {this.renderSquare(5)} </div> <div className="board-row"> {this.renderSquare(6)} {this.renderSquare(7)} {this.renderSquare(8)} </div> </div> ); } }
app/components/Thumb.js
fakob/electron-test-v003
// @flow import React from 'react'; import PropTypes from 'prop-types'; import { SortableHandle } from 'react-sortable-hoc'; import styles from './ThumbGrid.css'; import inPoint from './../img/Thumb_IN.png'; import outPoint from './../img/Thumb_OUT.png'; import back from './../img/Thumb_BACK.png'; import forward from './../img/Thumb_FORWARD.png'; import scrub from './../img/Thumb_SCRUB.png'; import handle from './../img/Thumb_HANDLE.png'; import hide from './../img/Thumb_HIDE.png'; import show from './../img/Thumb_SHOW.png'; import empty from './../img/Thumb_EMPTY.png'; const DragHandle = SortableHandle(() => { function over(event){ event.target.style.opacity = 1; } function out(event){ event.target.style.opacity = 0.3; } return ( <img src={handle} className={styles.dragHandle} alt="" onMouseOver={over} onMouseLeave={out} /> ); }); const Thumb = ( { onToggle, onRemove, onDragOver, onInPoint, onOutPoint, onBack, onForward, onOver, onOut,hidden, frameNumber, id, objectUrl, width, height, controlersAreVisible } ) => { const thumbWidth = 270; // console.log(`controlersAreVisible: ${controlersAreVisible}`); function over(event) { event.target.style.opacity = 1; } function out(event) { event.target.style.opacity = 0.5; } function pad(num, size) { let s = num.toString(); while (s.length < size) s = `0${s}`; return s; } return ( <div onMouseOver={onOver} onMouseLeave={onOut} className={styles.gridItem} style={{ opacity: hidden ? '0.2' : '1', width: thumbWidth, }} > <img src={objectUrl || empty} className={styles.image} alt="" width={`${thumbWidth}px`} height={`${(thumbWidth * (height / width))}px`} /> <div className={styles.frameNumber} > {pad(frameNumber, 4)} </div> <div style={{ display: controlersAreVisible ? 'block' : 'none' }} > <DragHandle /> <img src={hidden ? show : hide} className={styles.hide} alt="" onClick={onToggle} onMouseOver={over} onMouseLeave={out} /> <img src={inPoint} className={styles.inPoint} alt="" onClick={onInPoint} onMouseOver={over} onMouseLeave={out} /> <img src={back} className={styles.back} alt="" onClick={onBack} onMouseOver={over} onMouseLeave={out} /> {/* <img src={scrub} className={styles.scrub} alt="" onMouseOver={over} onMouseLeave={out} /> */} <img src={forward} className={styles.forward} alt="" onClick={onForward} onMouseOver={over} onMouseLeave={out} /> <img src={outPoint} className={styles.outPoint} alt="" onClick={onOutPoint} onMouseOver={over} onMouseLeave={out} /> </div> </div> ); }; Thumb.defaultProps = { width: 1920, height: 1080 }; Thumb.propTypes = { id: PropTypes.string.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, onToggle: PropTypes.func.isRequired, onRemove: PropTypes.func.isRequired, hidden: PropTypes.bool.isRequired, frameNumber: PropTypes.number.isRequired, onInPoint: PropTypes.func.isRequired, onOutPoint: PropTypes.func.isRequired, onBack: PropTypes.func.isRequired, onForward: PropTypes.func.isRequired, onOver: PropTypes.func.isRequired, onOut: PropTypes.func.isRequired, }; export default Thumb;
lib/svg-icons/notification/ondemand-video.js
ghondar/material-ui
'use strict'; var React = require('react/addons'); var PureRenderMixin = React.addons.PureRenderMixin; var SvgIcon = require('../../svg-icon'); var NotificationOndemandVideo = React.createClass({ displayName: 'NotificationOndemandVideo', mixins: [PureRenderMixin], render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12zm-5-6l-7 4V7z' }) ); } }); module.exports = NotificationOndemandVideo;
src/app/app.js
batazor/LMap
import React from 'react' // eslint-disable-line no-unused-vars import { render } from 'react-dom' import { browserHistory } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import Root from './containers/Root' import configureStore from './store/configureStore' const store = configureStore() const history = syncHistoryWithStore(browserHistory, store) render( <Root store={store} history={history} />, document.getElementById('app') )
day22_search_sort/src/components/TodoEditForm.js
eyesofkids/ironman2017
//@flow import React from 'react' //匯入Props靜態類型的定義 import type { TodoEditFormProps } from '../definitions/TodoTypeDefinition.js' const TodoEditForm = ({ title, onItemUpdate }: TodoEditFormProps) => { //給Flow檢查用的,這個參照值一開始都是null,渲染前是不確定值,所以用any let titleField: any = null return ( <li className="list-group-item"> <input type="text" defaultValue={title} ref={el => { titleField = el }} autoFocus onBlur={(e) => { if (titleField.value.trim() && e.target instanceof HTMLInputElement) { //更新標題 onItemUpdate(titleField.value) } } } onKeyPress={(e) => { if (titleField.value.trim() && e.target instanceof HTMLInputElement && e.key === 'Enter') { //更新標題 onItemUpdate(titleField.value) } } } /> </li> ) } //匯出TodoEditForm模組 export default TodoEditForm
tests/layouts/CoreLayout.spec.js
youdeshi/single-page-app-best-practice-client
import React from 'react' import TestUtils from 'react-addons-test-utils' import CoreLayout from 'layouts/CoreLayout/CoreLayout' function shallowRender (component) { const renderer = TestUtils.createRenderer() renderer.render(component) return renderer.getRenderOutput() } function shallowRenderWithProps (props = {}) { return shallowRender(<CoreLayout {...props} />) } describe('(Layout) Core', function () { let _component let _props let _child beforeEach(function () { _child = <h1 className='child'>Child</h1> _props = { children: _child } _component = shallowRenderWithProps(_props) }) it('Should render as a <div>.', function () { expect(_component.type).to.equal('div') }) })