path
stringlengths
5
304
repo_name
stringlengths
6
79
content
stringlengths
27
1.05M
src/svg-icons/image/image-aspect-ratio.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageImageAspectRatio = (props) => ( <SvgIcon {...props}> <path d="M16 10h-2v2h2v-2zm0 4h-2v2h2v-2zm-8-4H6v2h2v-2zm4 0h-2v2h2v-2zm8-6H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H4V6h16v12z"/> </SvgIcon> ); ImageImageAspectRatio = pure(ImageImageAspectRatio); ImageImageAspectRatio.displayName = 'ImageImageAspectRatio'; export default ImageImageAspectRatio;
fields/types/text/TextColumn.js
andrewlinfoot/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var TextColumn = React.createClass({ displayName: 'TextColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, linkTo: React.PropTypes.string, }, getValue () { // cropping text is important for textarea, which uses this column const value = this.props.data.fields[this.props.col.path]; return value ? value.substr(0, 100) : null; }, render () { const value = this.getValue(); const empty = !value && this.props.linkTo ? true : false; const className = this.props.col.field.monospace ? 'ItemList__value--monospace' : undefined; return ( <ItemsTableCell> <ItemsTableValue className={className} to={this.props.linkTo} empty={empty} padded interior field={this.props.col.type}> {value} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = TextColumn;
test/ColSpec.js
yickli/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Col from '../src/Col'; describe('Col', function () { it('Should set Offset of zero', function () { let instance = ReactTestUtils.renderIntoDocument( <Col xsOffset={0} smOffset={0} mdOffset={0} lgOffset={0} /> ); let instanceClassName = React.findDOMNode(instance).className; assert.ok(instanceClassName.match(/\bcol-xs-offset-0\b/)); assert.ok(instanceClassName.match(/\bcol-sm-offset-0\b/)); assert.ok(instanceClassName.match(/\bcol-md-offset-0\b/)); assert.ok(instanceClassName.match(/\bcol-lg-offset-0\b/)); }); it('Should set Pull of zero', function () { let instance = ReactTestUtils.renderIntoDocument( <Col xsPull={0} smPull={0} mdPull={0} lgPull={0} /> ); let instanceClassName = React.findDOMNode(instance).className; assert.ok(instanceClassName.match(/\bcol-xs-pull-0\b/)); assert.ok(instanceClassName.match(/\bcol-sm-pull-0\b/)); assert.ok(instanceClassName.match(/\bcol-md-pull-0\b/)); assert.ok(instanceClassName.match(/\bcol-lg-pull-0\b/)); }); it('Should set Push of zero', function () { let instance = ReactTestUtils.renderIntoDocument( <Col xsPush={0} smPush={0} mdPush={0} lgPush={0} /> ); let instanceClassName = React.findDOMNode(instance).className; assert.ok(instanceClassName.match(/\bcol-xs-push-0\b/)); assert.ok(instanceClassName.match(/\bcol-sm-push-0\b/)); assert.ok(instanceClassName.match(/\bcol-md-push-0\b/)); assert.ok(instanceClassName.match(/\bcol-lg-push-0\b/)); }); });
node_modules/react-icons/md/account-balance-wallet.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const MdAccountBalanceWallet = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m26.6 22.5q1.1 0 1.8-0.7t0.7-1.8-0.7-1.8-1.8-0.7-1.7 0.7-0.8 1.8 0.8 1.8 1.7 0.7z m-6.6 4.1v-13.2h16.6v13.2h-16.6z m15 3.4v1.6q0 1.4-1 2.4t-2.4 1h-23.2q-1.4 0-2.4-1t-1-2.4v-23.2q0-1.4 1-2.4t2.4-1h23.2q1.4 0 2.4 1t1 2.4v1.6h-15q-1.4 0-2.4 1t-1 2.4v13.2q0 1.4 1 2.4t2.4 1h15z"/></g> </Icon> ) export default MdAccountBalanceWallet
src/Header.js
ChangoMan/hunter-react
import React, { Component } from 'react'; import MainNav from './Header/MainNav'; export default class Header extends Component { render() { return ( <header className="site-header"> <div className="site-header__main"> <div className="container"> <div className="row"> <div className="col-xs-12"> <div> <img width="220" src="http://www.madwire.com/branding-guidelines/img/primary-logo.png" alt="" /> </div> {/* <p>{this.props.title}</p> */} {/* <p>{this.props.message}</p> */} </div> </div> </div> </div> <div className="site-header__nav"> <MainNav /> </div> </header> ); } }
src/components/Users/Users.js
waltcow/newsApp
import React from 'react'; import { connect } from 'dva'; import { Table, Pagination, Popconfirm, Button } from 'antd'; import { routerRedux } from 'dva/router'; import styles from './Users.css'; import { PAGE_SIZE } from '../../constants'; import UserModal from './UserModal'; function Users({ dispatch, list: dataSource, loading, total, page: current }) { function deleteHandler(id) { dispatch({ type: 'users/remove', payload: id, }); } function pageChangeHandler(page) { dispatch(routerRedux.push({ pathname: '/users', query: { page }, })); } function editHandler(id, values) { dispatch({ type: 'users/patch', payload: { id, values }, }); } function createHandler(values) { dispatch({ type: 'users/create', payload: values, }); } const columns = [ { title: 'Name', dataIndex: 'name', key: 'name', render: text => <a href="">{text}</a>, }, { title: 'Email', dataIndex: 'email', key: 'email', }, { title: 'Website', dataIndex: 'website', key: 'website', }, { title: 'Operation', key: 'operation', render: (text, record) => ( <span className={styles.operation}> <UserModal record={record} onOk={editHandler.bind(null, record.id)}> <a>Edit</a> </UserModal> <Popconfirm title="Confirm to delete?" onConfirm={deleteHandler.bind(null, record.id)}> <a href="">Delete</a> </Popconfirm> </span> ), }, ]; return ( <div className={styles.normal}> <div> <div className={styles.create}> <UserModal record={{}} onOk={createHandler}> <Button type="primary">Create User</Button> </UserModal> </div> <Table columns={columns} dataSource={dataSource} loading={loading} rowKey={record => record.id} pagination={false} /> <Pagination className="ant-table-pagination" total={total} current={current} pageSize={PAGE_SIZE} onChange={pageChangeHandler} /> </div> </div> ); } function mapStateToProps(state) { const { list, total, page } = state.users; return { loading: state.loading.models.users, list, total, page, }; } export default connect(mapStateToProps)(Users);
src/common/layouts/Dashboard/views/GuildView/GuildList.js
BeMacized/GrimoireWeb
import React from 'react' import List, { ListItem, ListItemText } from 'material-ui/List' import Avatar from 'material-ui/Avatar' import PropTypes from 'prop-types' import { DEVELOPER_ID } from '../../../../globals' import { MANAGE_GUILD, hasPerms } from '../../../../utils/PermissionUtils' const GuildList = ({guilds, active, onSelect, userId}) => <List disablePadding> {(guilds || []) .sort((a, b) => a.name.localeCompare(b.name)) .sort((x, y) => (parseInt(userId) === DEVELOPER_ID || hasPerms(x.permissons, MANAGE_GUILD) === hasPerms(y.permissions, MANAGE_GUILD)) ? 0 : hasPerms(x.permissions, MANAGE_GUILD) ? -1 : 1) .map(guild => { const isActive = active && guild.id === active.id const permitted = parseInt(userId) === DEVELOPER_ID || hasPerms(guild.permissions, MANAGE_GUILD) return ( <ListItem style={isActive ? {background: 'linear-gradient(to right, #f857a6, #ff5858)'} : {}} button key={guild.id} disabled={!permitted} onClick={() => onSelect(guild)}> <Avatar style={{background: 'linear-gradient(to right, #f857a6, #ff5858)', border: '2px solid ' + (isActive ? '#FFF' : '#f857a6')}} src={guild.icon ? `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.png?size=64` : ''}> {guild.icon ? '' : guild.name.substring(0, 1).toUpperCase()} </Avatar> <ListItemText disableTypography primary={guild.name} secondary={permitted ? '' : <span style={{color: '#F00'}}><br />No "Manage Guild" Permission</span>} style={ { color: (isActive ? '#FFF' : '#555'), fontWeight: (isActive ? 'bold' : 'normal') } } /> </ListItem> ) } )} </List> GuildList.propTypes = { guilds: PropTypes.arrayOf(PropTypes.object), active: PropTypes.object, onSelect: PropTypes.func, userId: PropTypes.string } export default GuildList
src/svg-icons/image/assistant-photo.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageAssistantPhoto = (props) => ( <SvgIcon {...props}> <path d="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z"/> </SvgIcon> ); ImageAssistantPhoto = pure(ImageAssistantPhoto); ImageAssistantPhoto.displayName = 'ImageAssistantPhoto'; ImageAssistantPhoto.muiName = 'SvgIcon'; export default ImageAssistantPhoto;
src/components/error/e504/views/e504.js
vshao/webapp
/** * Created by feichongzheng on 17/6/9. */ import React from 'react' export default () => { return <div>非常抱歉,您的访问已超时!</div> }
ajax/libs/preact/8.2.2/preact.js
jonobr1/cdnjs
!function() { 'use strict'; function VNode() {} function h(nodeName, attributes) { var lastSimple, child, simple, i, children = EMPTY_CHILDREN; for (i = arguments.length; i-- > 2; ) stack.push(arguments[i]); if (attributes && null != attributes.children) { if (!stack.length) stack.push(attributes.children); delete attributes.children; } while (stack.length) if ((child = stack.pop()) && void 0 !== child.pop) for (i = child.length; i--; ) stack.push(child[i]); else { if ('boolean' == typeof child) child = null; if (simple = 'function' != typeof nodeName) if (null == child) child = ''; else if ('number' == typeof child) child = String(child); else if ('string' != typeof child) simple = !1; if (simple && lastSimple) children[children.length - 1] += child; else if (children === EMPTY_CHILDREN) children = [ child ]; else children.push(child); lastSimple = simple; } var p = new VNode(); p.nodeName = nodeName; p.children = children; p.attributes = null == attributes ? void 0 : attributes; p.key = null == attributes ? void 0 : attributes.key; if (void 0 !== options.vnode) options.vnode(p); return p; } function extend(obj, props) { for (var i in props) obj[i] = props[i]; return obj; } function cloneElement(vnode, props) { return h(vnode.nodeName, extend(extend({}, vnode.attributes), props), arguments.length > 2 ? [].slice.call(arguments, 2) : vnode.children); } function enqueueRender(component) { if (!component.__d && (component.__d = !0) && 1 == items.push(component)) (options.debounceRendering || defer)(rerender); } function rerender() { var p, list = items; items = []; while (p = list.pop()) if (p.__d) renderComponent(p); } function isSameNodeType(node, vnode, hydrating) { if ('string' == typeof vnode || 'number' == typeof vnode) return void 0 !== node.splitText; if ('string' == typeof vnode.nodeName) return !node._componentConstructor && isNamedNode(node, vnode.nodeName); else return hydrating || node._componentConstructor === vnode.nodeName; } function isNamedNode(node, nodeName) { return node.__n === nodeName || node.nodeName.toLowerCase() === nodeName.toLowerCase(); } function getNodeProps(vnode) { var props = extend({}, vnode.attributes); props.children = vnode.children; var defaultProps = vnode.nodeName.defaultProps; if (void 0 !== defaultProps) for (var i in defaultProps) if (void 0 === props[i]) props[i] = defaultProps[i]; return props; } function createNode(nodeName, isSvg) { var node = isSvg ? document.createElementNS('http://www.w3.org/2000/svg', nodeName) : document.createElement(nodeName); node.__n = nodeName; return node; } function removeNode(node) { var parentNode = node.parentNode; if (parentNode) parentNode.removeChild(node); } function setAccessor(node, name, old, value, isSvg) { if ('className' === name) name = 'class'; if ('key' === name) ; else if ('ref' === name) { if (old) old(null); if (value) value(node); } else if ('class' === name && !isSvg) node.className = value || ''; else if ('style' === name) { if (!value || 'string' == typeof value || 'string' == typeof old) node.style.cssText = value || ''; if (value && 'object' == typeof value) { if ('string' != typeof old) for (var i in old) if (!(i in value)) node.style[i] = ''; for (var i in value) node.style[i] = 'number' == typeof value[i] && !1 === IS_NON_DIMENSIONAL.test(i) ? value[i] + 'px' : value[i]; } } else if ('dangerouslySetInnerHTML' === name) { if (value) node.innerHTML = value.__html || ''; } else if ('o' == name[0] && 'n' == name[1]) { var useCapture = name !== (name = name.replace(/Capture$/, '')); name = name.toLowerCase().substring(2); if (value) { if (!old) node.addEventListener(name, eventProxy, useCapture); } else node.removeEventListener(name, eventProxy, useCapture); (node.__l || (node.__l = {}))[name] = value; } else if ('list' !== name && 'type' !== name && !isSvg && name in node) { setProperty(node, name, null == value ? '' : value); if (null == value || !1 === value) node.removeAttribute(name); } else { var ns = isSvg && name !== (name = name.replace(/^xlink\:?/, '')); if (null == value || !1 === value) if (ns) node.removeAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase()); else node.removeAttribute(name); else if ('function' != typeof value) if (ns) node.setAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase(), value); else node.setAttribute(name, value); } } function setProperty(node, name, value) { try { node[name] = value; } catch (e) {} } function eventProxy(e) { return this.__l[e.type](options.event && options.event(e) || e); } function flushMounts() { var c; while (c = mounts.pop()) { if (options.afterMount) options.afterMount(c); if (c.componentDidMount) c.componentDidMount(); } } function diff(dom, vnode, context, mountAll, parent, componentRoot) { if (!diffLevel++) { isSvgMode = null != parent && void 0 !== parent.ownerSVGElement; hydrating = null != dom && !('__preactattr_' in dom); } var ret = idiff(dom, vnode, context, mountAll, componentRoot); if (parent && ret.parentNode !== parent) parent.appendChild(ret); if (!--diffLevel) { hydrating = !1; if (!componentRoot) flushMounts(); } return ret; } function idiff(dom, vnode, context, mountAll, componentRoot) { var out = dom, prevSvgMode = isSvgMode; if (null == vnode || 'boolean' == typeof vnode) vnode = ''; if ('string' == typeof vnode || 'number' == typeof vnode) { if (dom && void 0 !== dom.splitText && dom.parentNode && (!dom._component || componentRoot)) { if (dom.nodeValue != vnode) dom.nodeValue = vnode; } else { out = document.createTextNode(vnode); if (dom) { if (dom.parentNode) dom.parentNode.replaceChild(out, dom); recollectNodeTree(dom, !0); } } out.__preactattr_ = !0; return out; } var vnodeName = vnode.nodeName; if ('function' == typeof vnodeName) return buildComponentFromVNode(dom, vnode, context, mountAll); isSvgMode = 'svg' === vnodeName ? !0 : 'foreignObject' === vnodeName ? !1 : isSvgMode; vnodeName = String(vnodeName); if (!dom || !isNamedNode(dom, vnodeName)) { out = createNode(vnodeName, isSvgMode); if (dom) { while (dom.firstChild) out.appendChild(dom.firstChild); if (dom.parentNode) dom.parentNode.replaceChild(out, dom); recollectNodeTree(dom, !0); } } var fc = out.firstChild, props = out.__preactattr_, vchildren = vnode.children; if (null == props) { props = out.__preactattr_ = {}; for (var a = out.attributes, i = a.length; i--; ) props[a[i].name] = a[i].value; } if (!hydrating && vchildren && 1 === vchildren.length && 'string' == typeof vchildren[0] && null != fc && void 0 !== fc.splitText && null == fc.nextSibling) { if (fc.nodeValue != vchildren[0]) fc.nodeValue = vchildren[0]; } else if (vchildren && vchildren.length || null != fc) innerDiffNode(out, vchildren, context, mountAll, hydrating || null != props.dangerouslySetInnerHTML); diffAttributes(out, vnode.attributes, props); isSvgMode = prevSvgMode; return out; } function innerDiffNode(dom, vchildren, context, mountAll, isHydrating) { var j, c, f, vchild, child, originalChildren = dom.childNodes, children = [], keyed = {}, keyedLen = 0, min = 0, len = originalChildren.length, childrenLen = 0, vlen = vchildren ? vchildren.length : 0; if (0 !== len) for (var i = 0; i < len; i++) { var _child = originalChildren[i], props = _child.__preactattr_, key = vlen && props ? _child._component ? _child._component.__k : props.key : null; if (null != key) { keyedLen++; keyed[key] = _child; } else if (props || (void 0 !== _child.splitText ? isHydrating ? _child.nodeValue.trim() : !0 : isHydrating)) children[childrenLen++] = _child; } if (0 !== vlen) for (var i = 0; i < vlen; i++) { vchild = vchildren[i]; child = null; var key = vchild.key; if (null != key) { if (keyedLen && void 0 !== keyed[key]) { child = keyed[key]; keyed[key] = void 0; keyedLen--; } } else if (!child && min < childrenLen) for (j = min; j < childrenLen; j++) if (void 0 !== children[j] && isSameNodeType(c = children[j], vchild, isHydrating)) { child = c; children[j] = void 0; if (j === childrenLen - 1) childrenLen--; if (j === min) min++; break; } child = idiff(child, vchild, context, mountAll); f = originalChildren[i]; if (child && child !== dom && child !== f) if (null == f) dom.appendChild(child); else if (child === f.nextSibling) removeNode(f); else dom.insertBefore(child, f); } if (keyedLen) for (var i in keyed) if (void 0 !== keyed[i]) recollectNodeTree(keyed[i], !1); while (min <= childrenLen) if (void 0 !== (child = children[childrenLen--])) recollectNodeTree(child, !1); } function recollectNodeTree(node, unmountOnly) { var component = node._component; if (component) unmountComponent(component); else { if (null != node.__preactattr_ && node.__preactattr_.ref) node.__preactattr_.ref(null); if (!1 === unmountOnly || null == node.__preactattr_) removeNode(node); removeChildren(node); } } function removeChildren(node) { node = node.lastChild; while (node) { var next = node.previousSibling; recollectNodeTree(node, !0); node = next; } } function diffAttributes(dom, attrs, old) { var name; for (name in old) if ((!attrs || null == attrs[name]) && null != old[name]) setAccessor(dom, name, old[name], old[name] = void 0, isSvgMode); for (name in attrs) if (!('children' === name || 'innerHTML' === name || name in old && attrs[name] === ('value' === name || 'checked' === name ? dom[name] : old[name]))) setAccessor(dom, name, old[name], old[name] = attrs[name], isSvgMode); } function collectComponent(component) { var name = component.constructor.name; (components[name] || (components[name] = [])).push(component); } function createComponent(Ctor, props, context) { var inst, list = components[Ctor.name]; if (Ctor.prototype && Ctor.prototype.render) { inst = new Ctor(props, context); Component.call(inst, props, context); } else { inst = new Component(props, context); inst.constructor = Ctor; inst.render = doRender; } if (list) for (var i = list.length; i--; ) if (list[i].constructor === Ctor) { inst.__b = list[i].__b; list.splice(i, 1); break; } return inst; } function doRender(props, state, context) { return this.constructor(props, context); } function setComponentProps(component, props, opts, context, mountAll) { if (!component.__x) { component.__x = !0; if (component.__r = props.ref) delete props.ref; if (component.__k = props.key) delete props.key; if (!component.base || mountAll) { if (component.componentWillMount) component.componentWillMount(); } else if (component.componentWillReceiveProps) component.componentWillReceiveProps(props, context); if (context && context !== component.context) { if (!component.__c) component.__c = component.context; component.context = context; } if (!component.__p) component.__p = component.props; component.props = props; component.__x = !1; if (0 !== opts) if (1 === opts || !1 !== options.syncComponentUpdates || !component.base) renderComponent(component, 1, mountAll); else enqueueRender(component); if (component.__r) component.__r(component); } } function renderComponent(component, opts, mountAll, isChild) { if (!component.__x) { var rendered, inst, cbase, props = component.props, state = component.state, context = component.context, previousProps = component.__p || props, previousState = component.__s || state, previousContext = component.__c || context, isUpdate = component.base, nextBase = component.__b, initialBase = isUpdate || nextBase, initialChildComponent = component._component, skip = !1; if (isUpdate) { component.props = previousProps; component.state = previousState; component.context = previousContext; if (2 !== opts && component.shouldComponentUpdate && !1 === component.shouldComponentUpdate(props, state, context)) skip = !0; else if (component.componentWillUpdate) component.componentWillUpdate(props, state, context); component.props = props; component.state = state; component.context = context; } component.__p = component.__s = component.__c = component.__b = null; component.__d = !1; if (!skip) { rendered = component.render(props, state, context); if (component.getChildContext) context = extend(extend({}, context), component.getChildContext()); var toUnmount, base, childComponent = rendered && rendered.nodeName; if ('function' == typeof childComponent) { var childProps = getNodeProps(rendered); inst = initialChildComponent; if (inst && inst.constructor === childComponent && childProps.key == inst.__k) setComponentProps(inst, childProps, 1, context, !1); else { toUnmount = inst; component._component = inst = createComponent(childComponent, childProps, context); inst.__b = inst.__b || nextBase; inst.__u = component; setComponentProps(inst, childProps, 0, context, !1); renderComponent(inst, 1, mountAll, !0); } base = inst.base; } else { cbase = initialBase; toUnmount = initialChildComponent; if (toUnmount) cbase = component._component = null; if (initialBase || 1 === opts) { if (cbase) cbase._component = null; base = diff(cbase, rendered, context, mountAll || !isUpdate, initialBase && initialBase.parentNode, !0); } } if (initialBase && base !== initialBase && inst !== initialChildComponent) { var baseParent = initialBase.parentNode; if (baseParent && base !== baseParent) { baseParent.replaceChild(base, initialBase); if (!toUnmount) { initialBase._component = null; recollectNodeTree(initialBase, !1); } } } if (toUnmount) unmountComponent(toUnmount); component.base = base; if (base && !isChild) { var componentRef = component, t = component; while (t = t.__u) (componentRef = t).base = base; base._component = componentRef; base._componentConstructor = componentRef.constructor; } } if (!isUpdate || mountAll) mounts.unshift(component); else if (!skip) { if (component.componentDidUpdate) component.componentDidUpdate(previousProps, previousState, previousContext); if (options.afterUpdate) options.afterUpdate(component); } if (null != component.__h) while (component.__h.length) component.__h.pop().call(component); if (!diffLevel && !isChild) flushMounts(); } } function buildComponentFromVNode(dom, vnode, context, mountAll) { var c = dom && dom._component, originalComponent = c, oldDom = dom, isDirectOwner = c && dom._componentConstructor === vnode.nodeName, isOwner = isDirectOwner, props = getNodeProps(vnode); while (c && !isOwner && (c = c.__u)) isOwner = c.constructor === vnode.nodeName; if (c && isOwner && (!mountAll || c._component)) { setComponentProps(c, props, 3, context, mountAll); dom = c.base; } else { if (originalComponent && !isDirectOwner) { unmountComponent(originalComponent); dom = oldDom = null; } c = createComponent(vnode.nodeName, props, context); if (dom && !c.__b) { c.__b = dom; oldDom = null; } setComponentProps(c, props, 1, context, mountAll); dom = c.base; if (oldDom && dom !== oldDom) { oldDom._component = null; recollectNodeTree(oldDom, !1); } } return dom; } function unmountComponent(component) { if (options.beforeUnmount) options.beforeUnmount(component); var base = component.base; component.__x = !0; if (component.componentWillUnmount) component.componentWillUnmount(); component.base = null; var inner = component._component; if (inner) unmountComponent(inner); else if (base) { if (base.__preactattr_ && base.__preactattr_.ref) base.__preactattr_.ref(null); component.__b = base; removeNode(base); collectComponent(component); removeChildren(base); } if (component.__r) component.__r(null); } function Component(props, context) { this.__d = !0; this.context = context; this.props = props; this.state = this.state || {}; } function render(vnode, parent, merge) { return diff(merge, vnode, {}, !1, parent, !1); } var options = {}; var stack = []; var EMPTY_CHILDREN = []; var defer = 'function' == typeof Promise ? Promise.resolve().then.bind(Promise.resolve()) : setTimeout; var IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i; var items = []; var mounts = []; var diffLevel = 0; var isSvgMode = !1; var hydrating = !1; var components = {}; extend(Component.prototype, { setState: function(state, callback) { var s = this.state; if (!this.__s) this.__s = extend({}, s); extend(s, 'function' == typeof state ? state(s, this.props) : state); if (callback) (this.__h = this.__h || []).push(callback); enqueueRender(this); }, forceUpdate: function(callback) { if (callback) (this.__h = this.__h || []).push(callback); renderComponent(this, 2); }, render: function() {} }); var preact = { h: h, createElement: h, cloneElement: cloneElement, Component: Component, render: render, rerender: rerender, options: options }; if ('undefined' != typeof module) module.exports = preact; else self.preact = preact; }(); //# sourceMappingURL=preact.js.map
packages/material-ui-icons/src/TitleRounded.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M5 5.5C5 6.33 5.67 7 6.5 7h4v10.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V7h4c.83 0 1.5-.67 1.5-1.5S18.33 4 17.5 4h-11C5.67 4 5 4.67 5 5.5z" /></g></React.Fragment> , 'TitleRounded');
frontend/src/components/eois/details/overview/selectedPartners/singleSelectedPartnerInfo.js
unicef/un-partner-portal
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { reduxForm } from 'redux-form'; import { updateApplication } from '../../../../../reducers/applicationDetails'; import { loadCfei } from '../../../../../reducers/cfeiDetails'; import { selectNormalizedDirectJustification } from '../../../../../store'; import FileForm from '../../../../forms/fileForm'; import TextFieldForm from '../../../../forms/textFieldForm'; import SelectForm from '../../../../forms/selectForm'; import GridColumn from '../../../../common/grid/gridColumn'; const messages = { justificationWaiver: 'Justification for direct selection/retention', justificationSummary: 'Justification summary', attachment: 'Attachment', }; const SingleSelectedPartnerInfo = (props) => { const { directJustifications } = props; return ( <form> <GridColumn> <SelectForm values={directJustifications} fieldName="ds_justification_select" label={messages.justificationWaiver} readOnly /> <TextFieldForm fieldName="justification_reason" label={messages.justificationSummary} readOnly /> <FileForm fieldName="ds_attachment" label={messages.attachment} readOnly formName="formSingleSelectedPartnerInfo" /> </GridColumn> </form> ); }; SingleSelectedPartnerInfo.propTypes = { directJustifications: PropTypes.array, form: PropTypes.string, }; const formSingleSelectedPartnerInfo = reduxForm({ form: 'singleSelectedPartnerInfo', enableReinitialize: true, })(SingleSelectedPartnerInfo); const mapStateToProps = (state, ownProps) => { const justificationReason = ownProps.partner.justification_reason; const dsJustificationSelect = ownProps.partner.ds_justification_select; const attachment = ownProps.partner.ds_attachment; return { directJustifications: selectNormalizedDirectJustification(state), initialValues: { justification_reason: justificationReason, ds_justification_select: dsJustificationSelect, ds_attachment: attachment, }, }; }; const mapDispatchToProps = (dispatch, { id, partner = {} }) => ({ acceptSelection: () => dispatch(updateApplication(partner.id, { did_accept: true, did_decline: false })), loadCfei: () => dispatch(loadCfei(id)), }); export default connect(mapStateToProps, mapDispatchToProps)(formSingleSelectedPartnerInfo);
src/components/__tests__/InfoBar-test.js
hakonrossebo/ciq-layout-composer
import React from 'react'; import ReactDOM from 'react-dom'; import {renderIntoDocument} from 'react-addons-test-utils'; import { expect} from 'chai'; import { InfoBar } from 'components'; import { Provider } from 'react-redux'; import { browserHistory } from 'react-router'; import createStore from 'redux/create'; import ApiClient from 'helpers/ApiClient'; const client = new ApiClient(); describe('InfoBar', () => { const mockStore = { info: { load: () => {}, loaded: true, loading: false, data: { message: 'This came from the api server', time: Date.now() } } }; const store = createStore(browserHistory, client, mockStore); const renderer = renderIntoDocument( <Provider store={store} key="provider"> <InfoBar/> </Provider> ); const dom = ReactDOM.findDOMNode(renderer); it('should render correctly', () => { return expect(renderer).to.be.ok; }); it('should render with correct value', () => { const text = dom.getElementsByTagName('strong')[0].textContent; expect(text).to.equal(mockStore.info.data.message); }); it('should render with a reload button', () => { const text = dom.getElementsByTagName('button')[0].textContent; expect(text).to.be.a('string'); }); it('should render the correct className', () => { const styles = require('components/InfoBar/InfoBar.scss'); expect(styles.infoBar).to.be.a('string'); expect(dom.className).to.include(styles.infoBar); }); });
ajax/libs/yui/3.14.1/scrollview-base/scrollview-base.js
senekis/cdnjs
YUI.add('scrollview-base', function (Y, NAME) { /** * The scrollview-base module provides a basic ScrollView Widget, without scrollbar indicators * * @module scrollview * @submodule scrollview-base */ // Local vars var getClassName = Y.ClassNameManager.getClassName, DOCUMENT = Y.config.doc, IE = Y.UA.ie, NATIVE_TRANSITIONS = Y.Transition.useNative, vendorPrefix = Y.Transition._VENDOR_PREFIX, // Todo: This is a private property, and alternative approaches should be investigated SCROLLVIEW = 'scrollview', CLASS_NAMES = { vertical: getClassName(SCROLLVIEW, 'vert'), horizontal: getClassName(SCROLLVIEW, 'horiz') }, EV_SCROLL_END = 'scrollEnd', FLICK = 'flick', DRAG = 'drag', MOUSEWHEEL = 'mousewheel', UI = 'ui', TOP = 'top', LEFT = 'left', PX = 'px', AXIS = 'axis', SCROLL_Y = 'scrollY', SCROLL_X = 'scrollX', BOUNCE = 'bounce', DISABLED = 'disabled', DECELERATION = 'deceleration', DIM_X = 'x', DIM_Y = 'y', BOUNDING_BOX = 'boundingBox', CONTENT_BOX = 'contentBox', GESTURE_MOVE = 'gesturemove', START = 'start', END = 'end', EMPTY = '', ZERO = '0s', SNAP_DURATION = 'snapDuration', SNAP_EASING = 'snapEasing', EASING = 'easing', FRAME_DURATION = 'frameDuration', BOUNCE_RANGE = 'bounceRange', _constrain = function (val, min, max) { return Math.min(Math.max(val, min), max); }; /** * ScrollView provides a scrollable widget, supporting flick gestures, * across both touch and mouse based devices. * * @class ScrollView * @param config {Object} Object literal with initial attribute values * @extends Widget * @constructor */ function ScrollView() { ScrollView.superclass.constructor.apply(this, arguments); } Y.ScrollView = Y.extend(ScrollView, Y.Widget, { // *** Y.ScrollView prototype /** * Flag driving whether or not we should try and force H/W acceleration when transforming. Currently enabled by default for Webkit. * Used by the _transform method. * * @property _forceHWTransforms * @type boolean * @protected */ _forceHWTransforms: Y.UA.webkit ? true : false, /** * <p>Used to control whether or not ScrollView's internal * gesturemovestart, gesturemove and gesturemoveend * event listeners should preventDefault. The value is an * object, with "start", "move" and "end" properties used to * specify which events should preventDefault and which shouldn't:</p> * * <pre> * { * start: false, * move: true, * end: false * } * </pre> * * <p>The default values are set up in order to prevent panning, * on touch devices, while allowing click listeners on elements inside * the ScrollView to be notified as expected.</p> * * @property _prevent * @type Object * @protected */ _prevent: { start: false, move: true, end: false }, /** * Contains the distance (postive or negative) in pixels by which * the scrollview was last scrolled. This is useful when setting up * click listeners on the scrollview content, which on mouse based * devices are always fired, even after a drag/flick. * * <p>Touch based devices don't currently fire a click event, * if the finger has been moved (beyond a threshold) so this * check isn't required, if working in a purely touch based environment</p> * * @property lastScrolledAmt * @type Number * @public * @default 0 */ lastScrolledAmt: 0, /** * Internal state, defines the minimum amount that the scrollview can be scrolled along the X axis * * @property _minScrollX * @type number * @protected */ _minScrollX: null, /** * Internal state, defines the maximum amount that the scrollview can be scrolled along the X axis * * @property _maxScrollX * @type number * @protected */ _maxScrollX: null, /** * Internal state, defines the minimum amount that the scrollview can be scrolled along the Y axis * * @property _minScrollY * @type number * @protected */ _minScrollY: null, /** * Internal state, defines the maximum amount that the scrollview can be scrolled along the Y axis * * @property _maxScrollY * @type number * @protected */ _maxScrollY: null, /** * Designated initializer * * @method initializer * @param {config} Configuration object for the plugin */ initializer: function () { var sv = this; // Cache these values, since they aren't going to change. sv._bb = sv.get(BOUNDING_BOX); sv._cb = sv.get(CONTENT_BOX); // Cache some attributes sv._cAxis = sv.get(AXIS); sv._cBounce = sv.get(BOUNCE); sv._cBounceRange = sv.get(BOUNCE_RANGE); sv._cDeceleration = sv.get(DECELERATION); sv._cFrameDuration = sv.get(FRAME_DURATION); }, /** * bindUI implementation * * Hooks up events for the widget * @method bindUI */ bindUI: function () { var sv = this; // Bind interaction listers sv._bindFlick(sv.get(FLICK)); sv._bindDrag(sv.get(DRAG)); sv._bindMousewheel(true); // Bind change events sv._bindAttrs(); // IE SELECT HACK. See if we can do this non-natively and in the gesture for a future release. if (IE) { sv._fixIESelect(sv._bb, sv._cb); } // Set any deprecated static properties if (ScrollView.SNAP_DURATION) { sv.set(SNAP_DURATION, ScrollView.SNAP_DURATION); } if (ScrollView.SNAP_EASING) { sv.set(SNAP_EASING, ScrollView.SNAP_EASING); } if (ScrollView.EASING) { sv.set(EASING, ScrollView.EASING); } if (ScrollView.FRAME_STEP) { sv.set(FRAME_DURATION, ScrollView.FRAME_STEP); } if (ScrollView.BOUNCE_RANGE) { sv.set(BOUNCE_RANGE, ScrollView.BOUNCE_RANGE); } // Recalculate dimension properties // TODO: This should be throttled. // Y.one(WINDOW).after('resize', sv._afterDimChange, sv); }, /** * Bind event listeners * * @method _bindAttrs * @private */ _bindAttrs: function () { var sv = this, scrollChangeHandler = sv._afterScrollChange, dimChangeHandler = sv._afterDimChange; // Bind any change event listeners sv.after({ 'scrollEnd': sv._afterScrollEnd, 'disabledChange': sv._afterDisabledChange, 'flickChange': sv._afterFlickChange, 'dragChange': sv._afterDragChange, 'axisChange': sv._afterAxisChange, 'scrollYChange': scrollChangeHandler, 'scrollXChange': scrollChangeHandler, 'heightChange': dimChangeHandler, 'widthChange': dimChangeHandler }); }, /** * Bind (or unbind) gesture move listeners required for drag support * * @method _bindDrag * @param drag {boolean} If true, the method binds listener to enable * drag (gesturemovestart). If false, the method unbinds gesturemove * listeners for drag support. * @private */ _bindDrag: function (drag) { var sv = this, bb = sv._bb; // Unbind any previous 'drag' listeners bb.detach(DRAG + '|*'); if (drag) { bb.on(DRAG + '|' + GESTURE_MOVE + START, Y.bind(sv._onGestureMoveStart, sv)); } }, /** * Bind (or unbind) flick listeners. * * @method _bindFlick * @param flick {Object|boolean} If truthy, the method binds listeners for * flick support. If false, the method unbinds flick listeners. * @private */ _bindFlick: function (flick) { var sv = this, bb = sv._bb; // Unbind any previous 'flick' listeners bb.detach(FLICK + '|*'); if (flick) { bb.on(FLICK + '|' + FLICK, Y.bind(sv._flick, sv), flick); // Rebind Drag, becuase _onGestureMoveEnd always has to fire -after- _flick sv._bindDrag(sv.get(DRAG)); } }, /** * Bind (or unbind) mousewheel listeners. * * @method _bindMousewheel * @param mousewheel {Object|boolean} If truthy, the method binds listeners for * mousewheel support. If false, the method unbinds mousewheel listeners. * @private */ _bindMousewheel: function (mousewheel) { var sv = this, bb = sv._bb; // Unbind any previous 'mousewheel' listeners // TODO: This doesn't actually appear to work properly. Fix. #2532743 bb.detach(MOUSEWHEEL + '|*'); // Only enable for vertical scrollviews if (mousewheel) { // Bound to document, because that's where mousewheel events fire off of. Y.one(DOCUMENT).on(MOUSEWHEEL, Y.bind(sv._mousewheel, sv)); } }, /** * syncUI implementation. * * Update the scroll position, based on the current value of scrollX/scrollY. * * @method syncUI */ syncUI: function () { var sv = this, scrollDims = sv._getScrollDims(), width = scrollDims.offsetWidth, height = scrollDims.offsetHeight, scrollWidth = scrollDims.scrollWidth, scrollHeight = scrollDims.scrollHeight; // If the axis is undefined, auto-calculate it if (sv._cAxis === undefined) { // This should only ever be run once (for now). // In the future SV might post-load axis changes sv._cAxis = { x: (scrollWidth > width), y: (scrollHeight > height) }; sv._set(AXIS, sv._cAxis); } // get text direction on or inherited by scrollview node sv.rtl = (sv._cb.getComputedStyle('direction') === 'rtl'); // Cache the disabled value sv._cDisabled = sv.get(DISABLED); // Run this to set initial values sv._uiDimensionsChange(); // If we're out-of-bounds, snap back. if (sv._isOutOfBounds()) { sv._snapBack(); } }, /** * Utility method to obtain widget dimensions * * @method _getScrollDims * @return {Object} The offsetWidth, offsetHeight, scrollWidth and * scrollHeight as an array: [offsetWidth, offsetHeight, scrollWidth, * scrollHeight] * @private */ _getScrollDims: function () { var sv = this, cb = sv._cb, bb = sv._bb, TRANS = ScrollView._TRANSITION, // Ideally using CSSMatrix - don't think we have it normalized yet though. // origX = (new WebKitCSSMatrix(cb.getComputedStyle("transform"))).e, // origY = (new WebKitCSSMatrix(cb.getComputedStyle("transform"))).f, origX = sv.get(SCROLL_X), origY = sv.get(SCROLL_Y), origHWTransform, dims; // TODO: Is this OK? Just in case it's called 'during' a transition. if (NATIVE_TRANSITIONS) { cb.setStyle(TRANS.DURATION, ZERO); cb.setStyle(TRANS.PROPERTY, EMPTY); } origHWTransform = sv._forceHWTransforms; sv._forceHWTransforms = false; // the z translation was causing issues with picking up accurate scrollWidths in Chrome/Mac. sv._moveTo(cb, 0, 0); dims = { 'offsetWidth': bb.get('offsetWidth'), 'offsetHeight': bb.get('offsetHeight'), 'scrollWidth': bb.get('scrollWidth'), 'scrollHeight': bb.get('scrollHeight') }; sv._moveTo(cb, -(origX), -(origY)); sv._forceHWTransforms = origHWTransform; return dims; }, /** * This method gets invoked whenever the height or width attributes change, * allowing us to determine which scrolling axes need to be enabled. * * @method _uiDimensionsChange * @protected */ _uiDimensionsChange: function () { var sv = this, bb = sv._bb, scrollDims = sv._getScrollDims(), width = scrollDims.offsetWidth, height = scrollDims.offsetHeight, scrollWidth = scrollDims.scrollWidth, scrollHeight = scrollDims.scrollHeight, rtl = sv.rtl, svAxis = sv._cAxis, minScrollX = (rtl ? Math.min(0, -(scrollWidth - width)) : 0), maxScrollX = (rtl ? 0 : Math.max(0, scrollWidth - width)), minScrollY = 0, maxScrollY = Math.max(0, scrollHeight - height); if (svAxis && svAxis.x) { bb.addClass(CLASS_NAMES.horizontal); } if (svAxis && svAxis.y) { bb.addClass(CLASS_NAMES.vertical); } sv._setBounds({ minScrollX: minScrollX, maxScrollX: maxScrollX, minScrollY: minScrollY, maxScrollY: maxScrollY }); }, /** * Set the bounding dimensions of the ScrollView * * @method _setBounds * @protected * @param bounds {Object} [duration] ms of the scroll animation. (default is 0) * @param {Number} [bounds.minScrollX] The minimum scroll X value * @param {Number} [bounds.maxScrollX] The maximum scroll X value * @param {Number} [bounds.minScrollY] The minimum scroll Y value * @param {Number} [bounds.maxScrollY] The maximum scroll Y value */ _setBounds: function (bounds) { var sv = this; // TODO: Do a check to log if the bounds are invalid sv._minScrollX = bounds.minScrollX; sv._maxScrollX = bounds.maxScrollX; sv._minScrollY = bounds.minScrollY; sv._maxScrollY = bounds.maxScrollY; }, /** * Get the bounding dimensions of the ScrollView * * @method _getBounds * @protected */ _getBounds: function () { var sv = this; return { minScrollX: sv._minScrollX, maxScrollX: sv._maxScrollX, minScrollY: sv._minScrollY, maxScrollY: sv._maxScrollY }; }, /** * Scroll the element to a given xy coordinate * * @method scrollTo * @param x {Number} The x-position to scroll to. (null for no movement) * @param y {Number} The y-position to scroll to. (null for no movement) * @param {Number} [duration] ms of the scroll animation. (default is 0) * @param {String} [easing] An easing equation if duration is set. (default is `easing` attribute) * @param {String} [node] The node to transform. Setting this can be useful in * dual-axis paginated instances. (default is the instance's contentBox) */ scrollTo: function (x, y, duration, easing, node) { // Check to see if widget is disabled if (this._cDisabled) { return; } var sv = this, cb = sv._cb, TRANS = ScrollView._TRANSITION, callback = Y.bind(sv._onTransEnd, sv), // @Todo : cache this newX = 0, newY = 0, transition = {}, transform; // default the optional arguments duration = duration || 0; easing = easing || sv.get(EASING); // @TODO: Cache this node = node || cb; if (x !== null) { sv.set(SCROLL_X, x, {src:UI}); newX = -(x); } if (y !== null) { sv.set(SCROLL_Y, y, {src:UI}); newY = -(y); } transform = sv._transform(newX, newY); if (NATIVE_TRANSITIONS) { // ANDROID WORKAROUND - try and stop existing transition, before kicking off new one. node.setStyle(TRANS.DURATION, ZERO).setStyle(TRANS.PROPERTY, EMPTY); } // Move if (duration === 0) { if (NATIVE_TRANSITIONS) { node.setStyle('transform', transform); } else { // TODO: If both set, batch them in the same update // Update: Nope, setStyles() just loops through each property and applies it. if (x !== null) { node.setStyle(LEFT, newX + PX); } if (y !== null) { node.setStyle(TOP, newY + PX); } } } // Animate else { transition.easing = easing; transition.duration = duration / 1000; if (NATIVE_TRANSITIONS) { transition.transform = transform; } else { transition.left = newX + PX; transition.top = newY + PX; } node.transition(transition, callback); } }, /** * Utility method, to create the translate transform string with the * x, y translation amounts provided. * * @method _transform * @param {Number} x Number of pixels to translate along the x axis * @param {Number} y Number of pixels to translate along the y axis * @private */ _transform: function (x, y) { // TODO: Would we be better off using a Matrix for this? var prop = 'translate(' + x + 'px, ' + y + 'px)'; if (this._forceHWTransforms) { prop += ' translateZ(0)'; } return prop; }, /** * Utility method, to move the given element to the given xy position * * @method _moveTo * @param node {Node} The node to move * @param x {Number} The x-position to move to * @param y {Number} The y-position to move to * @private */ _moveTo : function(node, x, y) { if (NATIVE_TRANSITIONS) { node.setStyle('transform', this._transform(x, y)); } else { node.setStyle(LEFT, x + PX); node.setStyle(TOP, y + PX); } }, /** * Content box transition callback * * @method _onTransEnd * @param {Event.Facade} e The event facade * @private */ _onTransEnd: function () { var sv = this; // If for some reason we're OOB, snapback if (sv._isOutOfBounds()) { sv._snapBack(); } else { /** * Notification event fired at the end of a scroll transition * * @event scrollEnd * @param e {EventFacade} The default event facade. */ sv.fire(EV_SCROLL_END); } }, /** * gesturemovestart event handler * * @method _onGestureMoveStart * @param e {Event.Facade} The gesturemovestart event facade * @private */ _onGestureMoveStart: function (e) { if (this._cDisabled) { return false; } var sv = this, bb = sv._bb, currentX = sv.get(SCROLL_X), currentY = sv.get(SCROLL_Y), clientX = e.clientX, clientY = e.clientY; if (sv._prevent.start) { e.preventDefault(); } // if a flick animation is in progress, cancel it if (sv._flickAnim) { sv._cancelFlick(); sv._onTransEnd(); } // Reset lastScrolledAmt sv.lastScrolledAmt = 0; // Stores data for this gesture cycle. Cleaned up later sv._gesture = { // Will hold the axis value axis: null, // The current attribute values startX: currentX, startY: currentY, // The X/Y coordinates where the event began startClientX: clientX, startClientY: clientY, // The X/Y coordinates where the event will end endClientX: null, endClientY: null, // The current delta of the event deltaX: null, deltaY: null, // Will be populated for flicks flick: null, // Create some listeners for the rest of the gesture cycle onGestureMove: bb.on(DRAG + '|' + GESTURE_MOVE, Y.bind(sv._onGestureMove, sv)), // @TODO: Don't bind gestureMoveEnd if it's a Flick? onGestureMoveEnd: bb.on(DRAG + '|' + GESTURE_MOVE + END, Y.bind(sv._onGestureMoveEnd, sv)) }; }, /** * gesturemove event handler * * @method _onGestureMove * @param e {Event.Facade} The gesturemove event facade * @private */ _onGestureMove: function (e) { var sv = this, gesture = sv._gesture, svAxis = sv._cAxis, svAxisX = svAxis.x, svAxisY = svAxis.y, startX = gesture.startX, startY = gesture.startY, startClientX = gesture.startClientX, startClientY = gesture.startClientY, clientX = e.clientX, clientY = e.clientY; if (sv._prevent.move) { e.preventDefault(); } gesture.deltaX = startClientX - clientX; gesture.deltaY = startClientY - clientY; // Determine if this is a vertical or horizontal movement // @TODO: This is crude, but it works. Investigate more intelligent ways to detect intent if (gesture.axis === null) { gesture.axis = (Math.abs(gesture.deltaX) > Math.abs(gesture.deltaY)) ? DIM_X : DIM_Y; } // Move X or Y. @TODO: Move both if dualaxis. if (gesture.axis === DIM_X && svAxisX) { sv.set(SCROLL_X, startX + gesture.deltaX); } else if (gesture.axis === DIM_Y && svAxisY) { sv.set(SCROLL_Y, startY + gesture.deltaY); } }, /** * gesturemoveend event handler * * @method _onGestureMoveEnd * @param e {Event.Facade} The gesturemoveend event facade * @private */ _onGestureMoveEnd: function (e) { var sv = this, gesture = sv._gesture, flick = gesture.flick, clientX = e.clientX, clientY = e.clientY, isOOB; if (sv._prevent.end) { e.preventDefault(); } // Store the end X/Y coordinates gesture.endClientX = clientX; gesture.endClientY = clientY; // Cleanup the event handlers gesture.onGestureMove.detach(); gesture.onGestureMoveEnd.detach(); // If this wasn't a flick, wrap up the gesture cycle if (!flick) { // @TODO: Be more intelligent about this. Look at the Flick attribute to see // if it is safe to assume _flick did or didn't fire. // Then, the order _flick and _onGestureMoveEnd fire doesn't matter? // If there was movement (_onGestureMove fired) if (gesture.deltaX !== null && gesture.deltaY !== null) { isOOB = sv._isOutOfBounds(); // If we're out-out-bounds, then snapback if (isOOB) { sv._snapBack(); } // Inbounds else { // Fire scrollEnd unless this is a paginated instance and the gesture axis is the same as paginator's // Not totally confident this is ideal to access a plugin's properties from a host, @TODO revisit if (!sv.pages || (sv.pages && !sv.pages.get(AXIS)[gesture.axis])) { sv._onTransEnd(); } } } } }, /** * Execute a flick at the end of a scroll action * * @method _flick * @param e {Event.Facade} The Flick event facade * @private */ _flick: function (e) { if (this._cDisabled) { return false; } var sv = this, svAxis = sv._cAxis, flick = e.flick, flickAxis = flick.axis, flickVelocity = flick.velocity, axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y, startPosition = sv.get(axisAttr); // Sometimes flick is enabled, but drag is disabled if (sv._gesture) { sv._gesture.flick = flick; } // Prevent unneccesary firing of _flickFrame if we can't scroll on the flick axis if (svAxis[flickAxis]) { sv._flickFrame(flickVelocity, flickAxis, startPosition); } }, /** * Execute a single frame in the flick animation * * @method _flickFrame * @param velocity {Number} The velocity of this animated frame * @param flickAxis {String} The axis on which to animate * @param startPosition {Number} The starting X/Y point to flick from * @protected */ _flickFrame: function (velocity, flickAxis, startPosition) { var sv = this, axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y, bounds = sv._getBounds(), // Localize cached values bounce = sv._cBounce, bounceRange = sv._cBounceRange, deceleration = sv._cDeceleration, frameDuration = sv._cFrameDuration, // Calculate newVelocity = velocity * deceleration, newPosition = startPosition - (frameDuration * newVelocity), // Some convinience conditions min = flickAxis === DIM_X ? bounds.minScrollX : bounds.minScrollY, max = flickAxis === DIM_X ? bounds.maxScrollX : bounds.maxScrollY, belowMin = (newPosition < min), belowMax = (newPosition < max), aboveMin = (newPosition > min), aboveMax = (newPosition > max), belowMinRange = (newPosition < (min - bounceRange)), withinMinRange = (belowMin && (newPosition > (min - bounceRange))), withinMaxRange = (aboveMax && (newPosition < (max + bounceRange))), aboveMaxRange = (newPosition > (max + bounceRange)), tooSlow; // If we're within the range but outside min/max, dampen the velocity if (withinMinRange || withinMaxRange) { newVelocity *= bounce; } // Is the velocity too slow to bother? tooSlow = (Math.abs(newVelocity).toFixed(4) < 0.015); // If the velocity is too slow or we're outside the range if (tooSlow || belowMinRange || aboveMaxRange) { // Cancel and delete sv._flickAnim if (sv._flickAnim) { sv._cancelFlick(); } // If we're inside the scroll area, just end if (aboveMin && belowMax) { sv._onTransEnd(); } // We're outside the scroll area, so we need to snap back else { sv._snapBack(); } } // Otherwise, animate to the next frame else { // @TODO: maybe use requestAnimationFrame instead sv._flickAnim = Y.later(frameDuration, sv, '_flickFrame', [newVelocity, flickAxis, newPosition]); sv.set(axisAttr, newPosition); } }, _cancelFlick: function () { var sv = this; if (sv._flickAnim) { // Cancel the flick (if it exists) sv._flickAnim.cancel(); // Also delete it, otherwise _onGestureMoveStart will think we're still flicking delete sv._flickAnim; } }, /** * Handle mousewheel events on the widget * * @method _mousewheel * @param e {Event.Facade} The mousewheel event facade * @private */ _mousewheel: function (e) { var sv = this, scrollY = sv.get(SCROLL_Y), bounds = sv._getBounds(), bb = sv._bb, scrollOffset = 10, // 10px isForward = (e.wheelDelta > 0), scrollToY = scrollY - ((isForward ? 1 : -1) * scrollOffset); scrollToY = _constrain(scrollToY, bounds.minScrollY, bounds.maxScrollY); // Because Mousewheel events fire off 'document', every ScrollView widget will react // to any mousewheel anywhere on the page. This check will ensure that the mouse is currently // over this specific ScrollView. Also, only allow mousewheel scrolling on Y-axis, // becuase otherwise the 'prevent' will block page scrolling. if (bb.contains(e.target) && sv._cAxis[DIM_Y]) { // Reset lastScrolledAmt sv.lastScrolledAmt = 0; // Jump to the new offset sv.set(SCROLL_Y, scrollToY); // if we have scrollbars plugin, update & set the flash timer on the scrollbar // @TODO: This probably shouldn't be in this module if (sv.scrollbars) { // @TODO: The scrollbars should handle this themselves sv.scrollbars._update(); sv.scrollbars.flash(); // or just this // sv.scrollbars._hostDimensionsChange(); } // Fire the 'scrollEnd' event sv._onTransEnd(); // prevent browser default behavior on mouse scroll e.preventDefault(); } }, /** * Checks to see the current scrollX/scrollY position beyond the min/max boundary * * @method _isOutOfBounds * @param x {Number} [optional] The X position to check * @param y {Number} [optional] The Y position to check * @return {boolen} Whether the current X/Y position is out of bounds (true) or not (false) * @private */ _isOutOfBounds: function (x, y) { var sv = this, svAxis = sv._cAxis, svAxisX = svAxis.x, svAxisY = svAxis.y, currentX = x || sv.get(SCROLL_X), currentY = y || sv.get(SCROLL_Y), bounds = sv._getBounds(), minX = bounds.minScrollX, minY = bounds.minScrollY, maxX = bounds.maxScrollX, maxY = bounds.maxScrollY; return (svAxisX && (currentX < minX || currentX > maxX)) || (svAxisY && (currentY < minY || currentY > maxY)); }, /** * Bounces back * @TODO: Should be more generalized and support both X and Y detection * * @method _snapBack * @private */ _snapBack: function () { var sv = this, currentX = sv.get(SCROLL_X), currentY = sv.get(SCROLL_Y), bounds = sv._getBounds(), minX = bounds.minScrollX, minY = bounds.minScrollY, maxX = bounds.maxScrollX, maxY = bounds.maxScrollY, newY = _constrain(currentY, minY, maxY), newX = _constrain(currentX, minX, maxX), duration = sv.get(SNAP_DURATION), easing = sv.get(SNAP_EASING); if (newX !== currentX) { sv.set(SCROLL_X, newX, {duration:duration, easing:easing}); } else if (newY !== currentY) { sv.set(SCROLL_Y, newY, {duration:duration, easing:easing}); } else { sv._onTransEnd(); } }, /** * After listener for changes to the scrollX or scrollY attribute * * @method _afterScrollChange * @param e {Event.Facade} The event facade * @protected */ _afterScrollChange: function (e) { if (e.src === ScrollView.UI_SRC) { return false; } var sv = this, duration = e.duration, easing = e.easing, val = e.newVal, scrollToArgs = []; // Set the scrolled value sv.lastScrolledAmt = sv.lastScrolledAmt + (e.newVal - e.prevVal); // Generate the array of args to pass to scrollTo() if (e.attrName === SCROLL_X) { scrollToArgs.push(val); scrollToArgs.push(sv.get(SCROLL_Y)); } else { scrollToArgs.push(sv.get(SCROLL_X)); scrollToArgs.push(val); } scrollToArgs.push(duration); scrollToArgs.push(easing); sv.scrollTo.apply(sv, scrollToArgs); }, /** * After listener for changes to the flick attribute * * @method _afterFlickChange * @param e {Event.Facade} The event facade * @protected */ _afterFlickChange: function (e) { this._bindFlick(e.newVal); }, /** * After listener for changes to the disabled attribute * * @method _afterDisabledChange * @param e {Event.Facade} The event facade * @protected */ _afterDisabledChange: function (e) { // Cache for performance - we check during move this._cDisabled = e.newVal; }, /** * After listener for the axis attribute * * @method _afterAxisChange * @param e {Event.Facade} The event facade * @protected */ _afterAxisChange: function (e) { this._cAxis = e.newVal; }, /** * After listener for changes to the drag attribute * * @method _afterDragChange * @param e {Event.Facade} The event facade * @protected */ _afterDragChange: function (e) { this._bindDrag(e.newVal); }, /** * After listener for the height or width attribute * * @method _afterDimChange * @param e {Event.Facade} The event facade * @protected */ _afterDimChange: function () { this._uiDimensionsChange(); }, /** * After listener for scrollEnd, for cleanup * * @method _afterScrollEnd * @param e {Event.Facade} The event facade * @protected */ _afterScrollEnd: function () { var sv = this; if (sv._flickAnim) { sv._cancelFlick(); } // Ideally this should be removed, but doing so causing some JS errors with fast swiping // because _gesture is being deleted after the previous one has been overwritten // delete sv._gesture; // TODO: Move to sv.prevGesture? }, /** * Setter for 'axis' attribute * * @method _axisSetter * @param val {Mixed} A string ('x', 'y', 'xy') to specify which axis/axes to allow scrolling on * @param name {String} The attribute name * @return {Object} An object to specify scrollability on the x & y axes * * @protected */ _axisSetter: function (val) { // Turn a string into an axis object if (Y.Lang.isString(val)) { return { x: val.match(/x/i) ? true : false, y: val.match(/y/i) ? true : false }; } }, /** * The scrollX, scrollY setter implementation * * @method _setScroll * @private * @param {Number} val * @param {String} dim * * @return {Number} The value */ _setScroll : function(val) { // Just ensure the widget is not disabled if (this._cDisabled) { val = Y.Attribute.INVALID_VALUE; } return val; }, /** * Setter for the scrollX attribute * * @method _setScrollX * @param val {Number} The new scrollX value * @return {Number} The normalized value * @protected */ _setScrollX: function(val) { return this._setScroll(val, DIM_X); }, /** * Setter for the scrollY ATTR * * @method _setScrollY * @param val {Number} The new scrollY value * @return {Number} The normalized value * @protected */ _setScrollY: function(val) { return this._setScroll(val, DIM_Y); } // End prototype properties }, { // Static properties /** * The identity of the widget. * * @property NAME * @type String * @default 'scrollview' * @readOnly * @protected * @static */ NAME: 'scrollview', /** * Static property used to define the default attribute configuration of * the Widget. * * @property ATTRS * @type {Object} * @protected * @static */ ATTRS: { /** * Specifies ability to scroll on x, y, or x and y axis/axes. * * @attribute axis * @type String */ axis: { setter: '_axisSetter', writeOnce: 'initOnly' }, /** * The current scroll position in the x-axis * * @attribute scrollX * @type Number * @default 0 */ scrollX: { value: 0, setter: '_setScrollX' }, /** * The current scroll position in the y-axis * * @attribute scrollY * @type Number * @default 0 */ scrollY: { value: 0, setter: '_setScrollY' }, /** * Drag coefficent for inertial scrolling. The closer to 1 this * value is, the less friction during scrolling. * * @attribute deceleration * @default 0.93 */ deceleration: { value: 0.93 }, /** * Drag coefficient for intertial scrolling at the upper * and lower boundaries of the scrollview. Set to 0 to * disable "rubber-banding". * * @attribute bounce * @type Number * @default 0.1 */ bounce: { value: 0.1 }, /** * The minimum distance and/or velocity which define a flick. Can be set to false, * to disable flick support (note: drag support is enabled/disabled separately) * * @attribute flick * @type Object * @default Object with properties minDistance = 10, minVelocity = 0.3. */ flick: { value: { minDistance: 10, minVelocity: 0.3 } }, /** * Enable/Disable dragging the ScrollView content (note: flick support is enabled/disabled separately) * @attribute drag * @type boolean * @default true */ drag: { value: true }, /** * The default duration to use when animating the bounce snap back. * * @attribute snapDuration * @type Number * @default 400 */ snapDuration: { value: 400 }, /** * The default easing to use when animating the bounce snap back. * * @attribute snapEasing * @type String * @default 'ease-out' */ snapEasing: { value: 'ease-out' }, /** * The default easing used when animating the flick * * @attribute easing * @type String * @default 'cubic-bezier(0, 0.1, 0, 1.0)' */ easing: { value: 'cubic-bezier(0, 0.1, 0, 1.0)' }, /** * The interval (ms) used when animating the flick for JS-timer animations * * @attribute frameDuration * @type Number * @default 15 */ frameDuration: { value: 15 }, /** * The default bounce distance in pixels * * @attribute bounceRange * @type Number * @default 150 */ bounceRange: { value: 150 } }, /** * List of class names used in the scrollview's DOM * * @property CLASS_NAMES * @type Object * @static */ CLASS_NAMES: CLASS_NAMES, /** * Flag used to source property changes initiated from the DOM * * @property UI_SRC * @type String * @static * @default 'ui' */ UI_SRC: UI, /** * Object map of style property names used to set transition properties. * Defaults to the vendor prefix established by the Transition module. * The configured property names are `_TRANSITION.DURATION` (e.g. "WebkitTransitionDuration") and * `_TRANSITION.PROPERTY (e.g. "WebkitTransitionProperty"). * * @property _TRANSITION * @private */ _TRANSITION: { DURATION: (vendorPrefix ? vendorPrefix + 'TransitionDuration' : 'transitionDuration'), PROPERTY: (vendorPrefix ? vendorPrefix + 'TransitionProperty' : 'transitionProperty') }, /** * The default bounce distance in pixels * * @property BOUNCE_RANGE * @type Number * @static * @default false * @deprecated (in 3.7.0) */ BOUNCE_RANGE: false, /** * The interval (ms) used when animating the flick * * @property FRAME_STEP * @type Number * @static * @default false * @deprecated (in 3.7.0) */ FRAME_STEP: false, /** * The default easing used when animating the flick * * @property EASING * @type String * @static * @default false * @deprecated (in 3.7.0) */ EASING: false, /** * The default easing to use when animating the bounce snap back. * * @property SNAP_EASING * @type String * @static * @default false * @deprecated (in 3.7.0) */ SNAP_EASING: false, /** * The default duration to use when animating the bounce snap back. * * @property SNAP_DURATION * @type Number * @static * @default false * @deprecated (in 3.7.0) */ SNAP_DURATION: false // End static properties }); }, '@VERSION@', {"requires": ["widget", "event-gestures", "event-mousewheel", "transition"], "skinnable": true});
example/src/index.js
mauriciojovel/redux-form-material-ui
import React from 'react' import ReactDOM from 'react-dom' import injectTapEventPlugin from 'react-tap-event-plugin' import { Provider } from 'react-redux' import { createStore, combineReducers } from 'redux' import { reducer as reduxFormReducer } from 'redux-form' import getMuiTheme from 'material-ui/styles/getMuiTheme' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import { Code, Markdown, Values } from 'redux-form-website-template' injectTapEventPlugin() const dest = document.getElementById('content') const reducer = combineReducers({ form: reduxFormReducer // mounted under "form" }) const store = (window.devToolsExtension ? window.devToolsExtension()(createStore) : createStore)(reducer) const showResults = values => new Promise(resolve => { setTimeout(() => { // simulate server latency window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`) resolve() }, 500) }) let render = () => { const Form = require('./Form').default const readme = require('./Example.md') const raw = require('!!raw!./Form') ReactDOM.render( <Provider store={store}> <MuiThemeProvider muiTheme={getMuiTheme()}> <div> <Markdown content={readme}/> <h2>Form</h2> <Form onSubmit={showResults}/> <Values form="example"/> <h2>Code</h2> <h4>Form.js</h4> <Code source={raw}/> </div> </MuiThemeProvider> </Provider>, dest ) } if (module.hot) { // Support hot reloading of components // and display an overlay for runtime errors const renderApp = render const renderError = (error) => { console.error('ERROR:', error) // eslint-disable-line no-console const RedBox = require('redbox-react') ReactDOM.render( <RedBox error={error} className="redbox"/>, dest ) } render = () => { try { renderApp() } catch (error) { renderError(error) } } const rerender = () => { setTimeout(render) } module.hot.accept('./Form', rerender) module.hot.accept('./Example.md', rerender) module.hot.accept('!!raw!./Form', rerender) } render()
src/__tests__/index.js
luzeduardo/crypto-simulator-form
import React from 'react'; import {shallow, mount, render} from 'enzyme'; import {expect} from 'chai'; import sinon from 'sinon'; import Simulador from '../index'; import {FormControl, Button} from 'react-bootstrap'; // Shallow Rendering // https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md describe('Shallow Rendering', () => { it('to have two FormControl', () => { const wrapper = shallow(<Simulador />); expect(wrapper.find('FormControl')).to.have.length(2); }); it('to have one Button', () => { const wrapper = shallow(<Simulador />); expect(wrapper.find('Button')).to.have.length(1); }); it('to have one textarea', () => { const wrapper = shallow(<Simulador />); expect(wrapper.find('FormControl').filter({componentClass: 'textarea'})).to.have.length(1); }); // it('simulates click events', () => { // const onSubmit = sinon.spy(); // const wrapper = shallow(<Simulador handleSubmit={onSubmit} />); // wrapper.find('Form').simulate('submit'); // expect(onSubmit.calledOnce).to.equal(true); // }); });
src/parser/rogue/subtlety/modules/features/ShadowBladesUptime.js
FaideWW/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import Analyzer from 'parser/core/Analyzer'; import Enemies from 'parser/shared/modules/Enemies'; class ShadowBladesUptime extends Analyzer { static dependencies = { enemies: Enemies, }; statistic() { const shadowBladesUptime = this.selectedCombatant.getBuffUptime(SPELLS.SHADOW_BLADES.id) / this.owner.fightDuration; return ( <StatisticBox icon={<SpellIcon id={SPELLS.SHADOW_BLADES.id} />} value={`${formatPercentage(shadowBladesUptime)} %`} label="Shadow Blades uptime" /> ); } statisticOrder = STATISTIC_ORDER.CORE(1); } export default ShadowBladesUptime;
packages/material-ui-icons/src/CommentRounded.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18zM17 14H7c-.55 0-1-.45-1-1s.45-1 1-1h10c.55 0 1 .45 1 1s-.45 1-1 1zm0-3H7c-.55 0-1-.45-1-1s.45-1 1-1h10c.55 0 1 .45 1 1s-.45 1-1 1zm0-3H7c-.55 0-1-.45-1-1s.45-1 1-1h10c.55 0 1 .45 1 1s-.45 1-1 1z" /></g></React.Fragment> , 'CommentRounded');
lms/static/js/vendor/candy_libs/libs.bundle.js
edxnercel/edx-platform
// This code was written by Tyler Akins and has been placed in the // public domain. It would be nice if you left this header intact. // Base64 code from Tyler Akins -- http://rumkin.com var Base64 = (function () { var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var obj = { /** * Encodes a string in base64 * @param {String} input The string to encode in base64. */ encode: function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; do { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } while (i < input.length); return output; }, /** * Decodes a base64 string. * @param {String} input The string to decode. */ decode: function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; // remove all characters that are not A-Z, a-z, 0-9, +, /, or = input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); do { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } while (i < input.length); return output; } }; return obj; })(); /* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ var MD5 = (function () { /* * Configurable variables. You may need to tweak these to be compatible with * the server-side, but the defaults work in most cases. */ var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ var safe_add = function (x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); }; /* * Bitwise rotate a 32-bit number to the left. */ var bit_rol = function (num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); }; /* * Convert a string to an array of little-endian words * If chrsz is ASCII, characters >255 have their hi-byte silently ignored. */ var str2binl = function (str) { var bin = []; var mask = (1 << chrsz) - 1; for(var i = 0; i < str.length * chrsz; i += chrsz) { bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32); } return bin; }; /* * Convert an array of little-endian words to a string */ var binl2str = function (bin) { var str = ""; var mask = (1 << chrsz) - 1; for(var i = 0; i < bin.length * 32; i += chrsz) { str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask); } return str; }; /* * Convert an array of little-endian words to a hex string. */ var binl2hex = function (binarray) { var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; var str = ""; for(var i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF); } return str; }; /* * Convert an array of little-endian words to a base-64 string */ var binl2b64 = function (binarray) { var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var str = ""; var triplet, j; for(var i = 0; i < binarray.length * 4; i += 3) { triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16) | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 ) | ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF); for(j = 0; j < 4; j++) { if(i * 8 + j * 6 > binarray.length * 32) { str += b64pad; } else { str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); } } } return str; }; /* * These functions implement the four basic operations the algorithm uses. */ var md5_cmn = function (q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q),safe_add(x, t)), s),b); }; var md5_ff = function (a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); }; var md5_gg = function (a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); }; var md5_hh = function (a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); }; var md5_ii = function (a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); }; /* * Calculate the MD5 of an array of little-endian words, and a bit length */ var core_md5 = function (x, len) { /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; var olda, oldb, oldc, oldd; for (var i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i+10], 17, -42063); b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; }; /* * Calculate the HMAC-MD5, of a key and some data */ var core_hmac_md5 = function (key, data) { var bkey = str2binl(key); if(bkey.length > 16) { bkey = core_md5(bkey, key.length * chrsz); } var ipad = new Array(16), opad = new Array(16); for(var i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz); return core_md5(opad.concat(hash), 512 + 128); }; var obj = { /* * These are the functions you'll usually want to call. * They take string arguments and return either hex or base-64 encoded * strings. */ hexdigest: function (s) { return binl2hex(core_md5(str2binl(s), s.length * chrsz)); }, b64digest: function (s) { return binl2b64(core_md5(str2binl(s), s.length * chrsz)); }, hash: function (s) { return binl2str(core_md5(str2binl(s), s.length * chrsz)); }, hmac_hexdigest: function (key, data) { return binl2hex(core_hmac_md5(key, data)); }, hmac_b64digest: function (key, data) { return binl2b64(core_hmac_md5(key, data)); }, hmac_hash: function (key, data) { return binl2str(core_hmac_md5(key, data)); }, /* * Perform a simple self-test to see if the VM is working */ test: function () { return MD5.hexdigest("abc") === "900150983cd24fb0d6963f7d28e17f72"; } }; return obj; })(); /* This program is distributed under the terms of the MIT license. Please see the LICENSE file for details. Copyright 2006-2008, OGG, LLC */ /* jslint configuration: */ /*global document, window, setTimeout, clearTimeout, console, XMLHttpRequest, ActiveXObject, Base64, MD5, Strophe, $build, $msg, $iq, $pres */ /** File: strophe.js * A JavaScript library for XMPP BOSH. * * This is the JavaScript version of the Strophe library. Since JavaScript * has no facilities for persistent TCP connections, this library uses * Bidirectional-streams Over Synchronous HTTP (BOSH) to emulate * a persistent, stateful, two-way connection to an XMPP server. More * information on BOSH can be found in XEP 124. */ /** PrivateFunction: Function.prototype.bind * Bind a function to an instance. * * This Function object extension method creates a bound method similar * to those in Python. This means that the 'this' object will point * to the instance you want. See * <a href='https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind'>MDC's bind() documentation</a> and * <a href='http://benjamin.smedbergs.us/blog/2007-01-03/bound-functions-and-function-imports-in-javascript/'>Bound Functions and Function Imports in JavaScript</a> * for a complete explanation. * * This extension already exists in some browsers (namely, Firefox 3), but * we provide it to support those that don't. * * Parameters: * (Object) obj - The object that will become 'this' in the bound function. * (Object) argN - An option argument that will be prepended to the * arguments given for the function call * * Returns: * The bound function. */ if (!Function.prototype.bind) { Function.prototype.bind = function (obj /*, arg1, arg2, ... */) { var func = this; var _slice = Array.prototype.slice; var _concat = Array.prototype.concat; var _args = _slice.call(arguments, 1); return function () { return func.apply(obj ? obj : this, _concat.call(_args, _slice.call(arguments, 0))); }; }; } /** PrivateFunction: Array.prototype.indexOf * Return the index of an object in an array. * * This function is not supplied by some JavaScript implementations, so * we provide it if it is missing. This code is from: * http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:indexOf * * Parameters: * (Object) elt - The object to look for. * (Integer) from - The index from which to start looking. (optional). * * Returns: * The index of elt in the array or -1 if not found. */ if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) { from += len; } for (; from < len; from++) { if (from in this && this[from] === elt) { return from; } } return -1; }; } /* All of the Strophe globals are defined in this special function below so * that references to the globals become closures. This will ensure that * on page reload, these references will still be available to callbacks * that are still executing. */ (function (callback) { var Strophe; /** Function: $build * Create a Strophe.Builder. * This is an alias for 'new Strophe.Builder(name, attrs)'. * * Parameters: * (String) name - The root element name. * (Object) attrs - The attributes for the root element in object notation. * * Returns: * A new Strophe.Builder object. */ function $build(name, attrs) { return new Strophe.Builder(name, attrs); } /** Function: $msg * Create a Strophe.Builder with a <message/> element as the root. * * Parmaeters: * (Object) attrs - The <message/> element attributes in object notation. * * Returns: * A new Strophe.Builder object. */ function $msg(attrs) { return new Strophe.Builder("message", attrs); } /** Function: $iq * Create a Strophe.Builder with an <iq/> element as the root. * * Parameters: * (Object) attrs - The <iq/> element attributes in object notation. * * Returns: * A new Strophe.Builder object. */ function $iq(attrs) { return new Strophe.Builder("iq", attrs); } /** Function: $pres * Create a Strophe.Builder with a <presence/> element as the root. * * Parameters: * (Object) attrs - The <presence/> element attributes in object notation. * * Returns: * A new Strophe.Builder object. */ function $pres(attrs) { return new Strophe.Builder("presence", attrs); } /** Class: Strophe * An object container for all Strophe library functions. * * This class is just a container for all the objects and constants * used in the library. It is not meant to be instantiated, but to * provide a namespace for library objects, constants, and functions. */ Strophe = { /** Constant: VERSION * The version of the Strophe library. Unreleased builds will have * a version of head-HASH where HASH is a partial revision. */ VERSION: "8d27954", /** Constants: XMPP Namespace Constants * Common namespace constants from the XMPP RFCs and XEPs. * * NS.HTTPBIND - HTTP BIND namespace from XEP 124. * NS.BOSH - BOSH namespace from XEP 206. * NS.CLIENT - Main XMPP client namespace. * NS.AUTH - Legacy authentication namespace. * NS.ROSTER - Roster operations namespace. * NS.PROFILE - Profile namespace. * NS.DISCO_INFO - Service discovery info namespace from XEP 30. * NS.DISCO_ITEMS - Service discovery items namespace from XEP 30. * NS.MUC - Multi-User Chat namespace from XEP 45. * NS.SASL - XMPP SASL namespace from RFC 3920. * NS.STREAM - XMPP Streams namespace from RFC 3920. * NS.BIND - XMPP Binding namespace from RFC 3920. * NS.SESSION - XMPP Session namespace from RFC 3920. */ NS: { HTTPBIND: "http://jabber.org/protocol/httpbind", BOSH: "urn:xmpp:xbosh", CLIENT: "jabber:client", AUTH: "jabber:iq:auth", ROSTER: "jabber:iq:roster", PROFILE: "jabber:iq:profile", DISCO_INFO: "http://jabber.org/protocol/disco#info", DISCO_ITEMS: "http://jabber.org/protocol/disco#items", MUC: "http://jabber.org/protocol/muc", SASL: "urn:ietf:params:xml:ns:xmpp-sasl", STREAM: "http://etherx.jabber.org/streams", BIND: "urn:ietf:params:xml:ns:xmpp-bind", SESSION: "urn:ietf:params:xml:ns:xmpp-session", VERSION: "jabber:iq:version", STANZAS: "urn:ietf:params:xml:ns:xmpp-stanzas" }, /** Function: addNamespace * This function is used to extend the current namespaces in * Strophe.NS. It takes a key and a value with the key being the * name of the new namespace, with its actual value. * For example: * Strophe.addNamespace('PUBSUB', "http://jabber.org/protocol/pubsub"); * * Parameters: * (String) name - The name under which the namespace will be * referenced under Strophe.NS * (String) value - The actual namespace. */ addNamespace: function (name, value) { Strophe.NS[name] = value; }, /** Constants: Connection Status Constants * Connection status constants for use by the connection handler * callback. * * Status.ERROR - An error has occurred * Status.CONNECTING - The connection is currently being made * Status.CONNFAIL - The connection attempt failed * Status.AUTHENTICATING - The connection is authenticating * Status.AUTHFAIL - The authentication attempt failed * Status.CONNECTED - The connection has succeeded * Status.DISCONNECTED - The connection has been terminated * Status.DISCONNECTING - The connection is currently being terminated * Status.ATTACHED - The connection has been attached */ Status: { ERROR: 0, CONNECTING: 1, CONNFAIL: 2, AUTHENTICATING: 3, AUTHFAIL: 4, CONNECTED: 5, DISCONNECTED: 6, DISCONNECTING: 7, ATTACHED: 8 }, /** Constants: Log Level Constants * Logging level indicators. * * LogLevel.DEBUG - Debug output * LogLevel.INFO - Informational output * LogLevel.WARN - Warnings * LogLevel.ERROR - Errors * LogLevel.FATAL - Fatal errors */ LogLevel: { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, FATAL: 4 }, /** PrivateConstants: DOM Element Type Constants * DOM element types. * * ElementType.NORMAL - Normal element. * ElementType.TEXT - Text data element. */ ElementType: { NORMAL: 1, TEXT: 3, CDATA: 4 }, /** PrivateConstants: Timeout Values * Timeout values for error states. These values are in seconds. * These should not be changed unless you know exactly what you are * doing. * * TIMEOUT - Timeout multiplier. A waiting request will be considered * failed after Math.floor(TIMEOUT * wait) seconds have elapsed. * This defaults to 1.1, and with default wait, 66 seconds. * SECONDARY_TIMEOUT - Secondary timeout multiplier. In cases where * Strophe can detect early failure, it will consider the request * failed if it doesn't return after * Math.floor(SECONDARY_TIMEOUT * wait) seconds have elapsed. * This defaults to 0.1, and with default wait, 6 seconds. */ TIMEOUT: 1.1, SECONDARY_TIMEOUT: 0.1, /** Function: forEachChild * Map a function over some or all child elements of a given element. * * This is a small convenience function for mapping a function over * some or all of the children of an element. If elemName is null, all * children will be passed to the function, otherwise only children * whose tag names match elemName will be passed. * * Parameters: * (XMLElement) elem - The element to operate on. * (String) elemName - The child element tag name filter. * (Function) func - The function to apply to each child. This * function should take a single argument, a DOM element. */ forEachChild: function (elem, elemName, func) { var i, childNode; for (i = 0; i < elem.childNodes.length; i++) { childNode = elem.childNodes[i]; if (childNode.nodeType == Strophe.ElementType.NORMAL && (!elemName || this.isTagEqual(childNode, elemName))) { func(childNode); } } }, /** Function: isTagEqual * Compare an element's tag name with a string. * * This function is case insensitive. * * Parameters: * (XMLElement) el - A DOM element. * (String) name - The element name. * * Returns: * true if the element's tag name matches _el_, and false * otherwise. */ isTagEqual: function (el, name) { return el.tagName.toLowerCase() == name.toLowerCase(); }, /** PrivateVariable: _xmlGenerator * _Private_ variable that caches a DOM document to * generate elements. */ _xmlGenerator: null, /** PrivateFunction: _makeGenerator * _Private_ function that creates a dummy XML DOM document to serve as * an element and text node generator. */ _makeGenerator: function () { var doc; if (document.implementation.createDocument === undefined) { doc = this._getIEXmlDom(); doc.appendChild(doc.createElement('strophe')); } else { doc = document.implementation .createDocument('jabber:client', 'strophe', null); } return doc; }, /** Function: xmlGenerator * Get the DOM document to generate elements. * * Returns: * The currently used DOM document. */ xmlGenerator: function () { if (!Strophe._xmlGenerator) { Strophe._xmlGenerator = Strophe._makeGenerator(); } return Strophe._xmlGenerator; }, /** PrivateFunction: _getIEXmlDom * Gets IE xml doc object * * Returns: * A Microsoft XML DOM Object * See Also: * http://msdn.microsoft.com/en-us/library/ms757837%28VS.85%29.aspx */ _getIEXmlDom : function() { var doc = null; var docStrings = [ "Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM" ]; for (var d = 0; d < docStrings.length; d++) { if (doc === null) { try { doc = new ActiveXObject(docStrings[d]); } catch (e) { doc = null; } } else { break; } } return doc; }, /** Function: xmlElement * Create an XML DOM element. * * This function creates an XML DOM element correctly across all * implementations. Note that these are not HTML DOM elements, which * aren't appropriate for XMPP stanzas. * * Parameters: * (String) name - The name for the element. * (Array|Object) attrs - An optional array or object containing * key/value pairs to use as element attributes. The object should * be in the format {'key': 'value'} or {key: 'value'}. The array * should have the format [['key1', 'value1'], ['key2', 'value2']]. * (String) text - The text child data for the element. * * Returns: * A new XML DOM element. */ xmlElement: function (name) { if (!name) { return null; } var node = Strophe.xmlGenerator().createElement(name); // FIXME: this should throw errors if args are the wrong type or // there are more than two optional args var a, i, k; for (a = 1; a < arguments.length; a++) { if (!arguments[a]) { continue; } if (typeof(arguments[a]) == "string" || typeof(arguments[a]) == "number") { node.appendChild(Strophe.xmlTextNode(arguments[a])); } else if (typeof(arguments[a]) == "object" && typeof(arguments[a].sort) == "function") { for (i = 0; i < arguments[a].length; i++) { if (typeof(arguments[a][i]) == "object" && typeof(arguments[a][i].sort) == "function") { node.setAttribute(arguments[a][i][0], arguments[a][i][1]); } } } else if (typeof(arguments[a]) == "object") { for (k in arguments[a]) { if (arguments[a].hasOwnProperty(k)) { node.setAttribute(k, arguments[a][k]); } } } } return node; }, /* Function: xmlescape * Excapes invalid xml characters. * * Parameters: * (String) text - text to escape. * * Returns: * Escaped text. */ xmlescape: function(text) { text = text.replace(/\&/g, "&amp;"); text = text.replace(/</g, "&lt;"); text = text.replace(/>/g, "&gt;"); text = text.replace(/'/g, "&apos;"); text = text.replace(/"/g, "&quot;"); return text; }, /** Function: xmlTextNode * Creates an XML DOM text node. * * Provides a cross implementation version of document.createTextNode. * * Parameters: * (String) text - The content of the text node. * * Returns: * A new XML DOM text node. */ xmlTextNode: function (text) { //ensure text is escaped text = Strophe.xmlescape(text); return Strophe.xmlGenerator().createTextNode(text); }, /** Function: getText * Get the concatenation of all text children of an element. * * Parameters: * (XMLElement) elem - A DOM element. * * Returns: * A String with the concatenated text of all text element children. */ getText: function (elem) { if (!elem) { return null; } var str = ""; if (elem.childNodes.length === 0 && elem.nodeType == Strophe.ElementType.TEXT) { str += elem.nodeValue; } for (var i = 0; i < elem.childNodes.length; i++) { if (elem.childNodes[i].nodeType == Strophe.ElementType.TEXT) { str += elem.childNodes[i].nodeValue; } } return str; }, /** Function: copyElement * Copy an XML DOM element. * * This function copies a DOM element and all its descendants and returns * the new copy. * * Parameters: * (XMLElement) elem - A DOM element. * * Returns: * A new, copied DOM element tree. */ copyElement: function (elem) { var i, el; if (elem.nodeType == Strophe.ElementType.NORMAL) { el = Strophe.xmlElement(elem.tagName); for (i = 0; i < elem.attributes.length; i++) { el.setAttribute(elem.attributes[i].nodeName.toLowerCase(), elem.attributes[i].value); } for (i = 0; i < elem.childNodes.length; i++) { el.appendChild(Strophe.copyElement(elem.childNodes[i])); } } else if (elem.nodeType == Strophe.ElementType.TEXT) { el = Strophe.xmlGenerator().createTextNode(elem.nodeValue); } return el; }, /** Function: escapeNode * Escape the node part (also called local part) of a JID. * * Parameters: * (String) node - A node (or local part). * * Returns: * An escaped node (or local part). */ escapeNode: function (node) { return node.replace(/^\s+|\s+$/g, '') .replace(/\\/g, "\\5c") .replace(/ /g, "\\20") .replace(/\"/g, "\\22") .replace(/\&/g, "\\26") .replace(/\'/g, "\\27") .replace(/\//g, "\\2f") .replace(/:/g, "\\3a") .replace(/</g, "\\3c") .replace(/>/g, "\\3e") .replace(/@/g, "\\40"); }, /** Function: unescapeNode * Unescape a node part (also called local part) of a JID. * * Parameters: * (String) node - A node (or local part). * * Returns: * An unescaped node (or local part). */ unescapeNode: function (node) { return node.replace(/\\20/g, " ") .replace(/\\22/g, '"') .replace(/\\26/g, "&") .replace(/\\27/g, "'") .replace(/\\2f/g, "/") .replace(/\\3a/g, ":") .replace(/\\3c/g, "<") .replace(/\\3e/g, ">") .replace(/\\40/g, "@") .replace(/\\5c/g, "\\"); }, /** Function: getNodeFromJid * Get the node portion of a JID String. * * Parameters: * (String) jid - A JID. * * Returns: * A String containing the node. */ getNodeFromJid: function (jid) { if (jid.indexOf("@") < 0) { return null; } return jid.split("@")[0]; }, /** Function: getDomainFromJid * Get the domain portion of a JID String. * * Parameters: * (String) jid - A JID. * * Returns: * A String containing the domain. */ getDomainFromJid: function (jid) { var bare = Strophe.getBareJidFromJid(jid); if (bare.indexOf("@") < 0) { return bare; } else { var parts = bare.split("@"); parts.splice(0, 1); return parts.join('@'); } }, /** Function: getResourceFromJid * Get the resource portion of a JID String. * * Parameters: * (String) jid - A JID. * * Returns: * A String containing the resource. */ getResourceFromJid: function (jid) { var s = jid.split("/"); if (s.length < 2) { return null; } s.splice(0, 1); return s.join('/'); }, /** Function: getBareJidFromJid * Get the bare JID from a JID String. * * Parameters: * (String) jid - A JID. * * Returns: * A String containing the bare JID. */ getBareJidFromJid: function (jid) { return jid ? jid.split("/")[0] : null; }, /** Function: log * User overrideable logging function. * * This function is called whenever the Strophe library calls any * of the logging functions. The default implementation of this * function does nothing. If client code wishes to handle the logging * messages, it should override this with * > Strophe.log = function (level, msg) { * > (user code here) * > }; * * Please note that data sent and received over the wire is logged * via Strophe.Connection.rawInput() and Strophe.Connection.rawOutput(). * * The different levels and their meanings are * * DEBUG - Messages useful for debugging purposes. * INFO - Informational messages. This is mostly information like * 'disconnect was called' or 'SASL auth succeeded'. * WARN - Warnings about potential problems. This is mostly used * to report transient connection errors like request timeouts. * ERROR - Some error occurred. * FATAL - A non-recoverable fatal error occurred. * * Parameters: * (Integer) level - The log level of the log message. This will * be one of the values in Strophe.LogLevel. * (String) msg - The log message. */ log: function (level, msg) { return; }, /** Function: debug * Log a message at the Strophe.LogLevel.DEBUG level. * * Parameters: * (String) msg - The log message. */ debug: function(msg) { this.log(this.LogLevel.DEBUG, msg); }, /** Function: info * Log a message at the Strophe.LogLevel.INFO level. * * Parameters: * (String) msg - The log message. */ info: function (msg) { this.log(this.LogLevel.INFO, msg); }, /** Function: warn * Log a message at the Strophe.LogLevel.WARN level. * * Parameters: * (String) msg - The log message. */ warn: function (msg) { this.log(this.LogLevel.WARN, msg); }, /** Function: error * Log a message at the Strophe.LogLevel.ERROR level. * * Parameters: * (String) msg - The log message. */ error: function (msg) { this.log(this.LogLevel.ERROR, msg); }, /** Function: fatal * Log a message at the Strophe.LogLevel.FATAL level. * * Parameters: * (String) msg - The log message. */ fatal: function (msg) { this.log(this.LogLevel.FATAL, msg); }, /** Function: serialize * Render a DOM element and all descendants to a String. * * Parameters: * (XMLElement) elem - A DOM element. * * Returns: * The serialized element tree as a String. */ serialize: function (elem) { var result; if (!elem) { return null; } if (typeof(elem.tree) === "function") { elem = elem.tree(); } var nodeName = elem.nodeName; var i, child; if (elem.getAttribute("_realname")) { nodeName = elem.getAttribute("_realname"); } result = "<" + nodeName; for (i = 0; i < elem.attributes.length; i++) { if(elem.attributes[i].nodeName != "_realname") { result += " " + elem.attributes[i].nodeName.toLowerCase() + "='" + elem.attributes[i].value .replace(/&/g, "&amp;") .replace(/\'/g, "&apos;") .replace(/</g, "&lt;") + "'"; } } if (elem.childNodes.length > 0) { result += ">"; for (i = 0; i < elem.childNodes.length; i++) { child = elem.childNodes[i]; switch( child.nodeType ){ case Strophe.ElementType.NORMAL: // normal element, so recurse result += Strophe.serialize(child); break; case Strophe.ElementType.TEXT: // text element to escape values result += child.nodeValue; break; case Strophe.ElementType.CDATA: // cdata section so don't escape values result += "<![CDATA["+child.nodeValue+"]]>"; } } result += "</" + nodeName + ">"; } else { result += "/>"; } return result; }, /** PrivateVariable: _requestId * _Private_ variable that keeps track of the request ids for * connections. */ _requestId: 0, /** PrivateVariable: Strophe.connectionPlugins * _Private_ variable Used to store plugin names that need * initialization on Strophe.Connection construction. */ _connectionPlugins: {}, /** Function: addConnectionPlugin * Extends the Strophe.Connection object with the given plugin. * * Parameters: * (String) name - The name of the extension. * (Object) ptype - The plugin's prototype. */ addConnectionPlugin: function (name, ptype) { Strophe._connectionPlugins[name] = ptype; } }; /** Class: Strophe.Builder * XML DOM builder. * * This object provides an interface similar to JQuery but for building * DOM element easily and rapidly. All the functions except for toString() * and tree() return the object, so calls can be chained. Here's an * example using the $iq() builder helper. * > $iq({to: 'you', from: 'me', type: 'get', id: '1'}) * > .c('query', {xmlns: 'strophe:example'}) * > .c('example') * > .toString() * The above generates this XML fragment * > <iq to='you' from='me' type='get' id='1'> * > <query xmlns='strophe:example'> * > <example/> * > </query> * > </iq> * The corresponding DOM manipulations to get a similar fragment would be * a lot more tedious and probably involve several helper variables. * * Since adding children makes new operations operate on the child, up() * is provided to traverse up the tree. To add two children, do * > builder.c('child1', ...).up().c('child2', ...) * The next operation on the Builder will be relative to the second child. */ /** Constructor: Strophe.Builder * Create a Strophe.Builder object. * * The attributes should be passed in object notation. For example * > var b = new Builder('message', {to: 'you', from: 'me'}); * or * > var b = new Builder('messsage', {'xml:lang': 'en'}); * * Parameters: * (String) name - The name of the root element. * (Object) attrs - The attributes for the root element in object notation. * * Returns: * A new Strophe.Builder. */ Strophe.Builder = function (name, attrs) { // Set correct namespace for jabber:client elements if (name == "presence" || name == "message" || name == "iq") { if (attrs && !attrs.xmlns) { attrs.xmlns = Strophe.NS.CLIENT; } else if (!attrs) { attrs = {xmlns: Strophe.NS.CLIENT}; } } // Holds the tree being built. this.nodeTree = Strophe.xmlElement(name, attrs); // Points to the current operation node. this.node = this.nodeTree; }; Strophe.Builder.prototype = { /** Function: tree * Return the DOM tree. * * This function returns the current DOM tree as an element object. This * is suitable for passing to functions like Strophe.Connection.send(). * * Returns: * The DOM tree as a element object. */ tree: function () { return this.nodeTree; }, /** Function: toString * Serialize the DOM tree to a String. * * This function returns a string serialization of the current DOM * tree. It is often used internally to pass data to a * Strophe.Request object. * * Returns: * The serialized DOM tree in a String. */ toString: function () { return Strophe.serialize(this.nodeTree); }, /** Function: up * Make the current parent element the new current element. * * This function is often used after c() to traverse back up the tree. * For example, to add two children to the same element * > builder.c('child1', {}).up().c('child2', {}); * * Returns: * The Stophe.Builder object. */ up: function () { this.node = this.node.parentNode; return this; }, /** Function: attrs * Add or modify attributes of the current element. * * The attributes should be passed in object notation. This function * does not move the current element pointer. * * Parameters: * (Object) moreattrs - The attributes to add/modify in object notation. * * Returns: * The Strophe.Builder object. */ attrs: function (moreattrs) { for (var k in moreattrs) { if (moreattrs.hasOwnProperty(k)) { this.node.setAttribute(k, moreattrs[k]); } } return this; }, /** Function: c * Add a child to the current element and make it the new current * element. * * This function moves the current element pointer to the child, * unless text is provided. If you need to add another child, it * is necessary to use up() to go back to the parent in the tree. * * Parameters: * (String) name - The name of the child. * (Object) attrs - The attributes of the child in object notation. * (String) text - The text to add to the child. * * Returns: * The Strophe.Builder object. */ c: function (name, attrs, text) { var child = Strophe.xmlElement(name, attrs, text); this.node.appendChild(child); if (!text) { this.node = child; } return this; }, /** Function: cnode * Add a child to the current element and make it the new current * element. * * This function is the same as c() except that instead of using a * name and an attributes object to create the child it uses an * existing DOM element object. * * Parameters: * (XMLElement) elem - A DOM element. * * Returns: * The Strophe.Builder object. */ cnode: function (elem) { var xmlGen = Strophe.xmlGenerator(); try { var impNode = (xmlGen.importNode !== undefined); } catch (e) { var impNode = false; } var newElem = impNode ? xmlGen.importNode(elem, true) : Strophe.copyElement(elem); this.node.appendChild(newElem); this.node = newElem; return this; }, /** Function: t * Add a child text element. * * This *does not* make the child the new current element since there * are no children of text elements. * * Parameters: * (String) text - The text data to append to the current element. * * Returns: * The Strophe.Builder object. */ t: function (text) { var child = Strophe.xmlTextNode(text); this.node.appendChild(child); return this; } }; /** PrivateClass: Strophe.Handler * _Private_ helper class for managing stanza handlers. * * A Strophe.Handler encapsulates a user provided callback function to be * executed when matching stanzas are received by the connection. * Handlers can be either one-off or persistant depending on their * return value. Returning true will cause a Handler to remain active, and * returning false will remove the Handler. * * Users will not use Strophe.Handler objects directly, but instead they * will use Strophe.Connection.addHandler() and * Strophe.Connection.deleteHandler(). */ /** PrivateConstructor: Strophe.Handler * Create and initialize a new Strophe.Handler. * * Parameters: * (Function) handler - A function to be executed when the handler is run. * (String) ns - The namespace to match. * (String) name - The element name to match. * (String) type - The element type to match. * (String) id - The element id attribute to match. * (String) from - The element from attribute to match. * (Object) options - Handler options * * Returns: * A new Strophe.Handler object. */ Strophe.Handler = function (handler, ns, name, type, id, from, options) { this.handler = handler; this.ns = ns; this.name = name; this.type = type; this.id = id; this.options = options || {matchbare: false}; // default matchBare to false if undefined if (!this.options.matchBare) { this.options.matchBare = false; } if (this.options.matchBare) { this.from = from ? Strophe.getBareJidFromJid(from) : null; } else { this.from = from; } // whether the handler is a user handler or a system handler this.user = true; }; Strophe.Handler.prototype = { /** PrivateFunction: isMatch * Tests if a stanza matches the Strophe.Handler. * * Parameters: * (XMLElement) elem - The XML element to test. * * Returns: * true if the stanza matches and false otherwise. */ isMatch: function (elem) { var nsMatch; var from = null; if (this.options.matchBare) { from = Strophe.getBareJidFromJid(elem.getAttribute('from')); } else { from = elem.getAttribute('from'); } nsMatch = false; if (!this.ns) { nsMatch = true; } else { var that = this; Strophe.forEachChild(elem, null, function (elem) { if (elem.getAttribute("xmlns") == that.ns) { nsMatch = true; } }); nsMatch = nsMatch || elem.getAttribute("xmlns") == this.ns; } if (nsMatch && (!this.name || Strophe.isTagEqual(elem, this.name)) && (!this.type || elem.getAttribute("type") == this.type) && (!this.id || elem.getAttribute("id") == this.id) && (!this.from || from == this.from)) { return true; } return false; }, /** PrivateFunction: run * Run the callback on a matching stanza. * * Parameters: * (XMLElement) elem - The DOM element that triggered the * Strophe.Handler. * * Returns: * A boolean indicating if the handler should remain active. */ run: function (elem) { var result = null; try { result = this.handler(elem); } catch (e) { if (e.sourceURL) { Strophe.fatal("error: " + this.handler + " " + e.sourceURL + ":" + e.line + " - " + e.name + ": " + e.message); } else if (e.fileName) { if (typeof(console) != "undefined") { console.trace(); console.error(this.handler, " - error - ", e, e.message); } Strophe.fatal("error: " + this.handler + " " + e.fileName + ":" + e.lineNumber + " - " + e.name + ": " + e.message); } else { Strophe.fatal("error: " + this.handler); } throw e; } return result; }, /** PrivateFunction: toString * Get a String representation of the Strophe.Handler object. * * Returns: * A String. */ toString: function () { return "{Handler: " + this.handler + "(" + this.name + "," + this.id + "," + this.ns + ")}"; } }; /** PrivateClass: Strophe.TimedHandler * _Private_ helper class for managing timed handlers. * * A Strophe.TimedHandler encapsulates a user provided callback that * should be called after a certain period of time or at regular * intervals. The return value of the callback determines whether the * Strophe.TimedHandler will continue to fire. * * Users will not use Strophe.TimedHandler objects directly, but instead * they will use Strophe.Connection.addTimedHandler() and * Strophe.Connection.deleteTimedHandler(). */ /** PrivateConstructor: Strophe.TimedHandler * Create and initialize a new Strophe.TimedHandler object. * * Parameters: * (Integer) period - The number of milliseconds to wait before the * handler is called. * (Function) handler - The callback to run when the handler fires. This * function should take no arguments. * * Returns: * A new Strophe.TimedHandler object. */ Strophe.TimedHandler = function (period, handler) { this.period = period; this.handler = handler; this.lastCalled = new Date().getTime(); this.user = true; }; Strophe.TimedHandler.prototype = { /** PrivateFunction: run * Run the callback for the Strophe.TimedHandler. * * Returns: * true if the Strophe.TimedHandler should be called again, and false * otherwise. */ run: function () { this.lastCalled = new Date().getTime(); return this.handler(); }, /** PrivateFunction: reset * Reset the last called time for the Strophe.TimedHandler. */ reset: function () { this.lastCalled = new Date().getTime(); }, /** PrivateFunction: toString * Get a string representation of the Strophe.TimedHandler object. * * Returns: * The string representation. */ toString: function () { return "{TimedHandler: " + this.handler + "(" + this.period +")}"; } }; /** PrivateClass: Strophe.Request * _Private_ helper class that provides a cross implementation abstraction * for a BOSH related XMLHttpRequest. * * The Strophe.Request class is used internally to encapsulate BOSH request * information. It is not meant to be used from user's code. */ /** PrivateConstructor: Strophe.Request * Create and initialize a new Strophe.Request object. * * Parameters: * (XMLElement) elem - The XML data to be sent in the request. * (Function) func - The function that will be called when the * XMLHttpRequest readyState changes. * (Integer) rid - The BOSH rid attribute associated with this request. * (Integer) sends - The number of times this same request has been * sent. */ Strophe.Request = function (elem, func, rid, sends) { this.id = ++Strophe._requestId; this.xmlData = elem; this.data = Strophe.serialize(elem); // save original function in case we need to make a new request // from this one. this.origFunc = func; this.func = func; this.rid = rid; this.date = NaN; this.sends = sends || 0; this.abort = false; this.dead = null; this.age = function () { if (!this.date) { return 0; } var now = new Date(); return (now - this.date) / 1000; }; this.timeDead = function () { if (!this.dead) { return 0; } var now = new Date(); return (now - this.dead) / 1000; }; this.xhr = this._newXHR(); }; Strophe.Request.prototype = { /** PrivateFunction: getResponse * Get a response from the underlying XMLHttpRequest. * * This function attempts to get a response from the request and checks * for errors. * * Throws: * "parsererror" - A parser error occured. * * Returns: * The DOM element tree of the response. */ getResponse: function () { var node = null; if (this.xhr.responseXML && this.xhr.responseXML.documentElement) { node = this.xhr.responseXML.documentElement; if (node.tagName == "parsererror") { Strophe.error("invalid response received"); Strophe.error("responseText: " + this.xhr.responseText); Strophe.error("responseXML: " + Strophe.serialize(this.xhr.responseXML)); throw "parsererror"; } } else if (this.xhr.responseText) { Strophe.error("invalid response received"); Strophe.error("responseText: " + this.xhr.responseText); Strophe.error("responseXML: " + Strophe.serialize(this.xhr.responseXML)); } return node; }, /** PrivateFunction: _newXHR * _Private_ helper function to create XMLHttpRequests. * * This function creates XMLHttpRequests across all implementations. * * Returns: * A new XMLHttpRequest. */ _newXHR: function () { var xhr = null; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); if (xhr.overrideMimeType) { xhr.overrideMimeType("text/xml"); } } else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } // use Function.bind() to prepend ourselves as an argument xhr.onreadystatechange = this.func.bind(null, this); return xhr; } }; /** Class: Strophe.Connection * XMPP Connection manager. * * Thie class is the main part of Strophe. It manages a BOSH connection * to an XMPP server and dispatches events to the user callbacks as * data arrives. It supports SASL PLAIN, SASL DIGEST-MD5, and legacy * authentication. * * After creating a Strophe.Connection object, the user will typically * call connect() with a user supplied callback to handle connection level * events like authentication failure, disconnection, or connection * complete. * * The user will also have several event handlers defined by using * addHandler() and addTimedHandler(). These will allow the user code to * respond to interesting stanzas or do something periodically with the * connection. These handlers will be active once authentication is * finished. * * To send data to the connection, use send(). */ /** Constructor: Strophe.Connection * Create and initialize a Strophe.Connection object. * * Parameters: * (String) service - The BOSH service URL. * * Returns: * A new Strophe.Connection object. */ Strophe.Connection = function (service) { /* The path to the httpbind service. */ this.service = service; /* The connected JID. */ this.jid = ""; /* request id for body tags */ this.rid = Math.floor(Math.random() * 4294967295); /* The current session ID. */ this.sid = null; this.streamId = null; /* stream:features */ this.features = null; // SASL this.do_session = false; this.do_bind = false; // handler lists this.timedHandlers = []; this.handlers = []; this.removeTimeds = []; this.removeHandlers = []; this.addTimeds = []; this.addHandlers = []; this._idleTimeout = null; this._disconnectTimeout = null; this.authenticated = false; this.disconnecting = false; this.connected = false; this.errors = 0; this.paused = false; // default BOSH values this.hold = 1; this.wait = 60; this.window = 5; this._data = []; this._requests = []; this._uniqueId = Math.round(Math.random() * 10000); this._sasl_success_handler = null; this._sasl_failure_handler = null; this._sasl_challenge_handler = null; // setup onIdle callback every 1/10th of a second this._idleTimeout = setTimeout(this._onIdle.bind(this), 100); // initialize plugins for (var k in Strophe._connectionPlugins) { if (Strophe._connectionPlugins.hasOwnProperty(k)) { var ptype = Strophe._connectionPlugins[k]; // jslint complaints about the below line, but this is fine var F = function () {}; F.prototype = ptype; this[k] = new F(); this[k].init(this); } } }; Strophe.Connection.prototype = { /** Function: reset * Reset the connection. * * This function should be called after a connection is disconnected * before that connection is reused. */ reset: function () { this.rid = Math.floor(Math.random() * 4294967295); this.sid = null; this.streamId = null; // SASL this.do_session = false; this.do_bind = false; // handler lists this.timedHandlers = []; this.handlers = []; this.removeTimeds = []; this.removeHandlers = []; this.addTimeds = []; this.addHandlers = []; this.authenticated = false; this.disconnecting = false; this.connected = false; this.errors = 0; this._requests = []; this._uniqueId = Math.round(Math.random()*10000); }, /** Function: pause * Pause the request manager. * * This will prevent Strophe from sending any more requests to the * server. This is very useful for temporarily pausing while a lot * of send() calls are happening quickly. This causes Strophe to * send the data in a single request, saving many request trips. */ pause: function () { this.paused = true; }, /** Function: resume * Resume the request manager. * * This resumes after pause() has been called. */ resume: function () { this.paused = false; }, /** Function: getUniqueId * Generate a unique ID for use in <iq/> elements. * * All <iq/> stanzas are required to have unique id attributes. This * function makes creating these easy. Each connection instance has * a counter which starts from zero, and the value of this counter * plus a colon followed by the suffix becomes the unique id. If no * suffix is supplied, the counter is used as the unique id. * * Suffixes are used to make debugging easier when reading the stream * data, and their use is recommended. The counter resets to 0 for * every new connection for the same reason. For connections to the * same server that authenticate the same way, all the ids should be * the same, which makes it easy to see changes. This is useful for * automated testing as well. * * Parameters: * (String) suffix - A optional suffix to append to the id. * * Returns: * A unique string to be used for the id attribute. */ getUniqueId: function (suffix) { if (typeof(suffix) == "string" || typeof(suffix) == "number") { return ++this._uniqueId + ":" + suffix; } else { return ++this._uniqueId + ""; } }, /** Function: connect * Starts the connection process. * * As the connection process proceeds, the user supplied callback will * be triggered multiple times with status updates. The callback * should take two arguments - the status code and the error condition. * * The status code will be one of the values in the Strophe.Status * constants. The error condition will be one of the conditions * defined in RFC 3920 or the condition 'strophe-parsererror'. * * Please see XEP 124 for a more detailed explanation of the optional * parameters below. * * Parameters: * (String) jid - The user's JID. This may be a bare JID, * or a full JID. If a node is not supplied, SASL ANONYMOUS * authentication will be attempted. * (String) pass - The user's password. * (Function) callback - The connect callback function. * (Integer) wait - The optional HTTPBIND wait value. This is the * time the server will wait before returning an empty result for * a request. The default setting of 60 seconds is recommended. * Other settings will require tweaks to the Strophe.TIMEOUT value. * (Integer) hold - The optional HTTPBIND hold value. This is the * number of connections the server will hold at one time. This * should almost always be set to 1 (the default). */ connect: function (jid, pass, callback, wait, hold) { this.jid = jid; this.pass = pass; this.connect_callback = callback; this.disconnecting = false; this.connected = false; this.authenticated = false; this.errors = 0; this.wait = wait || this.wait; this.hold = hold || this.hold; // parse jid for domain and resource this.domain = Strophe.getDomainFromJid(this.jid); // build the body tag var body = this._buildBody().attrs({ to: this.domain, "xml:lang": "en", wait: this.wait, hold: this.hold, content: "text/xml; charset=utf-8", ver: "1.6", "xmpp:version": "1.0", "xmlns:xmpp": Strophe.NS.BOSH }); this._changeConnectStatus(Strophe.Status.CONNECTING, null); this._requests.push( new Strophe.Request(body.tree(), this._onRequestStateChange.bind( this, this._connect_cb.bind(this)), body.tree().getAttribute("rid"))); this._throttledRequestHandler(); }, /** Function: attach * Attach to an already created and authenticated BOSH session. * * This function is provided to allow Strophe to attach to BOSH * sessions which have been created externally, perhaps by a Web * application. This is often used to support auto-login type features * without putting user credentials into the page. * * Parameters: * (String) jid - The full JID that is bound by the session. * (String) sid - The SID of the BOSH session. * (String) rid - The current RID of the BOSH session. This RID * will be used by the next request. * (Function) callback The connect callback function. * (Integer) wait - The optional HTTPBIND wait value. This is the * time the server will wait before returning an empty result for * a request. The default setting of 60 seconds is recommended. * Other settings will require tweaks to the Strophe.TIMEOUT value. * (Integer) hold - The optional HTTPBIND hold value. This is the * number of connections the server will hold at one time. This * should almost always be set to 1 (the default). * (Integer) wind - The optional HTTBIND window value. This is the * allowed range of request ids that are valid. The default is 5. */ attach: function (jid, sid, rid, callback, wait, hold, wind) { this.jid = jid; this.sid = sid; this.rid = rid; this.connect_callback = callback; this.domain = Strophe.getDomainFromJid(this.jid); this.authenticated = true; this.connected = true; this.wait = wait || this.wait; this.hold = hold || this.hold; this.window = wind || this.window; this._changeConnectStatus(Strophe.Status.ATTACHED, null); }, /** Function: xmlInput * User overrideable function that receives XML data coming into the * connection. * * The default function does nothing. User code can override this with * > Strophe.Connection.xmlInput = function (elem) { * > (user code) * > }; * * Parameters: * (XMLElement) elem - The XML data received by the connection. */ xmlInput: function (elem) { return; }, /** Function: xmlOutput * User overrideable function that receives XML data sent to the * connection. * * The default function does nothing. User code can override this with * > Strophe.Connection.xmlOutput = function (elem) { * > (user code) * > }; * * Parameters: * (XMLElement) elem - The XMLdata sent by the connection. */ xmlOutput: function (elem) { return; }, /** Function: rawInput * User overrideable function that receives raw data coming into the * connection. * * The default function does nothing. User code can override this with * > Strophe.Connection.rawInput = function (data) { * > (user code) * > }; * * Parameters: * (String) data - The data received by the connection. */ rawInput: function (data) { return; }, /** Function: rawOutput * User overrideable function that receives raw data sent to the * connection. * * The default function does nothing. User code can override this with * > Strophe.Connection.rawOutput = function (data) { * > (user code) * > }; * * Parameters: * (String) data - The data sent by the connection. */ rawOutput: function (data) { return; }, /** Function: send * Send a stanza. * * This function is called to push data onto the send queue to * go out over the wire. Whenever a request is sent to the BOSH * server, all pending data is sent and the queue is flushed. * * Parameters: * (XMLElement | * [XMLElement] | * Strophe.Builder) elem - The stanza to send. */ send: function (elem) { if (elem === null) { return ; } if (typeof(elem.sort) === "function") { for (var i = 0; i < elem.length; i++) { this._queueData(elem[i]); } } else if (typeof(elem.tree) === "function") { this._queueData(elem.tree()); } else { this._queueData(elem); } this._throttledRequestHandler(); clearTimeout(this._idleTimeout); this._idleTimeout = setTimeout(this._onIdle.bind(this), 100); }, /** Function: flush * Immediately send any pending outgoing data. * * Normally send() queues outgoing data until the next idle period * (100ms), which optimizes network use in the common cases when * several send()s are called in succession. flush() can be used to * immediately send all pending data. */ flush: function () { // cancel the pending idle period and run the idle function // immediately clearTimeout(this._idleTimeout); this._onIdle(); }, /** Function: sendIQ * Helper function to send IQ stanzas. * * Parameters: * (XMLElement) elem - The stanza to send. * (Function) callback - The callback function for a successful request. * (Function) errback - The callback function for a failed or timed * out request. On timeout, the stanza will be null. * (Integer) timeout - The time specified in milliseconds for a * timeout to occur. * * Returns: * The id used to send the IQ. */ sendIQ: function(elem, callback, errback, timeout) { var timeoutHandler = null; var that = this; if (typeof(elem.tree) === "function") { elem = elem.tree(); } var id = elem.getAttribute('id'); // inject id if not found if (!id) { id = this.getUniqueId("sendIQ"); elem.setAttribute("id", id); } var handler = this.addHandler(function (stanza) { // remove timeout handler if there is one if (timeoutHandler) { that.deleteTimedHandler(timeoutHandler); } var iqtype = stanza.getAttribute('type'); if (iqtype == 'result') { if (callback) { callback(stanza); } } else if (iqtype == 'error') { if (errback) { errback(stanza); } } else { throw { name: "StropheError", message: "Got bad IQ type of " + iqtype }; } }, null, 'iq', null, id); // if timeout specified, setup timeout handler. if (timeout) { timeoutHandler = this.addTimedHandler(timeout, function () { // get rid of normal handler that.deleteHandler(handler); // call errback on timeout with null stanza if (errback) { errback(null); } return false; }); } this.send(elem); return id; }, /** PrivateFunction: _queueData * Queue outgoing data for later sending. Also ensures that the data * is a DOMElement. */ _queueData: function (element) { if (element === null || !element.tagName || !element.childNodes) { throw { name: "StropheError", message: "Cannot queue non-DOMElement." }; } this._data.push(element); }, /** PrivateFunction: _sendRestart * Send an xmpp:restart stanza. */ _sendRestart: function () { this._data.push("restart"); this._throttledRequestHandler(); clearTimeout(this._idleTimeout); this._idleTimeout = setTimeout(this._onIdle.bind(this), 100); }, /** Function: addTimedHandler * Add a timed handler to the connection. * * This function adds a timed handler. The provided handler will * be called every period milliseconds until it returns false, * the connection is terminated, or the handler is removed. Handlers * that wish to continue being invoked should return true. * * Because of method binding it is necessary to save the result of * this function if you wish to remove a handler with * deleteTimedHandler(). * * Note that user handlers are not active until authentication is * successful. * * Parameters: * (Integer) period - The period of the handler. * (Function) handler - The callback function. * * Returns: * A reference to the handler that can be used to remove it. */ addTimedHandler: function (period, handler) { var thand = new Strophe.TimedHandler(period, handler); this.addTimeds.push(thand); return thand; }, /** Function: deleteTimedHandler * Delete a timed handler for a connection. * * This function removes a timed handler from the connection. The * handRef parameter is *not* the function passed to addTimedHandler(), * but is the reference returned from addTimedHandler(). * * Parameters: * (Strophe.TimedHandler) handRef - The handler reference. */ deleteTimedHandler: function (handRef) { // this must be done in the Idle loop so that we don't change // the handlers during iteration this.removeTimeds.push(handRef); }, /** Function: addHandler * Add a stanza handler for the connection. * * This function adds a stanza handler to the connection. The * handler callback will be called for any stanza that matches * the parameters. Note that if multiple parameters are supplied, * they must all match for the handler to be invoked. * * The handler will receive the stanza that triggered it as its argument. * The handler should return true if it is to be invoked again; * returning false will remove the handler after it returns. * * As a convenience, the ns parameters applies to the top level element * and also any of its immediate children. This is primarily to make * matching /iq/query elements easy. * * The options argument contains handler matching flags that affect how * matches are determined. Currently the only flag is matchBare (a * boolean). When matchBare is true, the from parameter and the from * attribute on the stanza will be matched as bare JIDs instead of * full JIDs. To use this, pass {matchBare: true} as the value of * options. The default value for matchBare is false. * * The return value should be saved if you wish to remove the handler * with deleteHandler(). * * Parameters: * (Function) handler - The user callback. * (String) ns - The namespace to match. * (String) name - The stanza name to match. * (String) type - The stanza type attribute to match. * (String) id - The stanza id attribute to match. * (String) from - The stanza from attribute to match. * (String) options - The handler options * * Returns: * A reference to the handler that can be used to remove it. */ addHandler: function (handler, ns, name, type, id, from, options) { var hand = new Strophe.Handler(handler, ns, name, type, id, from, options); this.addHandlers.push(hand); return hand; }, /** Function: deleteHandler * Delete a stanza handler for a connection. * * This function removes a stanza handler from the connection. The * handRef parameter is *not* the function passed to addHandler(), * but is the reference returned from addHandler(). * * Parameters: * (Strophe.Handler) handRef - The handler reference. */ deleteHandler: function (handRef) { // this must be done in the Idle loop so that we don't change // the handlers during iteration this.removeHandlers.push(handRef); }, /** Function: disconnect * Start the graceful disconnection process. * * This function starts the disconnection process. This process starts * by sending unavailable presence and sending BOSH body of type * terminate. A timeout handler makes sure that disconnection happens * even if the BOSH server does not respond. * * The user supplied connection callback will be notified of the * progress as this process happens. * * Parameters: * (String) reason - The reason the disconnect is occuring. */ disconnect: function (reason) { this._changeConnectStatus(Strophe.Status.DISCONNECTING, reason); Strophe.info("Disconnect was called because: " + reason); if (this.connected) { // setup timeout handler this._disconnectTimeout = this._addSysTimedHandler( 3000, this._onDisconnectTimeout.bind(this)); this._sendTerminate(); } }, /** PrivateFunction: _changeConnectStatus * _Private_ helper function that makes sure plugins and the user's * callback are notified of connection status changes. * * Parameters: * (Integer) status - the new connection status, one of the values * in Strophe.Status * (String) condition - the error condition or null */ _changeConnectStatus: function (status, condition) { // notify all plugins listening for status changes for (var k in Strophe._connectionPlugins) { if (Strophe._connectionPlugins.hasOwnProperty(k)) { var plugin = this[k]; if (plugin.statusChanged) { try { plugin.statusChanged(status, condition); } catch (err) { Strophe.error("" + k + " plugin caused an exception " + "changing status: " + err); } } } } // notify the user's callback if (this.connect_callback) { try { this.connect_callback(status, condition); } catch (e) { Strophe.error("User connection callback caused an " + "exception: " + e); } } }, /** PrivateFunction: _buildBody * _Private_ helper function to generate the <body/> wrapper for BOSH. * * Returns: * A Strophe.Builder with a <body/> element. */ _buildBody: function () { var bodyWrap = $build('body', { rid: this.rid++, xmlns: Strophe.NS.HTTPBIND }); if (this.sid !== null) { bodyWrap.attrs({sid: this.sid}); } return bodyWrap; }, /** PrivateFunction: _removeRequest * _Private_ function to remove a request from the queue. * * Parameters: * (Strophe.Request) req - The request to remove. */ _removeRequest: function (req) { Strophe.debug("removing request"); var i; for (i = this._requests.length - 1; i >= 0; i--) { if (req == this._requests[i]) { this._requests.splice(i, 1); } } // IE6 fails on setting to null, so set to empty function req.xhr.onreadystatechange = function () {}; this._throttledRequestHandler(); }, /** PrivateFunction: _restartRequest * _Private_ function to restart a request that is presumed dead. * * Parameters: * (Integer) i - The index of the request in the queue. */ _restartRequest: function (i) { var req = this._requests[i]; if (req.dead === null) { req.dead = new Date(); } this._processRequest(i); }, /** PrivateFunction: _processRequest * _Private_ function to process a request in the queue. * * This function takes requests off the queue and sends them and * restarts dead requests. * * Parameters: * (Integer) i - The index of the request in the queue. */ _processRequest: function (i) { var req = this._requests[i]; var reqStatus = -1; try { if (req.xhr.readyState == 4) { reqStatus = req.xhr.status; } } catch (e) { Strophe.error("caught an error in _requests[" + i + "], reqStatus: " + reqStatus); } if (typeof(reqStatus) == "undefined") { reqStatus = -1; } // make sure we limit the number of retries if (req.sends > 5) { this._onDisconnectTimeout(); return; } var time_elapsed = req.age(); var primaryTimeout = (!isNaN(time_elapsed) && time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait)); var secondaryTimeout = (req.dead !== null && req.timeDead() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait)); var requestCompletedWithServerError = (req.xhr.readyState == 4 && (reqStatus < 1 || reqStatus >= 500)); if (primaryTimeout || secondaryTimeout || requestCompletedWithServerError) { if (secondaryTimeout) { Strophe.error("Request " + this._requests[i].id + " timed out (secondary), restarting"); } req.abort = true; req.xhr.abort(); // setting to null fails on IE6, so set to empty function req.xhr.onreadystatechange = function () {}; this._requests[i] = new Strophe.Request(req.xmlData, req.origFunc, req.rid, req.sends); req = this._requests[i]; } if (req.xhr.readyState === 0) { Strophe.debug("request id " + req.id + "." + req.sends + " posting"); try { var async = !('sync' in this && this.sync === true); req.xhr.open("POST", this.service, async); } catch (e2) { Strophe.error("XHR open failed."); if (!this.connected) { this._changeConnectStatus(Strophe.Status.CONNFAIL, "bad-service"); } this.disconnect(); return; } // Fires the XHR request -- may be invoked immediately // or on a gradually expanding retry window for reconnects var sendFunc = function () { req.date = new Date(); req.xhr.send(req.data); }; // Implement progressive backoff for reconnects -- // First retry (send == 1) should also be instantaneous if (req.sends > 1) { // Using a cube of the retry number creates a nicely // expanding retry window var backoff = Math.min(Math.floor(Strophe.TIMEOUT * this.wait), Math.pow(req.sends, 3)) * 1000; setTimeout(sendFunc, backoff); } else { sendFunc(); } req.sends++; if (this.xmlOutput !== Strophe.Connection.prototype.xmlOutput) { this.xmlOutput(req.xmlData); } if (this.rawOutput !== Strophe.Connection.prototype.rawOutput) { this.rawOutput(req.data); } } else { Strophe.debug("_processRequest: " + (i === 0 ? "first" : "second") + " request has readyState of " + req.xhr.readyState); } }, /** PrivateFunction: _throttledRequestHandler * _Private_ function to throttle requests to the connection window. * * This function makes sure we don't send requests so fast that the * request ids overflow the connection window in the case that one * request died. */ _throttledRequestHandler: function () { if (!this._requests) { Strophe.debug("_throttledRequestHandler called with " + "undefined requests"); } else { Strophe.debug("_throttledRequestHandler called with " + this._requests.length + " requests"); } if (!this._requests || this._requests.length === 0) { return; } if (this._requests.length > 0) { this._processRequest(0); } if (this._requests.length > 1 && Math.abs(this._requests[0].rid - this._requests[1].rid) < this.window) { this._processRequest(1); } }, /** PrivateFunction: _onRequestStateChange * _Private_ handler for Strophe.Request state changes. * * This function is called when the XMLHttpRequest readyState changes. * It contains a lot of error handling logic for the many ways that * requests can fail, and calls the request callback when requests * succeed. * * Parameters: * (Function) func - The handler for the request. * (Strophe.Request) req - The request that is changing readyState. */ _onRequestStateChange: function (func, req) { Strophe.debug("request id " + req.id + "." + req.sends + " state changed to " + req.xhr.readyState); if (req.abort) { req.abort = false; return; } // request complete var reqStatus; if (req.xhr.readyState == 4) { reqStatus = 0; try { reqStatus = req.xhr.status; } catch (e) { // ignore errors from undefined status attribute. works // around a browser bug } if (typeof(reqStatus) == "undefined") { reqStatus = 0; } if (this.disconnecting) { if (reqStatus >= 400) { this._hitError(reqStatus); return; } } var reqIs0 = (this._requests[0] == req); var reqIs1 = (this._requests[1] == req); if ((reqStatus > 0 && reqStatus < 500) || req.sends > 5) { // remove from internal queue this._removeRequest(req); Strophe.debug("request id " + req.id + " should now be removed"); } // request succeeded if (reqStatus == 200) { // if request 1 finished, or request 0 finished and request // 1 is over Strophe.SECONDARY_TIMEOUT seconds old, we need to // restart the other - both will be in the first spot, as the // completed request has been removed from the queue already if (reqIs1 || (reqIs0 && this._requests.length > 0 && this._requests[0].age() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait))) { this._restartRequest(0); } // call handler Strophe.debug("request id " + req.id + "." + req.sends + " got 200"); func(req); this.errors = 0; } else { Strophe.error("request id " + req.id + "." + req.sends + " error " + reqStatus + " happened"); if (reqStatus === 0 || (reqStatus >= 400 && reqStatus < 600) || reqStatus >= 12000) { this._hitError(reqStatus); if (reqStatus >= 400 && reqStatus < 500) { this._changeConnectStatus(Strophe.Status.DISCONNECTING, null); this._doDisconnect(); } } } if (!((reqStatus > 0 && reqStatus < 500) || req.sends > 5)) { this._throttledRequestHandler(); } } }, /** PrivateFunction: _hitError * _Private_ function to handle the error count. * * Requests are resent automatically until their error count reaches * 5. Each time an error is encountered, this function is called to * increment the count and disconnect if the count is too high. * * Parameters: * (Integer) reqStatus - The request status. */ _hitError: function (reqStatus) { this.errors++; Strophe.warn("request errored, status: " + reqStatus + ", number of errors: " + this.errors); if (this.errors > 4) { this._onDisconnectTimeout(); } }, /** PrivateFunction: _doDisconnect * _Private_ function to disconnect. * * This is the last piece of the disconnection logic. This resets the * connection and alerts the user's connection callback. */ _doDisconnect: function () { Strophe.info("_doDisconnect was called"); this.authenticated = false; this.disconnecting = false; this.sid = null; this.streamId = null; this.rid = Math.floor(Math.random() * 4294967295); // tell the parent we disconnected if (this.connected) { this._changeConnectStatus(Strophe.Status.DISCONNECTED, null); this.connected = false; } // delete handlers this.handlers = []; this.timedHandlers = []; this.removeTimeds = []; this.removeHandlers = []; this.addTimeds = []; this.addHandlers = []; }, /** PrivateFunction: _dataRecv * _Private_ handler to processes incoming data from the the connection. * * Except for _connect_cb handling the initial connection request, * this function handles the incoming data for all requests. This * function also fires stanza handlers that match each incoming * stanza. * * Parameters: * (Strophe.Request) req - The request that has data ready. */ _dataRecv: function (req) { try { var elem = req.getResponse(); } catch (e) { if (e != "parsererror") { throw e; } this.disconnect("strophe-parsererror"); } if (elem === null) { return; } if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) { this.xmlInput(elem); } if (this.rawInput !== Strophe.Connection.prototype.rawInput) { this.rawInput(Strophe.serialize(elem)); } // remove handlers scheduled for deletion var i, hand; while (this.removeHandlers.length > 0) { hand = this.removeHandlers.pop(); i = this.handlers.indexOf(hand); if (i >= 0) { this.handlers.splice(i, 1); } } // add handlers scheduled for addition while (this.addHandlers.length > 0) { this.handlers.push(this.addHandlers.pop()); } // handle graceful disconnect if (this.disconnecting && this._requests.length === 0) { this.deleteTimedHandler(this._disconnectTimeout); this._disconnectTimeout = null; this._doDisconnect(); return; } var typ = elem.getAttribute("type"); var cond, conflict; if (typ !== null && typ == "terminate") { // Don't process stanzas that come in after disconnect if (this.disconnecting) { return; } // an error occurred cond = elem.getAttribute("condition"); conflict = elem.getElementsByTagName("conflict"); if (cond !== null) { if (cond == "remote-stream-error" && conflict.length > 0) { cond = "conflict"; } this._changeConnectStatus(Strophe.Status.CONNFAIL, cond); } else { this._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown"); } this.disconnect(); return; } // send each incoming stanza through the handler chain var that = this; Strophe.forEachChild(elem, null, function (child) { var i, newList; // process handlers newList = that.handlers; that.handlers = []; for (i = 0; i < newList.length; i++) { var hand = newList[i]; // encapsulate 'handler.run' not to lose the whole handler list if // one of the handlers throws an exception try { if (hand.isMatch(child) && (that.authenticated || !hand.user)) { if (hand.run(child)) { that.handlers.push(hand); } } else { that.handlers.push(hand); } } catch(e) { //if the handler throws an exception, we consider it as false } } }); }, /** PrivateFunction: _sendTerminate * _Private_ function to send initial disconnect sequence. * * This is the first step in a graceful disconnect. It sends * the BOSH server a terminate body and includes an unavailable * presence if authentication has completed. */ _sendTerminate: function () { Strophe.info("_sendTerminate was called"); var body = this._buildBody().attrs({type: "terminate"}); if (this.authenticated) { body.c('presence', { xmlns: Strophe.NS.CLIENT, type: 'unavailable' }); } this.disconnecting = true; var req = new Strophe.Request(body.tree(), this._onRequestStateChange.bind( this, this._dataRecv.bind(this)), body.tree().getAttribute("rid")); this._requests.push(req); this._throttledRequestHandler(); }, /** PrivateFunction: _connect_cb * _Private_ handler for initial connection request. * * This handler is used to process the initial connection request * response from the BOSH server. It is used to set up authentication * handlers and start the authentication process. * * SASL authentication will be attempted if available, otherwise * the code will fall back to legacy authentication. * * Parameters: * (Strophe.Request) req - The current request. */ _connect_cb: function (req) { Strophe.info("_connect_cb was called"); this.connected = true; var bodyWrap = req.getResponse(); if (!bodyWrap) { return; } if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) { this.xmlInput(bodyWrap); } if (this.rawInput !== Strophe.Connection.prototype.rawInput) { this.rawInput(Strophe.serialize(bodyWrap)); } var typ = bodyWrap.getAttribute("type"); var cond, conflict; if (typ !== null && typ == "terminate") { // an error occurred cond = bodyWrap.getAttribute("condition"); conflict = bodyWrap.getElementsByTagName("conflict"); if (cond !== null) { if (cond == "remote-stream-error" && conflict.length > 0) { cond = "conflict"; } this._changeConnectStatus(Strophe.Status.CONNFAIL, cond); } else { this._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown"); } return; } // check to make sure we don't overwrite these if _connect_cb is // called multiple times in the case of missing stream:features if (!this.sid) { this.sid = bodyWrap.getAttribute("sid"); } if (!this.stream_id) { this.stream_id = bodyWrap.getAttribute("authid"); } var wind = bodyWrap.getAttribute('requests'); if (wind) { this.window = parseInt(wind, 10); } var hold = bodyWrap.getAttribute('hold'); if (hold) { this.hold = parseInt(hold, 10); } var wait = bodyWrap.getAttribute('wait'); if (wait) { this.wait = parseInt(wait, 10); } var do_sasl_plain = false; var do_sasl_digest_md5 = false; var do_sasl_anonymous = false; var mechanisms = bodyWrap.getElementsByTagName("mechanism"); var i, mech, auth_str, hashed_auth_str; if (mechanisms.length > 0) { for (i = 0; i < mechanisms.length; i++) { mech = Strophe.getText(mechanisms[i]); if (mech == 'DIGEST-MD5') { do_sasl_digest_md5 = true; } else if (mech == 'PLAIN') { do_sasl_plain = true; } else if (mech == 'ANONYMOUS') { do_sasl_anonymous = true; } } } else { // we didn't get stream:features yet, so we need wait for it // by sending a blank poll request var body = this._buildBody(); this._requests.push( new Strophe.Request(body.tree(), this._onRequestStateChange.bind( this, this._connect_cb.bind(this)), body.tree().getAttribute("rid"))); this._throttledRequestHandler(); return; } if (Strophe.getNodeFromJid(this.jid) === null && do_sasl_anonymous) { this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null); this._sasl_success_handler = this._addSysHandler( this._sasl_success_cb.bind(this), null, "success", null, null); this._sasl_failure_handler = this._addSysHandler( this._sasl_failure_cb.bind(this), null, "failure", null, null); this.send($build("auth", { xmlns: Strophe.NS.SASL, mechanism: "ANONYMOUS" }).tree()); } else if (Strophe.getNodeFromJid(this.jid) === null) { // we don't have a node, which is required for non-anonymous // client connections this._changeConnectStatus(Strophe.Status.CONNFAIL, 'x-strophe-bad-non-anon-jid'); this.disconnect(); } else if (do_sasl_digest_md5) { this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null); this._sasl_challenge_handler = this._addSysHandler( this._sasl_challenge1_cb.bind(this), null, "challenge", null, null); this._sasl_failure_handler = this._addSysHandler( this._sasl_failure_cb.bind(this), null, "failure", null, null); this.send($build("auth", { xmlns: Strophe.NS.SASL, mechanism: "DIGEST-MD5" }).tree()); } else if (do_sasl_plain) { // Build the plain auth string (barejid null // username null password) and base 64 encoded. auth_str = unescape(encodeURIComponent(Strophe.getBareJidFromJid(this.jid))); auth_str = auth_str + "\u0000"; auth_str = auth_str + unescape(encodeURIComponent(Strophe.getNodeFromJid(this.jid))); auth_str = auth_str + "\u0000"; auth_str = auth_str + this.pass; this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null); this._sasl_success_handler = this._addSysHandler( this._sasl_success_cb.bind(this), null, "success", null, null); this._sasl_failure_handler = this._addSysHandler( this._sasl_failure_cb.bind(this), null, "failure", null, null); hashed_auth_str = Base64.encode(auth_str); this.send($build("auth", { xmlns: Strophe.NS.SASL, mechanism: "PLAIN" }).t(hashed_auth_str).tree()); } else { this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null); this._addSysHandler(this._auth1_cb.bind(this), null, null, null, "_auth_1"); this.send($iq({ type: "get", to: this.domain, id: "_auth_1" }).c("query", { xmlns: Strophe.NS.AUTH }).c("username", {}).t(Strophe.getNodeFromJid(this.jid)).tree()); } }, /** PrivateFunction: _sasl_challenge1_cb * _Private_ handler for DIGEST-MD5 SASL authentication. * * Parameters: * (XMLElement) elem - The challenge stanza. * * Returns: * false to remove the handler. */ _sasl_challenge1_cb: function (elem) { var attribMatch = /([a-z]+)=("[^"]+"|[^,"]+)(?:,|$)/; var challenge = Base64.decode(Strophe.getText(elem)); var cnonce = MD5.hexdigest("" + (Math.random() * 1234567890)); var realm = ""; var host = null; var nonce = ""; var qop = ""; var matches; // remove unneeded handlers this.deleteHandler(this._sasl_failure_handler); while (challenge.match(attribMatch)) { matches = challenge.match(attribMatch); challenge = challenge.replace(matches[0], ""); matches[2] = matches[2].replace(/^"(.+)"$/, "$1"); switch (matches[1]) { case "realm": realm = matches[2]; break; case "nonce": nonce = matches[2]; break; case "qop": qop = matches[2]; break; case "host": host = matches[2]; break; } } var digest_uri = "xmpp/" + this.domain; if (host !== null) { digest_uri = digest_uri + "/" + host; } var A1 = MD5.hash(unescape(encodeURIComponent(Strophe.getNodeFromJid(this.jid))) + ":" + realm + ":" + this.pass) + ":" + nonce + ":" + cnonce; var A2 = 'AUTHENTICATE:' + digest_uri; var responseText = ""; responseText += 'username=' + this._quote(unescape(encodeURIComponent(Strophe.getNodeFromJid(this.jid)))) + ','; responseText += 'realm=' + this._quote(realm) + ','; responseText += 'nonce=' + this._quote(nonce) + ','; responseText += 'cnonce=' + this._quote(cnonce) + ','; responseText += 'nc="00000001",'; responseText += 'qop="auth",'; responseText += 'digest-uri=' + this._quote(digest_uri) + ','; responseText += 'response=' + this._quote( MD5.hexdigest(MD5.hexdigest(A1) + ":" + nonce + ":00000001:" + cnonce + ":auth:" + MD5.hexdigest(A2))) + ','; responseText += 'charset="utf-8"'; this._sasl_challenge_handler = this._addSysHandler( this._sasl_challenge2_cb.bind(this), null, "challenge", null, null); this._sasl_success_handler = this._addSysHandler( this._sasl_success_cb.bind(this), null, "success", null, null); this._sasl_failure_handler = this._addSysHandler( this._sasl_failure_cb.bind(this), null, "failure", null, null); this.send($build('response', { xmlns: Strophe.NS.SASL }).t(Base64.encode(responseText)).tree()); return false; }, /** PrivateFunction: _quote * _Private_ utility function to backslash escape and quote strings. * * Parameters: * (String) str - The string to be quoted. * * Returns: * quoted string */ _quote: function (str) { return '"' + str.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"'; //" end string workaround for emacs }, /** PrivateFunction: _sasl_challenge2_cb * _Private_ handler for second step of DIGEST-MD5 SASL authentication. * * Parameters: * (XMLElement) elem - The challenge stanza. * * Returns: * false to remove the handler. */ _sasl_challenge2_cb: function (elem) { // remove unneeded handlers this.deleteHandler(this._sasl_success_handler); this.deleteHandler(this._sasl_failure_handler); this._sasl_success_handler = this._addSysHandler( this._sasl_success_cb.bind(this), null, "success", null, null); this._sasl_failure_handler = this._addSysHandler( this._sasl_failure_cb.bind(this), null, "failure", null, null); this.send($build('response', {xmlns: Strophe.NS.SASL}).tree()); return false; }, /** PrivateFunction: _auth1_cb * _Private_ handler for legacy authentication. * * This handler is called in response to the initial <iq type='get'/> * for legacy authentication. It builds an authentication <iq/> and * sends it, creating a handler (calling back to _auth2_cb()) to * handle the result * * Parameters: * (XMLElement) elem - The stanza that triggered the callback. * * Returns: * false to remove the handler. */ _auth1_cb: function (elem) { // build plaintext auth iq var iq = $iq({type: "set", id: "_auth_2"}) .c('query', {xmlns: Strophe.NS.AUTH}) .c('username', {}).t(Strophe.getNodeFromJid(this.jid)) .up() .c('password').t(this.pass); if (!Strophe.getResourceFromJid(this.jid)) { // since the user has not supplied a resource, we pick // a default one here. unlike other auth methods, the server // cannot do this for us. this.jid = Strophe.getBareJidFromJid(this.jid) + '/strophe'; } iq.up().c('resource', {}).t(Strophe.getResourceFromJid(this.jid)); this._addSysHandler(this._auth2_cb.bind(this), null, null, null, "_auth_2"); this.send(iq.tree()); return false; }, /** PrivateFunction: _sasl_success_cb * _Private_ handler for succesful SASL authentication. * * Parameters: * (XMLElement) elem - The matching stanza. * * Returns: * false to remove the handler. */ _sasl_success_cb: function (elem) { Strophe.info("SASL authentication succeeded."); // remove old handlers this.deleteHandler(this._sasl_failure_handler); this._sasl_failure_handler = null; if (this._sasl_challenge_handler) { this.deleteHandler(this._sasl_challenge_handler); this._sasl_challenge_handler = null; } this._addSysHandler(this._sasl_auth1_cb.bind(this), null, "stream:features", null, null); // we must send an xmpp:restart now this._sendRestart(); return false; }, /** PrivateFunction: _sasl_auth1_cb * _Private_ handler to start stream binding. * * Parameters: * (XMLElement) elem - The matching stanza. * * Returns: * false to remove the handler. */ _sasl_auth1_cb: function (elem) { // save stream:features for future usage this.features = elem; var i, child; for (i = 0; i < elem.childNodes.length; i++) { child = elem.childNodes[i]; if (child.nodeName == 'bind') { this.do_bind = true; } if (child.nodeName == 'session') { this.do_session = true; } } if (!this.do_bind) { this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); return false; } else { this._addSysHandler(this._sasl_bind_cb.bind(this), null, null, null, "_bind_auth_2"); var resource = Strophe.getResourceFromJid(this.jid); if (resource) { this.send($iq({type: "set", id: "_bind_auth_2"}) .c('bind', {xmlns: Strophe.NS.BIND}) .c('resource', {}).t(resource).tree()); } else { this.send($iq({type: "set", id: "_bind_auth_2"}) .c('bind', {xmlns: Strophe.NS.BIND}) .tree()); } } return false; }, /** PrivateFunction: _sasl_bind_cb * _Private_ handler for binding result and session start. * * Parameters: * (XMLElement) elem - The matching stanza. * * Returns: * false to remove the handler. */ _sasl_bind_cb: function (elem) { if (elem.getAttribute("type") == "error") { Strophe.info("SASL binding failed."); this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); return false; } // TODO - need to grab errors var bind = elem.getElementsByTagName("bind"); var jidNode; if (bind.length > 0) { // Grab jid jidNode = bind[0].getElementsByTagName("jid"); if (jidNode.length > 0) { this.jid = Strophe.getText(jidNode[0]); if (this.do_session) { this._addSysHandler(this._sasl_session_cb.bind(this), null, null, null, "_session_auth_2"); this.send($iq({type: "set", id: "_session_auth_2"}) .c('session', {xmlns: Strophe.NS.SESSION}) .tree()); } else { this.authenticated = true; this._changeConnectStatus(Strophe.Status.CONNECTED, null); } } } else { Strophe.info("SASL binding failed."); this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); return false; } }, /** PrivateFunction: _sasl_session_cb * _Private_ handler to finish successful SASL connection. * * This sets Connection.authenticated to true on success, which * starts the processing of user handlers. * * Parameters: * (XMLElement) elem - The matching stanza. * * Returns: * false to remove the handler. */ _sasl_session_cb: function (elem) { if (elem.getAttribute("type") == "result") { this.authenticated = true; this._changeConnectStatus(Strophe.Status.CONNECTED, null); } else if (elem.getAttribute("type") == "error") { Strophe.info("Session creation failed."); this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); return false; } return false; }, /** PrivateFunction: _sasl_failure_cb * _Private_ handler for SASL authentication failure. * * Parameters: * (XMLElement) elem - The matching stanza. * * Returns: * false to remove the handler. */ _sasl_failure_cb: function (elem) { // delete unneeded handlers if (this._sasl_success_handler) { this.deleteHandler(this._sasl_success_handler); this._sasl_success_handler = null; } if (this._sasl_challenge_handler) { this.deleteHandler(this._sasl_challenge_handler); this._sasl_challenge_handler = null; } this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); return false; }, /** PrivateFunction: _auth2_cb * _Private_ handler to finish legacy authentication. * * This handler is called when the result from the jabber:iq:auth * <iq/> stanza is returned. * * Parameters: * (XMLElement) elem - The stanza that triggered the callback. * * Returns: * false to remove the handler. */ _auth2_cb: function (elem) { if (elem.getAttribute("type") == "result") { this.authenticated = true; this._changeConnectStatus(Strophe.Status.CONNECTED, null); } else if (elem.getAttribute("type") == "error") { this._changeConnectStatus(Strophe.Status.AUTHFAIL, null); this.disconnect(); } return false; }, /** PrivateFunction: _addSysTimedHandler * _Private_ function to add a system level timed handler. * * This function is used to add a Strophe.TimedHandler for the * library code. System timed handlers are allowed to run before * authentication is complete. * * Parameters: * (Integer) period - The period of the handler. * (Function) handler - The callback function. */ _addSysTimedHandler: function (period, handler) { var thand = new Strophe.TimedHandler(period, handler); thand.user = false; this.addTimeds.push(thand); return thand; }, /** PrivateFunction: _addSysHandler * _Private_ function to add a system level stanza handler. * * This function is used to add a Strophe.Handler for the * library code. System stanza handlers are allowed to run before * authentication is complete. * * Parameters: * (Function) handler - The callback function. * (String) ns - The namespace to match. * (String) name - The stanza name to match. * (String) type - The stanza type attribute to match. * (String) id - The stanza id attribute to match. */ _addSysHandler: function (handler, ns, name, type, id) { var hand = new Strophe.Handler(handler, ns, name, type, id); hand.user = false; this.addHandlers.push(hand); return hand; }, /** PrivateFunction: _onDisconnectTimeout * _Private_ timeout handler for handling non-graceful disconnection. * * If the graceful disconnect process does not complete within the * time allotted, this handler finishes the disconnect anyway. * * Returns: * false to remove the handler. */ _onDisconnectTimeout: function () { Strophe.info("_onDisconnectTimeout was called"); // cancel all remaining requests and clear the queue var req; while (this._requests.length > 0) { req = this._requests.pop(); req.abort = true; req.xhr.abort(); // jslint complains, but this is fine. setting to empty func // is necessary for IE6 req.xhr.onreadystatechange = function () {}; } // actually disconnect this._doDisconnect(); return false; }, /** PrivateFunction: _onIdle * _Private_ handler to process events during idle cycle. * * This handler is called every 100ms to fire timed handlers that * are ready and keep poll requests going. */ _onIdle: function () { var i, thand, since, newList; // add timed handlers scheduled for addition // NOTE: we add before remove in the case a timed handler is // added and then deleted before the next _onIdle() call. while (this.addTimeds.length > 0) { this.timedHandlers.push(this.addTimeds.pop()); } // remove timed handlers that have been scheduled for deletion while (this.removeTimeds.length > 0) { thand = this.removeTimeds.pop(); i = this.timedHandlers.indexOf(thand); if (i >= 0) { this.timedHandlers.splice(i, 1); } } // call ready timed handlers var now = new Date().getTime(); newList = []; for (i = 0; i < this.timedHandlers.length; i++) { thand = this.timedHandlers[i]; if (this.authenticated || !thand.user) { since = thand.lastCalled + thand.period; if (since - now <= 0) { if (thand.run()) { newList.push(thand); } } else { newList.push(thand); } } } this.timedHandlers = newList; var body, time_elapsed; // if no requests are in progress, poll if (this.authenticated && this._requests.length === 0 && this._data.length === 0 && !this.disconnecting) { Strophe.info("no requests during idle cycle, sending " + "blank request"); this._data.push(null); } if (this._requests.length < 2 && this._data.length > 0 && !this.paused) { body = this._buildBody(); for (i = 0; i < this._data.length; i++) { if (this._data[i] !== null) { if (this._data[i] === "restart") { body.attrs({ to: this.domain, "xml:lang": "en", "xmpp:restart": "true", "xmlns:xmpp": Strophe.NS.BOSH }); } else { body.cnode(this._data[i]).up(); } } } delete this._data; this._data = []; this._requests.push( new Strophe.Request(body.tree(), this._onRequestStateChange.bind( this, this._dataRecv.bind(this)), body.tree().getAttribute("rid"))); this._processRequest(this._requests.length - 1); } if (this._requests.length > 0) { time_elapsed = this._requests[0].age(); if (this._requests[0].dead !== null) { if (this._requests[0].timeDead() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait)) { this._throttledRequestHandler(); } } if (time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait)) { Strophe.warn("Request " + this._requests[0].id + " timed out, over " + Math.floor(Strophe.TIMEOUT * this.wait) + " seconds since last activity"); this._throttledRequestHandler(); } } clearTimeout(this._idleTimeout); // reactivate the timer only if connected if (this.connected) { this._idleTimeout = setTimeout(this._onIdle.bind(this), 100); } } }; if (callback) { callback(Strophe, $build, $msg, $iq, $pres); } })(function () { window.Strophe = arguments[0]; window.$build = arguments[1]; window.$msg = arguments[2]; window.$iq = arguments[3]; window.$pres = arguments[4]; }); /* Plugin to implement the MUC extension. http://xmpp.org/extensions/xep-0045.html */ /* jslint configuration: */ /* global document, window, setTimeout, clearTimeout, console, XMLHttpRequest, ActiveXObject, Base64, MD5, Strophe, $build, $msg, $iq, $pres */ Strophe.addConnectionPlugin('muc', { _connection: null, // The plugin must have the init function /***Function Initialize the MUC plugin. Sets the correct connection object and extends the namesace. */ init: function(conn) { this._connection = conn; /* extend name space * NS.MUC - XMPP Multi-user chat namespace * from XEP 45. * */ Strophe.addNamespace('MUC_OWNER', Strophe.NS.MUC+"#owner"); Strophe.addNamespace('MUC_ADMIN', Strophe.NS.MUC+"#admin"); }, /***Function Join a multi-user chat room Parameters: (String) room - The multi-user chat room to join. (String) nick - The nickname to use in the chat room. Optional (Function) msg_handler_cb - The function call to handle messages from the specified chat room. (Function) pres_handler_cb - The function call back to handle presence in the chat room. (String) password - The optional password to use. (password protected rooms only) */ join: function(room, nick, msg_handler_cb, pres_handler_cb, password) { var room_nick = this.test_append_nick(room, nick); var msg = $pres({from: this._connection.jid, to: room_nick}) .c("x",{xmlns: Strophe.NS.MUC}); if (password) { var password_elem = Strophe.xmlElement("password", [], password); msg.cnode(password_elem); } if (msg_handler_cb) { this._connection.addHandler(function(stanza) { var from = stanza.getAttribute('from'); var roomname = from.split("/"); // filter on room name if (roomname[0] == room) { return msg_handler_cb(stanza); } else { return true; } }, null, "message", null, null, null); } if (pres_handler_cb) { this._connection.addHandler(function(stanza) { var xquery = stanza.getElementsByTagName("x"); if (xquery.length > 0) { //Handle only MUC user protocol for (var i = 0; i < xquery.length; i++) { var xmlns = xquery[i].getAttribute("xmlns"); if (xmlns && xmlns.match(Strophe.NS.MUC)) { return pres_handler_cb(stanza); } } } return true; }, null, "presence", null, null, null); } this._connection.send(msg); }, /***Function Leave a multi-user chat room Parameters: (String) room - The multi-user chat room to leave. (String) nick - The nick name used in the room. (Function) handler_cb - Optional function to handle the successful leave. Returns: iqid - The unique id for the room leave. */ leave: function(room, nick, handler_cb) { var room_nick = this.test_append_nick(room, nick); var presenceid = this._connection.getUniqueId(); var presence = $pres({type: "unavailable", id: presenceid, from: this._connection.jid, to: room_nick}) .c("x",{xmlns: Strophe.NS.MUC}); this._connection.addHandler(handler_cb, null, "presence", null, presenceid, null); this._connection.send(presence); return presenceid; }, /***Function Parameters: (String) room - The multi-user chat room name. (String) nick - The nick name used in the chat room. (String) message - The message to send to the room. (String) type - "groupchat" for group chat messages or "chat" for private chat messages Returns: msgiq - the unique id used to send the message */ message: function(room, nick, message, type) { var room_nick = this.test_append_nick(room, nick); type = type || "groupchat"; var msgid = this._connection.getUniqueId(); var msg = $msg({to: room_nick, from: this._connection.jid, type: type, id: msgid}).c("body", {xmlns: Strophe.NS.CLIENT}).t(message); msg.up().c("x", {xmlns: "jabber:x:event"}).c("composing"); this._connection.send(msg); return msgid; }, /***Function Start a room configuration. Parameters: (String) room - The multi-user chat room name. Returns: id - the unique id used to send the configuration request */ configure: function(room) { //send iq to start room configuration var config = $iq({to:room, type: "get"}).c("query", {xmlns: Strophe.NS.MUC_OWNER}); var stanza = config.tree(); return this._connection.sendIQ(stanza, function(){}, function(){}); }, /***Function Cancel the room configuration Parameters: (String) room - The multi-user chat room name. Returns: id - the unique id used to cancel the configuration. */ cancelConfigure: function(room) { //send iq to start room configuration var config = $iq({to: room, type: "set"}) .c("query", {xmlns: Strophe.NS.MUC_OWNER}) .c("x", {xmlns: "jabber:x:data", type: "cancel"}); var stanza = config.tree(); return this._connection.sendIQ(stanza, function(){}, function(){}); }, /***Function Save a room configuration. Parameters: (String) room - The multi-user chat room name. (Array) configarray - an array of form elements used to configure the room. Returns: id - the unique id used to save the configuration. */ saveConfiguration: function(room, configarray) { var config = $iq({to: room, type: "set"}) .c("query", {xmlns: Strophe.NS.MUC_OWNER}) .c("x", {xmlns: "jabber:x:data", type: "submit"}); for (var i = 0; i < configarray.length; i++) { config.cnode(configarray[i]); config.up(); } var stanza = config.tree(); return this._connection.sendIQ(stanza, function(){}, function(){}); }, /***Function Parameters: (String) room - The multi-user chat room name. Returns: id - the unique id used to create the chat room. */ createInstantRoom: function(room) { var roomiq = $iq({to: room, type: "set"}) .c("query", {xmlns: Strophe.NS.MUC_OWNER}) .c("x", {xmlns: "jabber:x:data", type: "submit"}); return this._connection.sendIQ(roomiq.tree(), function() {}, function() {}); }, /*** Set the topic of the chat room. Parameters: (String) room - The multi-user chat room name. (String) topic - Topic message. */ setTopic: function(room, topic) { var msg = $msg({to: room, from: this._connection.jid, type: "groupchat"}) .c("subject", {xmlns: "jabber:client"}).t(topic); this._connection.send(msg.tree()); }, /***Function Changes the role and affiliation of a member of a MUC room. The modification can only be done by a room moderator. An error will be returned if the user doesn't have permission. Parameters: (String) room - The multi-user chat room name. (String) nick - The nick name of the user to modify. (String) role - The new role of the user. (String) affiliation - The new affiliation of the user. (String) reason - The reason for the change. Returns: iq - the id of the mode change request. */ modifyUser: function(room, nick, role, affiliation, reason) { var item_attrs = {nick: Strophe.escapeNode(nick)}; if (role !== null) { item_attrs.role = role; } if (affiliation !== null) { item_attrs.affiliation = affiliation; } var item = $build("item", item_attrs); if (reason !== null) { item.cnode(Strophe.xmlElement("reason", reason)); } var roomiq = $iq({to: room, type: "set"}) .c("query", {xmlns: Strophe.NS.MUC_OWNER}).cnode(item.tree()); return this._connection.sendIQ(roomiq.tree(), function() {}, function() {}); }, /***Function Change the current users nick name. Parameters: (String) room - The multi-user chat room name. (String) user - The new nick name. */ changeNick: function(room, user) { var room_nick = this.test_append_nick(room, user); var presence = $pres({from: this._connection.jid, to: room_nick}) .c("x",{xmlns: Strophe.NS.MUC}); this._connection.send(presence.tree()); }, /***Function List all chat room available on a server. Parameters: (String) server - name of chat server. (String) handle_cb - Function to call for room list return. */ listRooms: function(server, handle_cb) { var iq = $iq({to: server, from: this._connection.jid, type: "get"}) .c("query",{xmlns: Strophe.NS.DISCO_ITEMS}); this._connection.sendIQ(iq, handle_cb, function(){}); }, test_append_nick: function(room, nick) { var room_nick = room; if (nick) { room_nick += "/" + Strophe.escapeNode(nick); } return room_nick; } }); /* mustache.js — Logic-less templates in JavaScript See http://mustache.github.com/ for more info. */ var Mustache = function() { var Renderer = function() {}; Renderer.prototype = { otag: "{{", ctag: "}}", pragmas: {}, buffer: [], pragmas_implemented: { "IMPLICIT-ITERATOR": true }, context: {}, render: function(template, context, partials, in_recursion) { // reset buffer & set context if(!in_recursion) { this.context = context; this.buffer = []; // TODO: make this non-lazy } // fail fast if(!this.includes("", template)) { if(in_recursion) { return template; } else { this.send(template); return; } } template = this.render_pragmas(template); var html = this.render_section(template, context, partials); if(in_recursion) { return this.render_tags(html, context, partials, in_recursion); } this.render_tags(html, context, partials, in_recursion); }, /* Sends parsed lines */ send: function(line) { if(line !== "") { this.buffer.push(line); } }, /* Looks for %PRAGMAS */ render_pragmas: function(template) { // no pragmas if(!this.includes("%", template)) { return template; } var that = this; var regex = new RegExp(this.otag + "%([\\w-]+) ?([\\w]+=[\\w]+)?" + this.ctag, "g"); return template.replace(regex, function(match, pragma, options) { if(!that.pragmas_implemented[pragma]) { throw({message: "This implementation of mustache doesn't understand the '" + pragma + "' pragma"}); } that.pragmas[pragma] = {}; if(options) { var opts = options.split("="); that.pragmas[pragma][opts[0]] = opts[1]; } return ""; // ignore unknown pragmas silently }); }, /* Tries to find a partial in the curent scope and render it */ render_partial: function(name, context, partials) { name = this.trim(name); if(!partials || partials[name] === undefined) { throw({message: "unknown_partial '" + name + "'"}); } if(typeof(context[name]) != "object") { return this.render(partials[name], context, partials, true); } return this.render(partials[name], context[name], partials, true); }, /* Renders inverted (^) and normal (#) sections */ render_section: function(template, context, partials) { if(!this.includes("#", template) && !this.includes("^", template)) { return template; } var that = this; // CSW - Added "+?" so it finds the tighest bound, not the widest var regex = new RegExp(this.otag + "(\\^|\\#)\\s*(.+)\\s*" + this.ctag + "\n*([\\s\\S]+?)" + this.otag + "\\/\\s*\\2\\s*" + this.ctag + "\\s*", "mg"); // for each {{#foo}}{{/foo}} section do... return template.replace(regex, function(match, type, name, content) { var value = that.find(name, context); if(type == "^") { // inverted section if(!value || that.is_array(value) && value.length === 0) { // false or empty list, render it return that.render(content, context, partials, true); } else { return ""; } } else if(type == "#") { // normal section if(that.is_array(value)) { // Enumerable, Let's loop! return that.map(value, function(row) { return that.render(content, that.create_context(row), partials, true); }).join(""); } else if(that.is_object(value)) { // Object, Use it as subcontext! return that.render(content, that.create_context(value), partials, true); } else if(typeof value === "function") { // higher order section return value.call(context, content, function(text) { return that.render(text, context, partials, true); }); } else if(value) { // boolean section return that.render(content, context, partials, true); } else { return ""; } } }); }, /* Replace {{foo}} and friends with values from our view */ render_tags: function(template, context, partials, in_recursion) { // tit for tat var that = this; var new_regex = function() { return new RegExp(that.otag + "(=|!|>|\\{|%)?([^\\/#\\^]+?)\\1?" + that.ctag + "+", "g"); }; var regex = new_regex(); var tag_replace_callback = function(match, operator, name) { switch(operator) { case "!": // ignore comments return ""; case "=": // set new delimiters, rebuild the replace regexp that.set_delimiters(name); regex = new_regex(); return ""; case ">": // render partial return that.render_partial(name, context, partials); case "{": // the triple mustache is unescaped return that.find(name, context); default: // escape the value return that.escape(that.find(name, context)); } }; var lines = template.split("\n"); for(var i = 0; i < lines.length; i++) { lines[i] = lines[i].replace(regex, tag_replace_callback, this); if(!in_recursion) { this.send(lines[i]); } } if(in_recursion) { return lines.join("\n"); } }, set_delimiters: function(delimiters) { var dels = delimiters.split(" "); this.otag = this.escape_regex(dels[0]); this.ctag = this.escape_regex(dels[1]); }, escape_regex: function(text) { // thank you Simon Willison if(!arguments.callee.sRE) { var specials = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\' ]; arguments.callee.sRE = new RegExp( '(\\' + specials.join('|\\') + ')', 'g' ); } return text.replace(arguments.callee.sRE, '\\$1'); }, /* find `name` in current `context`. That is find me a value from the view object */ find: function(name, context) { name = this.trim(name); // Checks whether a value is thruthy or false or 0 function is_kinda_truthy(bool) { return bool === false || bool === 0 || bool; } var value; if(is_kinda_truthy(context[name])) { value = context[name]; } else if(is_kinda_truthy(this.context[name])) { value = this.context[name]; } if(typeof value === "function") { return value.apply(context); } if(value !== undefined) { return value; } // silently ignore unkown variables return ""; }, // Utility methods /* includes tag */ includes: function(needle, haystack) { return haystack.indexOf(this.otag + needle) != -1; }, /* Does away with nasty characters */ escape: function(s) { s = String(s === null ? "" : s); return s.replace(/&(?!\w+;)|["'<>\\]/g, function(s) { switch(s) { case "&": return "&amp;"; case "\\": return "\\\\"; case '"': return '&quot;'; case "'": return '&#39;'; case "<": return "&lt;"; case ">": return "&gt;"; default: return s; } }); }, // by @langalex, support for arrays of strings create_context: function(_context) { if(this.is_object(_context)) { return _context; } else { var iterator = "."; if(this.pragmas["IMPLICIT-ITERATOR"]) { iterator = this.pragmas["IMPLICIT-ITERATOR"].iterator; } var ctx = {}; ctx[iterator] = _context; return ctx; } }, is_object: function(a) { return a && typeof a == "object"; }, is_array: function(a) { return Object.prototype.toString.call(a) === '[object Array]'; }, /* Gets rid of leading and trailing whitespace */ trim: function(s) { return s.replace(/^\s*|\s*$/g, ""); }, /* Why, why, why? Because IE. Cry, cry cry. */ map: function(array, fn) { if (typeof array.map == "function") { return array.map(fn); } else { var r = []; var l = array.length; for(var i = 0; i < l; i++) { r.push(fn(array[i])); } return r; } } }; return({ name: "mustache.js", version: "0.3.1-dev", /* Turns a template and view into HTML */ to_html: function(template, view, partials, send_fun) { var renderer = new Renderer(); if(send_fun) { renderer.send = send_fun; } renderer.render(template, view, partials); if(!send_fun) { return renderer.buffer.join("\n"); } } }); }(); /* * jQuery i18n plugin * @requires jQuery v1.1 or later * * See http://recursive-design.com/projects/jquery-i18n/ * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Version: 0.9.2 (201111281039) */ (function($) { /** * i18n provides a mechanism for translating strings using a jscript dictionary. * */ /* * i18n property list */ $.i18n = { dict: null, /** * setDictionary() * Initialise the dictionary and translate nodes * * @param property_list i18n_dict : The dictionary to use for translation */ setDictionary: function(i18n_dict) { this.dict = i18n_dict; }, /** * _() * The actual translation function. Looks the given string up in the * dictionary and returns the translation if one exists. If a translation * is not found, returns the original word * * @param string str : The string to translate * @param property_list params : params for using printf() on the string * @return string : Translated word * */ _: function (str, params) { var transl = str; if (this.dict && this.dict[str]) { transl = this.dict[str]; } return this.printf(transl, params); }, /** * toEntity() * Change non-ASCII characters to entity representation * * @param string str : The string to transform * @return string result : Original string with non-ASCII content converted to entities * */ toEntity: function (str) { var result = ''; for (var i=0;i<str.length; i++) { if (str.charCodeAt(i) > 128) result += "&#"+str.charCodeAt(i)+";"; else result += str.charAt(i); } return result; }, /** * stripStr() * * @param string str : The string to strip * @return string result : Stripped string * */ stripStr: function(str) { return str.replace(/^\s*/, "").replace(/\s*$/, ""); }, /** * stripStrML() * * @param string str : The multi-line string to strip * @return string result : Stripped string * */ stripStrML: function(str) { // Split because m flag doesn't exist before JS1.5 and we need to // strip newlines anyway var parts = str.split('\n'); for (var i=0; i<parts.length; i++) parts[i] = stripStr(parts[i]); // Don't join with empty strings, because it "concats" words // And strip again return stripStr(parts.join(" ")); }, /* * printf() * C-printf like function, which substitutes %s with parameters * given in list. %%s is used to escape %s. * * Doesn't work in IE5.0 (splice) * * @param string S : string to perform printf on. * @param string L : Array of arguments for printf() */ printf: function(S, L) { if (!L) return S; var nS = "", search = /%(\d+)\$s/g; // replace %n1$ where n is a number while (result = search.exec(S)) { var index = parseInt(result[1], 10) -1; S = S.replace('%' + result[1] + '\$s', (L[index])); L.splice(index, 1); } var tS = S.split("%s"); if (tS.length > 1) { for(var i = 0; i < L.length; i++) { if (tS[i].lastIndexOf('%') == tS[i].length-1 && i != L.length-1) tS[i] += "s"+tS.splice(i+1,1)[0]; nS += tS[i] + L[i]; } } return nS + tS[tS.length-1]; } }; /* * _t * Allows you to translate a jQuery selector * * eg $('h1')._t('some text') * * @param string str : The string to translate * @param property_list params : params for using printf() on the string * @return element : chained and translated element(s) */ $.fn._t = function(str, params) { return $(this).text($.i18n._(str, params)); }; })(jQuery); /* * Date Format 1.2.3 * (c) 2007-2009 Steven Levithan <stevenlevithan.com> * MIT license * * Includes enhancements by Scott Trenda <scott.trenda.net> * and Kris Kowal <cixar.com/~kris.kowal/> * * Accepts a date, a mask, or a date and a mask. * Returns a formatted version of the given date. * The date defaults to the current date/time. * The mask defaults to dateFormat.masks.default. * * @link http://blog.stevenlevithan.com/archives/date-time-format */ var dateFormat = function () { var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g, timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, timezoneClip = /[^-+\dA-Z]/g, pad = function (val, len) { val = String(val); len = len || 2; while (val.length < len) val = "0" + val; return val; }; // Regexes and supporting functions are cached through closure return function (date, mask, utc) { var dF = dateFormat; // You can't provide utc if you skip other args (use the "UTC:" mask prefix) if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) { mask = date; date = undefined; } // Passing date through Date applies Date.parse, if necessary date = date ? new Date(date) : new Date; if (isNaN(date)) throw SyntaxError("invalid date"); mask = String(dF.masks[mask] || mask || dF.masks["default"]); // Allow setting the utc argument via the mask if (mask.slice(0, 4) == "UTC:") { mask = mask.slice(4); utc = true; } var _ = utc ? "getUTC" : "get", d = date[_ + "Date"](), D = date[_ + "Day"](), m = date[_ + "Month"](), y = date[_ + "FullYear"](), H = date[_ + "Hours"](), M = date[_ + "Minutes"](), s = date[_ + "Seconds"](), L = date[_ + "Milliseconds"](), o = utc ? 0 : date.getTimezoneOffset(), flags = { d: d, dd: pad(d), ddd: dF.i18n.dayNames[D], dddd: dF.i18n.dayNames[D + 7], m: m + 1, mm: pad(m + 1), mmm: dF.i18n.monthNames[m], mmmm: dF.i18n.monthNames[m + 12], yy: String(y).slice(2), yyyy: y, h: H % 12 || 12, hh: pad(H % 12 || 12), H: H, HH: pad(H), M: M, MM: pad(M), s: s, ss: pad(s), l: pad(L, 3), L: pad(L > 99 ? Math.round(L / 10) : L), t: H < 12 ? "a" : "p", tt: H < 12 ? "am" : "pm", T: H < 12 ? "A" : "P", TT: H < 12 ? "AM" : "PM", Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""), o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10] }; return mask.replace(token, function ($0) { return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1); }); }; }(); // Some common format strings dateFormat.masks = { "default": "ddd mmm dd yyyy HH:MM:ss", shortDate: "m/d/yy", mediumDate: "mmm d, yyyy", longDate: "mmmm d, yyyy", fullDate: "dddd, mmmm d, yyyy", shortTime: "h:MM TT", mediumTime: "h:MM:ss TT", longTime: "h:MM:ss TT Z", isoDate: "yyyy-mm-dd", isoTime: "HH:MM:ss", isoDateTime: "yyyy-mm-dd'T'HH:MM:ss", isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'" }; // Internationalization strings dateFormat.i18n = { dayNames: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] }; // For convenience... Date.prototype.format = function (mask, utc) { return dateFormat(this, mask, utc); };
src/components/Navbar/UserMenu.js
zksailor534/react-adminlte-dash
/* eslint-disable react/jsx-filename-extension */ import React from 'react'; import styled from 'styled-components'; import DropdownMenu from './DropdownMenu'; import { fontFamilyBase, fontSizeBase, lineHeightBase, fontWeightBase, navbarHeight, navbarPaddingHorizontal, navbarPaddingVertical, screenXsMin, } from '../../styles/variables'; const imageSize = `${Math.floor(parseInt(navbarHeight, 10) / 2)}px`; const imageMarginTop = `-${Math.ceil( ((parseInt(imageSize, 10) + parseInt(navbarPaddingHorizontal, 10) + parseInt(navbarPaddingVertical, 10)) - parseInt(navbarHeight, 10)) / 2)}px`; const imageMarginBottom = `-${Math.floor( ((parseInt(imageSize, 10) + parseInt(navbarPaddingHorizontal, 10) + parseInt(navbarPaddingVertical, 10)) - parseInt(navbarHeight, 10)) / 2)}px`; const StyledUserImage = styled.img` box-sizing: border-box; float: left; border: 0; vertical-align: middle; width: ${imageSize}; height: ${imageSize}; border-radius: 50%; margin-right: 10px; margin-top: ${imageMarginTop}; margin-bottom: ${imageMarginBottom}; max-width: none; cursor: pointer; -webkit-touch-callout: none; /* iOS Safari */ -webkit-user-select: none; /* Chrome/Safari/Opera */ -khtml-user-select: none; /* Konqueror */ -moz-user-select: none; /* Firefox */ -ms-user-select: none; /* Internet Explorer/Edge */ user-select: none; /* Non-prefixed version, currently not supported by any browser */ `; const StyledUserName = styled.span` cursor: pointer; -webkit-touch-callout: none; /* iOS Safari */ -webkit-user-select: none; /* Chrome/Safari/Opera */ -khtml-user-select: none; /* Konqueror */ -moz-user-select: none; /* Firefox */ -ms-user-select: none; /* Internet Explorer/Edge */ user-select: none; /* Non-prefixed version, currently not supported by any browser */ @media (max-width: ${screenXsMin}) { display: none; } `; const UserMenuHeader = styled.li` background-color: ${props => props.theme.navbarUserMenuHeaderBg || props.theme.backgroundColor}; padding: 10px; text-align: center; `; const UserMenuHeaderImage = styled.img` z-index: 5; height: 90px; width: 90px; border: 3px solid; border-color: rgba(255, 255, 255, 0.2); border-radius: 50%; `; const UserMenuHeaderName = styled.p` z-index: 5; color: #fff; color: rgba(255, 255, 255, 0.8); font-size: 17px; margin-top: 10px; `; const UserFooterButton = styled.button` color: #666666; box-shadow: none; border: 1px solid transparent; border-width: 1px; border-radius: 0; background-color: #f4f4f4; border-color: #ddd; display: inline-block; padding: 6px 12px; margin-bottom: 0; font-size: ${fontSizeBase}; font-weight: ${fontWeightBase}; line-height: ${lineHeightBase}; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; &:hover { @media (max-width: @screen-sm-max) { background-color: #f9f9f9; } } `; const UserFooter = styled.li` /* clearfix */ &:before, &:after { display: table; content: " "; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } &:after { clear: both; } background-color: #f9f9f9; padding: 10px; `; const UserDropDown = styled(DropdownMenu)` border-top-radius: 0; border-top: 0; padding: 1px 0 0 0; width: 280px; `; const StyledUserMenu = styled.li` /* shared */ -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-family: ${fontFamilyBase}; font-weight: ${fontWeightBase}; font-size: ${fontSizeBase}; line-height: ${lineHeightBase}; box-sizing: border-box; float: left; background-color: transparent; background-image: none; border: none; outline: none; padding: ${navbarPaddingVertical} ${navbarPaddingHorizontal}; position: relative; text-decoration: none; cursor: pointer; &:focus, &:active { background: transparent; } /* theme */ color: ${props => props.theme.navbarFontColor || '#fff'}; border-left: ${props => props.theme.navbarItemBorder || 'none'}; &:hover { color: ${props => props.theme.navbarHoverColor || '#fff'}; background-color: ${props => props.theme.logoBgColor || 'transparent'}; } @media (max-width: ${screenXsMin}) { padding: ${navbarPaddingVertical} 5px; } `; class UserMenu extends React.Component { constructor(props) { super(props); this.state = { open: false, }; this._toggleMenu = this.toggleMenu.bind(this); this._closeMenu = this.closeMenu.bind(this); } toggleMenu() { this.setState({ open: !this.state.open, }); } closeMenu() { this.setState({ open: false, }); } render() { return ( <StyledUserMenu onClick={this._toggleMenu} onMouseLeave={this._closeMenu} > <StyledUserImage src={this.props.image} /> <StyledUserName>{this.props.name}</StyledUserName> <UserDropDown open={this.state.open} > <UserMenuHeader> <UserMenuHeaderImage src={this.props.image} /> <UserMenuHeaderName>{this.props.name}</UserMenuHeaderName> </UserMenuHeader> <UserFooter> {this.props.profileAction && <div style={{ float: 'left' }}> <UserFooterButton onClick={this.props.profileAction}>Profile</UserFooterButton> </div>} {this.props.signOutAction && <div style={{ float: 'right' }}> <UserFooterButton onClick={this.props.signOutAction}>Sign Out</UserFooterButton> </div>} </UserFooter> </UserDropDown> </StyledUserMenu> ); } } UserMenu.propTypes = { name: React.PropTypes.string, image: React.PropTypes.string, profileAction: React.PropTypes.func, signOutAction: React.PropTypes.func, }; export default UserMenu;
packages/reactor-kitchensink/src/examples/Layouts/resizable/resizable.js
dbuhrman/extjs-reactor
import React from 'react'; import { Panel, Container } from '@extjs/ext-react'; import colors from '../../colors'; Ext.require('Ext.panel.Resizable'); export default function ResizableExample() { return ( <Panel shadow layout="fit"> <Panel title="Dock Left" docked="left" width={200} layout="center" resizable={{ split: true, edges: 'east', dynamic: true }} > <code>dynamic: true</code> </Panel> <Panel title="Unresizable region" flex={1}/> <Panel docked="right" title="Dock Right" width={200} collapsible="right" layout="center" resizable={{ split: true, edges: 'west' }} > <code>collapsible</code> </Panel> <Panel docked="top" title="Dock Top" height={150} resizable={{ split: true, edges: 'south' }} /> <Panel docked="bottom" title="Dock Bottom" height={150} layout="center" resizable={{ split: true, edges: 'north', snap: 50 }} > <code>snap: 50</code> </Panel> </Panel> ) } const styles = { panelBody: { fontSize: '18px', color: '#777' } }
src/utils/defaultMenuRenderer.js
serkanozer/react-select
import classNames from 'classnames'; import React from 'react'; function menuRenderer ({ focusedOption, instancePrefix, labelKey, onFocus, onSelect, optionClassName, optionComponent, optionRenderer, options, valueArray, valueKey, onOptionRef }) { let Option = optionComponent; return options.map((option, i) => { let isSelected = valueArray && valueArray.indexOf(option) > -1; let isFocused = option === focusedOption; let optionClass = classNames(optionClassName, { 'Select-option': true, 'is-selected': isSelected, 'is-focused': isFocused, 'is-disabled': option.disabled, }); return ( <Option className={optionClass} instancePrefix={instancePrefix} isDisabled={option.disabled} isFocused={isFocused} isSelected={isSelected} key={`option-${i}-${option[valueKey]}`} onFocus={onFocus} onSelect={onSelect} option={option} optionIndex={i} ref={ref => { onOptionRef(ref, isFocused); }} > {optionRenderer(option, i)} </Option> ); }); } export default menuRenderer;
ajax/libs/react-datetime/3.0.0-beta.4/react-datetime.min.js
sufuf3/cdnjs
/* react-datetime v3.0.0-beta.4 https://github.com/YouCanBookMe/react-datetime MIT: https://github.com/YouCanBookMe/react-datetime/raw/master/LICENSE */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("React"),require("moment"),require("ReactDOM")):"function"==typeof define&&define.amd?define(["React","moment","ReactDOM"],t):"object"==typeof exports?exports.Datetime=t(require("React"),require("moment"),require("ReactDOM")):e.Datetime=t(e.React,e.moment,e.ReactDOM)}(this,function(e,t,n){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";var r=n(1),o=n(2),i=n(9),a=n(17),s=n(10),c=n(18),u=n(19),l=n(20),p=n(21),d=n(22)["default"],f={YEARS:"years",MONTHS:"months",DAYS:"days",TIME:"time"},h=o,m=function(){},y=h.oneOfType([h.instanceOf(a),h.instanceOf(Date),h.string]),v=i({displayName:"DateTime",propTypes:{value:y,initialValue:y,initialViewDate:y,initialViewMode:h.oneOf([f.YEARS,f.MONTHS,f.DAYS,f.TIME]),onOpen:h.func,onClose:h.func,onChange:h.func,onNavigate:h.func,onBeforeNavigate:h.func,onNavigateBack:h.func,onNavigateForward:h.func,updateOnView:h.string,locale:h.string,utc:h.bool,displayTimeZone:h.string,input:h.bool,dateFormat:h.oneOfType([h.string,h.bool]),timeFormat:h.oneOfType([h.string,h.bool]),inputProps:h.object,timeConstraints:h.object,isValidDate:h.func,open:h.bool,strictParsing:h.bool,closeOnSelect:h.bool,closeOnTab:h.bool,renderView:h.func,renderInput:h.func,renderDay:h.func,renderMonth:h.func,renderYear:h.func},getDefaultProps:function(){return{onOpen:m,onClose:m,onCalendarOpen:m,onCalendarClose:m,onChange:m,onNavigate:m,onBeforeNavigate:function(e){return e},onNavigateBack:m,onNavigateForward:m,dateFormat:!0,timeFormat:!0,utc:!1,className:"",input:!0,inputProps:{},timeConstraints:{},isValidDate:function(){return!0},strictParsing:!0,closeOnSelect:!1,closeOnTab:!0,closeOnClickOutside:!0,renderView:function(e,t){return t()}}},getInitialState:function(){var e=this.props,t=this.getFormat("datetime"),n=this.parseDate(e.value||e.initialValue,t);return this.checkTZ(e),{open:!e.input,currentView:e.initialViewMode||this.getInitialView(this.getFormat("date")),viewDate:this.getInitialViewDate(e.initialViewDate,n,t),selectedDate:n&&n.isValid()?n:void 0,inputValue:e.inputProps.value||n&&n.isValid()&&n.format(t)||e.value&&"string"==typeof e.value&&e.value||e.initialValue&&"string"==typeof e.initialValue&&e.initialValue||""}},getInitialViewDate:function(e,t,n){var r;if(e){if(r=this.parseDate(e,n),r&&r.isValid())return r;this.log('The initialViewDated given "'+e+'" is not valid. Using current date instead.')}else if(t&&t.isValid())return t.clone();return this.getInitialDate()},getInitialDate:function(){var e=this.localMoment();return e.hour(0).minute(0).second(0).millisecond(0),e},getInitialView:function(e){return e?this.getUpdateOn(e):f.TIME},parseDate:function(e,t){var n;return e&&"string"==typeof e?n=this.localMoment(e,t):e&&(n=this.localMoment(e)),n&&!n.isValid()&&(n=null),n},isOpen:function(){var e=!this.props.input||(void 0===this.props.open?this.state.open:this.props.open);return e},getUpdateOn:function(e){return this.props.updateOnView?this.props.updateOnView:e.match(/[lLD]/)?f.DAYS:e.indexOf("M")!==-1?f.MONTHS:e.indexOf("Y")!==-1?f.YEARS:f.DAYS},getLocaleData:function(e){var t=e||this.props;return this.localMoment(t.value||t.defaultValue||new Date).localeData()},getDateFormat:function(e){var t=this.props.dateFormat;return t===!0?e.longDateFormat("L"):t?t:""},getTimeFormat:function(e){var t=this.props.timeFormat;return t===!0?e.longDateFormat("LT"):t?t:""},getFormat:function(e){if("date"===e)return this.getDateFormat(this.getLocaleData());if("time"===e)return this.getTimeFormat(this.getLocaleData());if("datetime"===e){var t=this.getLocaleData(),n=this.getDateFormat(t),r=this.getTimeFormat(t);return n&&r?n+" "+r:n||r}},onInputChange:function(e){var t=null===e.target?e:e.target.value,n=this.localMoment(t,this.getFormat("datetime")),r={inputValue:t};return n.isValid()?(r.selectedDate=n,r.viewDate=n.clone().startOf("month")):r.selectedDate=null,this.setState(r,function(){return this.props.onChange(n.isValid()?n:this.state.inputValue)})},onInputKey:function(e){9===e.which&&this.props.closeOnTab&&this.closeCalendar()},showView:function(e,t){var n=this;return function(){var r=n.props.onBeforeNavigate(e,n.state.currentView,(t||n.state.viewDate).clone());r&&n.state.currentView!==r&&(n.props.onNavigate(r),n.setState({currentView:r}))}},updateTime:function(e,t,n,r){var o={},i=r?"selectedDate":"viewDate";o[i]=this.state[i].clone()[e](t,n),this.setState(o)},viewToMethod:{days:"date",months:"month",years:"year"},nextView:{days:"time",months:"days",years:"months"},updateDate:function(e){var t=this.state,n=t.currentView,r=this.getUpdateOn(this.getFormat("date")),o=this.state.viewDate.clone();o[this.viewToMethod[n]](parseInt(e.target.getAttribute("data-value"),10)),"days"===n&&(o.month(parseInt(e.target.getAttribute("data-month"),10)),o.year(parseInt(e.target.getAttribute("data-year"),10)));var i={viewDate:o};n===r?(i.selectedDate=o.clone(),i.inputValue=o.format(this.getFormat("datetime")),void 0===this.props.open&&this.props.input&&this.props.closeOnSelect&&this.closeCalendar(),this.props.onChange(o.clone())):this.showView(this.nextView[n],o)(),this.setState(i)},navigate:function(e,t){var n=this;return function(){var r=n.state.viewDate.clone(),o={viewDate:r};r.add(e,t),e>0?n.props.onNavigateForward(e,t):n.props.onNavigateBack(-e,t),n.setState(o)}},allowedSetTime:["hours","minutes","seconds","milliseconds"],setTime:function(e,t){var n=this.state,r=(n.selectedDate||n.viewDate).clone();r[e](t),this.props.value||this.setState({selectedDate:r,viewDate:r.clone(),inputValue:r.format(this.getFormat("datetime"))}),this.props.onChange(r.clone())},openCalendar:function(e){this.isOpen()||this.setState({open:!0},function(){this.props.onOpen(e)})},closeCalendar:function(){this.setState({open:!1},function(){this.props.onClose(this.state.selectedDate||this.state.inputValue)})},handleClickOutside:function(){var e=this.props;e.input&&this.state.open&&void 0===e.open&&e.closeOnClickOutside&&this.closeCalendar()},localMoment:function(e,t,n){n=n||this.props;var r=null;return r=n.utc?a.utc(e,t,n.strictParsing):n.displayTimeZone?a.tz(e,t,n.displayTimeZone):a(e,t,n.strictParsing),n.locale&&r.locale(n.locale),r},checkTZ:function(e){!e.displayTimeZone||this.tzWarning||a.tz||(this.tzWarning=!0,this.log('displayTimeZone prop with value "'+e.displayTimeZone+'" is used but moment.js timezone is not loaded.',"error"))},overrideEvent:function(e,t){if(this.overridenEvents||(this.overridenEvents={}),!this.overridenEvents[e]){var n=this;this.overridenEvents[e]=function(r){var o;n.props.inputProps&&n.props.inputProps[e]&&(o=n.props.inputProps[e](r)),o!==!1&&t(r)}}return this.overridenEvents[e]},getClassName:function(){var e="rdt",t=this.props,n=t.className;return Array.isArray(n)?e+=" "+n.join(" "):n&&(e+=" "+n),t.input||(e+=" rdtStatic"),this.isOpen()&&(e+=" rdtOpen"),e},componentDidUpdate:function(e){if(e!==this.props){var t=!1,n=this.props;["locale","utc","displayZone","dateFormat","timeFormat"].forEach(function(r){e[r]!==n[r]&&(t=!0)}),t&&this.regenerateDates(this.props),this.checkTZ(this.props)}},regenerateDates:function(e){var t=this.state.viewDate.clone(),n=this.state.selectedDate&&this.state.selectedDate.clone();e.locale&&(t.locale(e.locale),n&&n.locale(e.locale)),e.utc?(t.utc(),n&&n.utc()):e.displayTimeZone?(t.tz(e.displayTimeZone),n&&n.tz(e.displayTimeZone)):(t.locale(),n&&n.locale());var r={viewDate:t,selectedDate:n};n&&n.isValid()&&(r.inputValue=n.format(this.getFormat("datetime"))),this.setState(r)},getSelectedDate:function(){if(void 0===this.props.value)return this.state.selectedDate;var e=this.parseDate(this.props.value,this.getFormat("datetime"));return!(!e||!e.isValid())&&e},getInputValue:function(){var e=this.getSelectedDate();return e?e.format(this.getFormat("datetime")):this.state.inputValue},setViewDate:function(e){var t=this,n=function(){return t.log("Invalid date passed to the `setViewDate` method: "+e)};if(!e)return n();var r;return r="string"==typeof e?this.localMoment(e,this.getFormat("datetime")):this.localMoment(e),r&&r.isValid()?void this.setState({viewDate:r}):n()},setViewMode:function(e){this.showView(e)()},log:function(e,t){var n=console;t||(t="warn"),n[t]("***react-datetime:"+e)},render:function(){var e=this.getClassName(),t=[];if(this.props.input){var n=r({type:"text",className:"form-control",value:this.getInputValue()},this.props.inputProps,{onFocus:this.overrideEvent("onOpen",this.openCalendar),onChange:this.overrideEvent("onChange",this.onInputChange),onKeyDown:this.overrideEvent("onKeyDown",this.onInputKey)});t=this.props.renderInput?[s.createElement("div",{key:"i"},this.props.renderInput(n,this.openCalendar,this.closeCalendar))]:[s.createElement("input",r({key:"i"},n))]}return s.createElement(g,{className:e,onClickOut:this.handleClickOutside},t.concat(s.createElement("div",{key:"dt",className:"rdtPicker"},this.props.renderView(this.state.currentView,this.renderCalendar.bind(this,this.state.currentView)))))},renderCalendar:function(e){var t=this.props,n=this.state,r={viewDate:n.viewDate.clone(),selectedDate:this.getSelectedDate(),isValidDate:t.isValidDate,updateDate:this.updateDate,navigate:this.navigate,showView:this.showView};return e===f.YEARS?(r.renderYear=t.renderYear,s.createElement(l,r)):e===f.MONTHS?(r.renderMonth=t.renderMonth,s.createElement(u,r)):e===f.DAYS?(r.renderDay=t.renderDay,r.timeFormat=this.getFormat("time"),s.createElement(c,r)):e===f.TIME?(r.dateFormat=this.getFormat("date"),r.timeFormat=this.getFormat("time"),r.timeConstraints=t.timeConstraints,r.setTime=this.setTime,s.createElement(p,r)):void 0}}),g=d(i({render:function(){return s.createElement("div",{className:this.props.className},this.props.children)},handleClickOutside:function(e){this.props.onClickOut(e)}}));v.moment=a,e.exports=v},function(e,t){"use strict";function n(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function r(e){var t=Object.getOwnPropertyNames(e);return Object.getOwnPropertySymbols&&(t=t.concat(Object.getOwnPropertySymbols(e))),t.filter(function(t){return o.call(e,t)})}var o=Object.prototype.propertyIsEnumerable;e.exports=Object.assign||function(e,t){for(var o,i,a=n(e),s=1;s<arguments.length;s++){o=arguments[s],i=r(Object(o));for(var c=0;c<i.length;c++)a[i[c]]=o[i[c]]}return a}},function(e,t,n){(function(t){if("production"!==t.env.NODE_ENV){var r="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103,o=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===r},i=!0;e.exports=n(4)(o,i)}else e.exports=n(8)()}).call(t,n(3))},function(e,t){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function o(e){if(l===setTimeout)return setTimeout(e,0);if((l===n||!l)&&setTimeout)return l=setTimeout,setTimeout(e,0);try{return l(e,0)}catch(t){try{return l.call(null,e,0)}catch(t){return l.call(this,e,0)}}}function i(e){if(p===clearTimeout)return clearTimeout(e);if((p===r||!p)&&clearTimeout)return p=clearTimeout,clearTimeout(e);try{return p(e)}catch(t){try{return p.call(null,e)}catch(t){return p.call(this,e)}}}function a(){m&&f&&(m=!1,f.length?h=f.concat(h):y=-1,h.length&&s())}function s(){if(!m){var e=o(a);m=!0;for(var t=h.length;t;){for(f=h,h=[];++y<t;)f&&f[y].run();y=-1,t=h.length}f=null,m=!1,i(e)}}function c(e,t){this.fun=e,this.array=t}function u(){}var l,p,d=e.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:n}catch(e){l=n}try{p="function"==typeof clearTimeout?clearTimeout:r}catch(e){p=r}}();var f,h=[],m=!1,y=-1;d.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];h.push(new c(e,t)),1!==h.length||m||o(s)},c.prototype.run=function(){this.fun.apply(null,this.array)},d.title="browser",d.browser=!0,d.env={},d.argv=[],d.version="",d.versions={},d.on=u,d.addListener=u,d.once=u,d.off=u,d.removeListener=u,d.removeAllListeners=u,d.emit=u,d.prependListener=u,d.prependOnceListener=u,d.listeners=function(e){return[]},d.binding=function(e){throw new Error("process.binding is not supported")},d.cwd=function(){return"/"},d.chdir=function(e){throw new Error("process.chdir is not supported")},d.umask=function(){return 0}},function(e,t,n){(function(t){"use strict";function r(){return null}var o=n(5),i=n(6),a=n(7),s=function(){};"production"!==t.env.NODE_ENV&&(s=function(e){var t="Warning: "+e;"undefined"!=typeof console&&console.error(t);try{throw new Error(t)}catch(n){}}),e.exports=function(e,n){function c(e){var t=e&&(x&&e[x]||e[T]);if("function"==typeof t)return t}function u(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function l(e){this.message=e,this.stack=""}function p(e){function r(r,c,u,p,d,f,h){if(p=p||I,f=f||u,h!==i){if(n){var m=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types");throw m.name="Invariant Violation",m}if("production"!==t.env.NODE_ENV&&"undefined"!=typeof console){var y=p+":"+u;!o[y]&&a<3&&(s("You are manually calling a React.PropTypes validation function for the `"+f+"` prop on `"+p+"`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."),o[y]=!0,a++)}}return null==c[u]?r?new l(null===c[u]?"The "+d+" `"+f+"` is marked as required "+("in `"+p+"`, but its value is `null`."):"The "+d+" `"+f+"` is marked as required in "+("`"+p+"`, but its value is `undefined`.")):null:e(c,u,p,d,f)}if("production"!==t.env.NODE_ENV)var o={},a=0;var c=r.bind(null,!1);return c.isRequired=r.bind(null,!0),c}function d(e){function t(t,n,r,o,i,a){var s=t[n],c=C(s);if(c!==e){var u=k(s);return new l("Invalid "+o+" `"+i+"` of type "+("`"+u+"` supplied to `"+r+"`, expected ")+("`"+e+"`."))}return null}return p(t)}function f(){return p(r)}function h(e){function t(t,n,r,o,a){if("function"!=typeof e)return new l("Property `"+a+"` of component `"+r+"` has invalid PropType notation inside arrayOf.");var s=t[n];if(!Array.isArray(s)){var c=C(s);return new l("Invalid "+o+" `"+a+"` of type "+("`"+c+"` supplied to `"+r+"`, expected an array."))}for(var u=0;u<s.length;u++){var p=e(s,u,r,o,a+"["+u+"]",i);if(p instanceof Error)return p}return null}return p(t)}function m(){function t(t,n,r,o,i){var a=t[n];if(!e(a)){var s=C(a);return new l("Invalid "+o+" `"+i+"` of type "+("`"+s+"` supplied to `"+r+"`, expected a single ReactElement."))}return null}return p(t)}function y(e){function t(t,n,r,o,i){if(!(t[n]instanceof e)){var a=e.name||I,s=S(t[n]);return new l("Invalid "+o+" `"+i+"` of type "+("`"+s+"` supplied to `"+r+"`, expected ")+("instance of `"+a+"`."))}return null}return p(t)}function v(e){function n(t,n,r,o,i){for(var a=t[n],s=0;s<e.length;s++)if(u(a,e[s]))return null;var c=JSON.stringify(e);return new l("Invalid "+o+" `"+i+"` of value `"+a+"` "+("supplied to `"+r+"`, expected one of "+c+"."))}return Array.isArray(e)?p(n):("production"!==t.env.NODE_ENV?s("Invalid argument supplied to oneOf, expected an instance of array."):void 0,r)}function g(e){function t(t,n,r,o,a){if("function"!=typeof e)return new l("Property `"+a+"` of component `"+r+"` has invalid PropType notation inside objectOf.");var s=t[n],c=C(s);if("object"!==c)return new l("Invalid "+o+" `"+a+"` of type "+("`"+c+"` supplied to `"+r+"`, expected an object."));for(var u in s)if(s.hasOwnProperty(u)){var p=e(s,u,r,o,a+"."+u,i);if(p instanceof Error)return p}return null}return p(t)}function E(e){function n(t,n,r,o,a){for(var s=0;s<e.length;s++){var c=e[s];if(null==c(t,n,r,o,a,i))return null}return new l("Invalid "+o+" `"+a+"` supplied to "+("`"+r+"`."))}if(!Array.isArray(e))return"production"!==t.env.NODE_ENV?s("Invalid argument supplied to oneOfType, expected an instance of array."):void 0,r;for(var o=0;o<e.length;o++){var a=e[o];if("function"!=typeof a)return s("Invalid argument supplied to oneOfType. Expected an array of check functions, but received "+_(a)+" at index "+o+"."),r}return p(n)}function D(){function e(e,t,n,r,o){return b(e[t])?null:new l("Invalid "+r+" `"+o+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return p(e)}function O(e){function t(t,n,r,o,a){var s=t[n],c=C(s);if("object"!==c)return new l("Invalid "+o+" `"+a+"` of type `"+c+"` "+("supplied to `"+r+"`, expected `object`."));for(var u in e){var p=e[u];if(p){var d=p(s,u,r,o,a+"."+u,i);if(d)return d}}return null}return p(t)}function w(e){function t(t,n,r,a,s){var c=t[n],u=C(c);if("object"!==u)return new l("Invalid "+a+" `"+s+"` of type `"+u+"` "+("supplied to `"+r+"`, expected `object`."));var p=o({},t[n],e);for(var d in p){var f=e[d];if(!f)return new l("Invalid "+a+" `"+s+"` key `"+d+"` supplied to `"+r+"`.\nBad object: "+JSON.stringify(t[n],null," ")+"\nValid keys: "+JSON.stringify(Object.keys(e),null," "));var h=f(c,d,r,a,s+"."+d,i);if(h)return h}return null}return p(t)}function b(t){switch(typeof t){case"number":case"string":case"undefined":return!0;case"boolean":return!t;case"object":if(Array.isArray(t))return t.every(b);if(null===t||e(t))return!0;var n=c(t);if(!n)return!1;var r,o=n.call(t);if(n!==t.entries){for(;!(r=o.next()).done;)if(!b(r.value))return!1}else for(;!(r=o.next()).done;){var i=r.value;if(i&&!b(i[1]))return!1}return!0;default:return!1}}function N(e,t){return"symbol"===e||("Symbol"===t["@@toStringTag"]||"function"==typeof Symbol&&t instanceof Symbol)}function C(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":N(t,e)?"symbol":t}function k(e){if("undefined"==typeof e||null===e)return""+e;var t=C(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function _(e){var t=k(e);switch(t){case"array":case"object":return"an "+t;case"boolean":case"date":case"regexp":return"a "+t;default:return t}}function S(e){return e.constructor&&e.constructor.name?e.constructor.name:I}var x="function"==typeof Symbol&&Symbol.iterator,T="@@iterator",I="<<anonymous>>",V={array:d("array"),bool:d("boolean"),func:d("function"),number:d("number"),object:d("object"),string:d("string"),symbol:d("symbol"),any:f(),arrayOf:h,element:m(),instanceOf:y,node:D(),objectOf:g,oneOf:v,oneOfType:E,shape:O,exact:w};return l.prototype=Error.prototype,V.checkPropTypes=a,V.PropTypes=V,V}}).call(t,n(3))},function(e,t){"use strict";function n(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function r(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;var r=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==r.join(""))return!1;var o={};return"abcdefghijklmnopqrst".split("").forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(i){return!1}}var o=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;e.exports=r()?Object.assign:function(e,t){for(var r,s,c=n(e),u=1;u<arguments.length;u++){r=Object(arguments[u]);for(var l in r)i.call(r,l)&&(c[l]=r[l]);if(o){s=o(r);for(var p=0;p<s.length;p++)a.call(r,s[p])&&(c[s[p]]=r[s[p]])}}return c}},function(e,t){"use strict";var n="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";e.exports=n},function(e,t,n){(function(t){"use strict";function r(e,n,r,s,c){if("production"!==t.env.NODE_ENV)for(var u in e)if(e.hasOwnProperty(u)){var l;try{if("function"!=typeof e[u]){var p=Error((s||"React class")+": "+r+" type `"+u+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[u]+"`.");throw p.name="Invariant Violation",p}l=e[u](n,u,s,r,null,i)}catch(d){l=d}if(!l||l instanceof Error||o((s||"React class")+": type specification of "+r+" `"+u+"` is invalid; the type checker function must return `null` or an `Error` but returned a "+typeof l+". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."),l instanceof Error&&!(l.message in a)){a[l.message]=!0;var f=c?c():"";o("Failed "+r+" type: "+l.message+(null!=f?f:""))}}}var o=function(){};if("production"!==t.env.NODE_ENV){var i=n(6),a={};o=function(e){var t="Warning: "+e;"undefined"!=typeof console&&console.error(t);try{throw new Error(t)}catch(n){}}}e.exports=r}).call(t,n(3))},function(e,t,n){"use strict";function r(){}var o=n(6);e.exports=function(){function e(e,t,n,r,i,a){if(a!==o){var s=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw s.name="Invariant Violation",s}}function t(){return e}e.isRequired=e;var n={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t};return n.checkPropTypes=r,n.PropTypes=n,n}},function(e,t,n){"use strict";var r=n(10),o=n(11);if("undefined"==typeof r)throw Error("create-react-class could not find the React object. If you are using script tags, make sure that React is being loaded before create-react-class.");var i=(new r.Component).updater;e.exports=o(r.Component,r.isValidElement,i)},function(t,n){t.exports=e},function(e,t,n){(function(t){"use strict";function r(e){return e}function o(e,n,o){function p(e,n,r){for(var o in n)n.hasOwnProperty(o)&&"production"!==t.env.NODE_ENV&&c("function"==typeof n[o],"%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.",e.displayName||"ReactClass",u[r],o)}function d(e,t){var n=w.hasOwnProperty(t)?w[t]:null;_.hasOwnProperty(t)&&s("OVERRIDE_BASE"===n,"ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.",t),e&&s("DEFINE_MANY"===n||"DEFINE_MANY_MERGED"===n,"ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.",t)}function f(e,r){if(r){s("function"!=typeof r,"ReactClass: You're attempting to use a component class or function as a mixin. Instead, just use a regular object."),s(!n(r),"ReactClass: You're attempting to use a component as a mixin. Instead, just use a regular object.");var o=e.prototype,i=o.__reactAutoBindPairs;r.hasOwnProperty(l)&&N.mixins(e,r.mixins);for(var a in r)if(r.hasOwnProperty(a)&&a!==l){var u=r[a],p=o.hasOwnProperty(a);if(d(p,a),N.hasOwnProperty(a))N[a](e,u);else{var f=w.hasOwnProperty(a),h="function"==typeof u,m=h&&!f&&!p&&r.autobind!==!1;if(m)i.push(a,u),o[a]=u;else if(p){var g=w[a];s(f&&("DEFINE_MANY_MERGED"===g||"DEFINE_MANY"===g),"ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.",g,a),"DEFINE_MANY_MERGED"===g?o[a]=y(o[a],u):"DEFINE_MANY"===g&&(o[a]=v(o[a],u))}else o[a]=u,"production"!==t.env.NODE_ENV&&"function"==typeof u&&r.displayName&&(o[a].displayName=r.displayName+"_"+a)}}}else if("production"!==t.env.NODE_ENV){var E=typeof r,D="object"===E&&null!==r;"production"!==t.env.NODE_ENV&&c(D,"%s: You're attempting to include a mixin that is either null or not an object. Check the mixins included by the component, as well as any mixins they include themselves. Expected object but got %s.",e.displayName||"ReactClass",null===r?null:E)}}function h(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in N;s(!o,'ReactClass: You are attempting to define a reserved property, `%s`, that shouldn\'t be on the "statics" key. Define it as an instance property instead; it will still be accessible on the constructor.',n);var i=n in e;if(i){var a=b.hasOwnProperty(n)?b[n]:null;return s("DEFINE_MANY_MERGED"===a,"ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.",n),void(e[n]=y(e[n],r))}e[n]=r}}}function m(e,t){s(e&&t&&"object"==typeof e&&"object"==typeof t,"mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.");for(var n in t)t.hasOwnProperty(n)&&(s(void 0===e[n],"mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.",n),e[n]=t[n]);return e}function y(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);if(null==n)return r;if(null==r)return n;var o={};return m(o,n),m(o,r),o}}function v(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function g(e,n){var r=n.bind(e);if("production"!==t.env.NODE_ENV){r.__reactBoundContext=e,r.__reactBoundMethod=n,r.__reactBoundArguments=null;var o=e.constructor.displayName,i=r.bind;r.bind=function(a){for(var s=arguments.length,u=Array(s>1?s-1:0),l=1;l<s;l++)u[l-1]=arguments[l];if(a!==e&&null!==a)"production"!==t.env.NODE_ENV&&c(!1,"bind(): React component methods may only be bound to the component instance. See %s",o);else if(!u.length)return"production"!==t.env.NODE_ENV&&c(!1,"bind(): You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call. See %s",o),r;var p=i.apply(r,arguments);return p.__reactBoundContext=e,p.__reactBoundMethod=n,p.__reactBoundArguments=u,p}}return r}function E(e){for(var t=e.__reactAutoBindPairs,n=0;n<t.length;n+=2){var r=t[n],o=t[n+1];e[r]=g(e,o)}}function D(e){var n=r(function(e,r,i){"production"!==t.env.NODE_ENV&&c(this instanceof n,"Something is calling a React component directly. Use a factory or JSX instead. See: https://fb.me/react-legacyfactory"),this.__reactAutoBindPairs.length&&E(this),this.props=e,this.context=r,this.refs=a,this.updater=i||o,this.state=null;var u=this.getInitialState?this.getInitialState():null;"production"!==t.env.NODE_ENV&&void 0===u&&this.getInitialState._isMockFunction&&(u=null),s("object"==typeof u&&!Array.isArray(u),"%s.getInitialState(): must return an object or null",n.displayName||"ReactCompositeComponent"),this.state=u});n.prototype=new S,n.prototype.constructor=n,n.prototype.__reactAutoBindPairs=[],O.forEach(f.bind(null,n)),f(n,C),f(n,e),f(n,k),n.getDefaultProps&&(n.defaultProps=n.getDefaultProps()),"production"!==t.env.NODE_ENV&&(n.getDefaultProps&&(n.getDefaultProps.isReactClassApproved={}),n.prototype.getInitialState&&(n.prototype.getInitialState.isReactClassApproved={})),s(n.prototype.render,"createClass(...): Class specification must implement a `render` method."),"production"!==t.env.NODE_ENV&&(c(!n.prototype.componentShouldUpdate,"%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.",e.displayName||"A component"),c(!n.prototype.componentWillRecieveProps,"%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?",e.displayName||"A component"),c(!n.prototype.UNSAFE_componentWillRecieveProps,"%s has a method called UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?",e.displayName||"A component"));for(var i in w)n.prototype[i]||(n.prototype[i]=null);return n}var O=[],w={mixins:"DEFINE_MANY",statics:"DEFINE_MANY",propTypes:"DEFINE_MANY",contextTypes:"DEFINE_MANY",childContextTypes:"DEFINE_MANY",getDefaultProps:"DEFINE_MANY_MERGED",getInitialState:"DEFINE_MANY_MERGED",getChildContext:"DEFINE_MANY_MERGED",render:"DEFINE_ONCE",componentWillMount:"DEFINE_MANY",componentDidMount:"DEFINE_MANY",componentWillReceiveProps:"DEFINE_MANY",shouldComponentUpdate:"DEFINE_ONCE",componentWillUpdate:"DEFINE_MANY",componentDidUpdate:"DEFINE_MANY",componentWillUnmount:"DEFINE_MANY",UNSAFE_componentWillMount:"DEFINE_MANY",UNSAFE_componentWillReceiveProps:"DEFINE_MANY",UNSAFE_componentWillUpdate:"DEFINE_MANY",updateComponent:"OVERRIDE_BASE"},b={getDerivedStateFromProps:"DEFINE_MANY_MERGED"},N={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)f(e,t[n])},childContextTypes:function(e,n){"production"!==t.env.NODE_ENV&&p(e,n,"childContext"),e.childContextTypes=i({},e.childContextTypes,n)},contextTypes:function(e,n){"production"!==t.env.NODE_ENV&&p(e,n,"context"),e.contextTypes=i({},e.contextTypes,n)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=y(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,n){"production"!==t.env.NODE_ENV&&p(e,n,"prop"),e.propTypes=i({},e.propTypes,n)},statics:function(e,t){h(e,t)},autobind:function(){}},C={componentDidMount:function(){this.__isMounted=!0}},k={componentWillUnmount:function(){this.__isMounted=!1}},_={replaceState:function(e,t){this.updater.enqueueReplaceState(this,e,t)},isMounted:function(){return"production"!==t.env.NODE_ENV&&(c(this.__didWarnIsMounted,"%s: isMounted is deprecated. Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks.",this.constructor&&this.constructor.displayName||this.name||"Component"),this.__didWarnIsMounted=!0),!!this.__isMounted}},S=function(){};return i(S.prototype,e.prototype,_),D}var i=n(12),a=n(13),s=n(14);if("production"!==t.env.NODE_ENV)var c=n(15);var u,l="mixins";u="production"!==t.env.NODE_ENV?{prop:"prop",context:"context",childContext:"child context"}:{},e.exports=o}).call(t,n(3))},function(e,t){"use strict";function n(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function r(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;var r=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==r.join(""))return!1;var o={};return"abcdefghijklmnopqrst".split("").forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(i){return!1}}var o=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;e.exports=r()?Object.assign:function(e,t){for(var r,s,c=n(e),u=1;u<arguments.length;u++){r=Object(arguments[u]);for(var l in r)i.call(r,l)&&(c[l]=r[l]);if(o){s=o(r);for(var p=0;p<s.length;p++)a.call(r,s[p])&&(c[s[p]]=r[s[p]])}}return c}},function(e,t,n){(function(t){"use strict";var n={};"production"!==t.env.NODE_ENV&&Object.freeze(n),e.exports=n}).call(t,n(3))},function(e,t,n){(function(t){"use strict";function n(e,t,n,o,i,a,s,c){if(r(t),!e){var u;if(void 0===t)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,o,i,a,s,c],p=0;u=new Error(t.replace(/%s/g,function(){return l[p++]})),u.name="Invariant Violation"}throw u.framesToPop=1,u}}var r=function(e){};"production"!==t.env.NODE_ENV&&(r=function(e){if(void 0===e)throw new Error("invariant requires an error message argument")}),e.exports=n}).call(t,n(3))},function(e,t,n){(function(t){"use strict";var r=n(16),o=r;if("production"!==t.env.NODE_ENV){var i=function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var o=0,i="Warning: "+e.replace(/%s/g,function(){return n[o++]});"undefined"!=typeof console&&console.error(i);try{throw new Error(i)}catch(a){}};o=function(e,t){if(void 0===t)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(0!==t.indexOf("Failed Composite propType: ")&&!e){for(var n=arguments.length,r=Array(n>2?n-2:0),o=2;o<n;o++)r[o-2]=arguments[o];i.apply(void 0,[t].concat(r)); }}}e.exports=o}).call(t,n(3))},function(e,t){"use strict";function n(e){return function(){return e}}var r=function(){};r.thatReturns=n,r.thatReturnsFalse=n(!1),r.thatReturnsTrue=n(!0),r.thatReturnsNull=n(null),r.thatReturnsThis=function(){return this},r.thatReturnsArgument=function(e){return e},e.exports=r},function(e,n){e.exports=t},function(e,t,n){"use strict";var r=n(10),o=n(9),i=n(17),a=o({render:function(){var e,t=this.renderFooter(),n=this.props.viewDate,o=n.localeData();return e=[r.createElement("thead",{key:"th"},[r.createElement("tr",{key:"h"},[r.createElement("th",{key:"p",className:"rdtPrev",onClick:this.props.navigate(-1,"months")},r.createElement("span",{},"‹")),r.createElement("th",{key:"s",className:"rdtSwitch",onClick:this.props.showView("months"),colSpan:5,"data-value":this.props.viewDate.month()},o.months(n)+" "+n.year()),r.createElement("th",{key:"n",className:"rdtNext",onClick:this.props.navigate(1,"months")},r.createElement("span",{},"›"))]),r.createElement("tr",{key:"d"},this.getDaysOfWeek(o).map(function(e,t){return r.createElement("th",{key:e+t,className:"dow"},e)}))]),r.createElement("tbody",{key:"tb"},this.renderDays())],t&&e.push(t),r.createElement("div",{className:"rdtDays"},r.createElement("table",{},e))},getDaysOfWeek:function(e){var t=e._weekdaysMin,n=e.firstDayOfWeek(),r=[],o=0;return t.forEach(function(e){r[(7+o++-n)%7]=e}),r},renderDays:function(){var e,t,n,o,a=this.props.viewDate,s=this.props.selectedDate&&this.props.selectedDate.clone(),c=a.clone().subtract(1,"months"),u=a.year(),l=a.month(),p=[],d=[],f=this.props.renderDay||this.renderDay,h=this.props.isValidDate||this.alwaysValidDate;c.date(c.daysInMonth()).startOf("week");for(var m=c.clone().add(42,"d");c.isBefore(m);)e="rdtDay",o=c.clone(),n={key:c.format("M_D"),"data-value":c.date(),"data-month":l,"data-year":u},c.year()===u&&c.month()<l||c.year()<u?(e+=" rdtOld",n["data-month"]=c.month(),n["data-year"]=c.year()):(c.year()===u&&c.month()>l||c.year()>u)&&(e+=" rdtNew",n["data-month"]=c.month(),n["data-year"]=c.year()),s&&c.isSame(s,"day")&&(e+=" rdtActive"),c.isSame(i(),"day")&&(e+=" rdtToday"),t=!h(o,s),t&&(e+=" rdtDisabled"),n.className=e,t||(n.onClick=this.updateSelectedDate),d.push(f(n,o,s)),7===d.length&&(p.push(r.createElement("tr",{key:c.format("M_D")},d)),d=[]),c.add(1,"d");return p},updateSelectedDate:function(e){this.props.updateDate(e)},renderDay:function(e,t){return r.createElement("td",e,t.date())},renderFooter:function(){if(!this.props.timeFormat)return"";var e=this.props.selectedDate||this.props.viewDate;return r.createElement("tfoot",{key:"tf"},r.createElement("tr",{},r.createElement("td",{onClick:this.props.showView("time"),colSpan:7,className:"rdtTimeToggle"},e.format(this.props.timeFormat))))},alwaysValidDate:function(){return 1}});e.exports=a},function(e,t,n){"use strict";function r(e){return e.charAt(0).toUpperCase()+e.slice(1)}var o=n(10),i=n(9),a=i({render:function(){return o.createElement("div",{className:"rdtMonths"},[o.createElement("table",{key:"a"},o.createElement("thead",{},o.createElement("tr",{},[o.createElement("th",{key:"prev",className:"rdtPrev",onClick:this.props.navigate(-1,"years")},o.createElement("span",{},"‹")),o.createElement("th",{key:"year",className:"rdtSwitch",onClick:this.props.showView("years"),colSpan:2,"data-value":this.props.viewDate.year()},this.props.viewDate.year()),o.createElement("th",{key:"next",className:"rdtNext",onClick:this.props.navigate(1,"years")},o.createElement("span",{},"›"))]))),o.createElement("table",{key:"months"},o.createElement("tbody",{key:"b"},this.renderMonths()))])},renderMonths:function(){for(var e,t,n,r,i,a,s,c=this.props.selectedDate,u=this.props.viewDate.month(),l=this.props.viewDate.year(),p=[],d=0,f=[],h=this.props.renderMonth||this.renderMonth,m=this.props.isValidDate||this.alwaysValidDate,y=1;d<12;)e="rdtMonth",n=this.props.viewDate.clone().set({year:l,month:d,date:y}),i=n.endOf("month").date(),a=Array.from({length:i},function(e,t){return t+1}),s=a.find(function(e){var t=n.clone().set("date",e);return m(t)}),r=void 0===s,r&&(e+=" rdtDisabled"),c&&d===c.month()&&l===c.year()&&(e+=" rdtActive"),t={key:d,"data-value":d,className:e},r||(t.onClick=this.updateSelectedMonth),f.push(h(t,d,l,c&&c.clone())),4===f.length&&(p.push(o.createElement("tr",{key:u+"_"+p.length},f)),f=[]),d++;return p},updateSelectedMonth:function(e){this.props.updateDate(e)},renderMonth:function(e,t){var n=this.props.viewDate,i=n.localeData().monthsShort(n.month(t)),a=3,s=i.substring(0,a);return o.createElement("td",e,r(s))},alwaysValidDate:function(){return 1}});e.exports=a},function(e,t,n){"use strict";var r=n(10),o=n(9),i=o({render:function(){var e=10*parseInt(this.props.viewDate.year()/10,10);return r.createElement("div",{className:"rdtYears"},[r.createElement("table",{key:"a"},r.createElement("thead",{},r.createElement("tr",{},[r.createElement("th",{key:"prev",className:"rdtPrev",onClick:this.props.navigate(-10,"years")},r.createElement("span",{},"‹")),r.createElement("th",{key:"year",className:"rdtSwitch",onClick:this.props.showView("years"),colSpan:2},e+"-"+(e+9)),r.createElement("th",{key:"next",className:"rdtNext",onClick:this.props.navigate(10,"years")},r.createElement("span",{},"›"))]))),r.createElement("table",{key:"years"},r.createElement("tbody",{},this.renderYears(e)))])},renderYears:function(e){var t,n,o,i,a,s,c,u=[],l=-1,p=[],d=this.props.renderYear||this.renderYear,f=this.props.selectedDate,h=this.props.isValidDate||this.alwaysValidDate,m=0,y=1;for(e--;l<11;)t="rdtYear",o=this.props.viewDate.clone().set({year:e,month:m,date:y}),a=o.endOf("year").dayOfYear(),s=Array.from({length:a},function(e,t){return t+1}),c=s.find(function(e){var t=o.clone().dayOfYear(e);return h(t)}),i=void 0===c,i&&(t+=" rdtDisabled"),f&&f.year()===e&&(t+=" rdtActive"),n={key:e,"data-value":e,className:t},i||(n.onClick=this.updateSelectedYear),u.push(d(n,e,f&&f.clone())),4===u.length&&(p.push(r.createElement("tr",{key:l},u)),u=[]),e++,l++;return p},updateSelectedYear:function(e){this.props.updateDate(e)},renderYear:function(e,t){return r.createElement("td",e,t)},alwaysValidDate:function(){return 1}});e.exports=i},function(e,t,n){"use strict";var r=n(10),o=n(9),i=n(1),a=o({getInitialState:function(){return this.calculateState(this.props)},calculateState:function(e){var t=e.selectedDate||e.viewDate,n=e.timeFormat,r=[];n.toLowerCase().indexOf("h")!==-1&&(r.push("hours"),n.indexOf("m")!==-1&&(r.push("minutes"),n.indexOf("s")!==-1&&r.push("seconds")));var o=t.hours(),i=!1;return null!==this.state&&this.props.timeFormat.toLowerCase().indexOf(" a")!==-1&&(i=this.props.timeFormat.indexOf(" A")!==-1?o>=12?"PM":"AM":o>=12?"pm":"am"),{hours:this.pad("hours",o),minutes:this.pad("minutes",t.minutes()),seconds:this.pad("seconds",t.seconds()),milliseconds:this.pad("milliseconds",t.milliseconds()),daypart:i,counters:r}},renderCounter:function(e){if("daypart"!==e){var t=this.state[e];return"hours"===e&&this.props.timeFormat.toLowerCase().indexOf(" a")!==-1&&(t=(t-1)%12+1,0===t&&(t=12)),r.createElement("div",{key:e,className:"rdtCounter"},[r.createElement("span",{key:"up",className:"rdtBtn",onMouseDown:this.onStartClicking("increase",e)},"▲"),r.createElement("div",{key:"c",className:"rdtCount"},t),r.createElement("span",{key:"do",className:"rdtBtn",onMouseDown:this.onStartClicking("decrease",e)},"▼")])}return""},renderDayPart:function(){return r.createElement("div",{key:"dayPart",className:"rdtCounter"},[r.createElement("span",{key:"up",className:"rdtBtn",onMouseDown:this.onStartClicking("toggleDayPart","hours")},"▲"),r.createElement("div",{key:this.state.daypart,className:"rdtCount"},this.state.daypart),r.createElement("span",{key:"do",className:"rdtBtn",onMouseDown:this.onStartClicking("toggleDayPart","hours")},"▼")])},render:function(){var e=this,t=[];return this.state.counters.forEach(function(n){t.length&&t.push(r.createElement("div",{key:"sep"+t.length,className:"rdtCounterSeparator"},":")),t.push(e.renderCounter(n))}),this.state.daypart!==!1&&t.push(e.renderDayPart()),3===this.state.counters.length&&this.props.timeFormat.indexOf("S")!==-1&&(t.push(r.createElement("div",{className:"rdtCounterSeparator",key:"sep5"},":")),t.push(r.createElement("div",{className:"rdtCounter rdtMilli",key:"m"},r.createElement("input",{value:this.state.milliseconds,type:"text",onChange:this.updateMilli})))),r.createElement("div",{className:"rdtTime"},r.createElement("table",{},[this.renderHeader(),r.createElement("tbody",{key:"b"},r.createElement("tr",{},r.createElement("td",{},r.createElement("div",{className:"rdtCounters"},t))))]))},componentWillMount:function(){var e=this;e.timeConstraints={hours:{min:0,max:23,step:1},minutes:{min:0,max:59,step:1},seconds:{min:0,max:59,step:1},milliseconds:{min:0,max:999,step:1}},["hours","minutes","seconds","milliseconds"].forEach(function(t){i(e.timeConstraints[t],e.props.timeConstraints[t])}),this.setState(this.calculateState(this.props))},componentWillReceiveProps:function(e){this.setState(this.calculateState(e))},updateMilli:function(e){var t=parseInt(e.target.value,10);t===e.target.value&&t>=0&&t<1e3&&(this.props.setTime("milliseconds",t),this.setState({milliseconds:t}))},renderHeader:function(){if(!this.props.dateFormat)return null;var e=this.props.selectedDate||this.props.viewDate;return r.createElement("thead",{key:"h"},r.createElement("tr",{},r.createElement("th",{className:"rdtSwitch",colSpan:4,onClick:this.props.showView("days")},e.format(this.props.dateFormat))))},onStartClicking:function(e,t){var n=this;return function(r){if(!r||!r.button||0===r.button){var o={};o[t]=n[e](t),n.setState(o),n.timer=setTimeout(function(){n.increaseTimer=setInterval(function(){o[t]=n[e](t),n.setState(o)},70)},500),n.mouseUpListener=function(){clearTimeout(n.timer),clearInterval(n.increaseTimer),n.props.setTime(t,n.state[t]),document.body.removeEventListener("mouseup",n.mouseUpListener),document.body.removeEventListener("touchend",n.mouseUpListener)},document.body.addEventListener("mouseup",n.mouseUpListener),document.body.addEventListener("touchend",n.mouseUpListener)}}},padValues:{hours:1,minutes:2,seconds:2,milliseconds:3},toggleDayPart:function(e){var t=parseInt(this.state[e],10)+12,n=this.timeConstraints[e];return t>n.max&&(t=n.min+(t-(n.max+1))),this.pad(e,t)},increase:function(e){var t=this.timeConstraints[e],n=parseInt(this.state[e],10)+t.step;return n>t.max&&(n=t.min+(n-(t.max+1))),this.pad(e,n)},decrease:function(e){var t=this.timeConstraints[e],n=parseInt(this.state[e],10)-t.step;return n<t.min&&(n=t.max+1-(t.min-n)),this.pad(e,n)},pad:function(e,t){for(var n=t+"";n.length<this.padValues[e];)n="0"+n;return n}});e.exports=a},function(e,t,n){"use strict";function r(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}function o(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||(o[n]=e[n]);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function i(e,t,n){return e===t||(e.correspondingElement?e.correspondingElement.classList.contains(n):e.classList.contains(n))}function a(e,t,n){if(e===t)return!0;for(;e.parentNode;){if(i(e,t,n))return!0;e=e.parentNode}return e}function s(e){return document.documentElement.clientWidth<=e.clientX||document.documentElement.clientHeight<=e.clientY}function c(e){return void 0===e&&(e=0),function(){return++e}}function u(e,t){var n=null,r=g.indexOf(t)!==-1;return r&&p&&(n={passive:!e.props.preventDefault}),n}function l(e,t){var n,i;return i=n=function(n){function i(e){var t;return t=n.call(this,e)||this,t.__outsideClickHandler=function(e){if("function"==typeof t.__clickOutsideHandlerProp)return void t.__clickOutsideHandlerProp(e);var n=t.getInstance();if("function"==typeof n.props.handleClickOutside)return void n.props.handleClickOutside(e);if("function"==typeof n.handleClickOutside)return void n.handleClickOutside(e);throw new Error("WrappedComponent lacks a handleClickOutside(event) function for processing outside click events.")},t.enableOnClickOutside=function(){if("undefined"!=typeof document&&!v[t._uid]){"undefined"==typeof p&&(p=h()),v[t._uid]=!0;var e=t.props.eventTypes;e.forEach||(e=[e]),y[t._uid]=function(e){if(!t.props.disableOnClickOutside&&null!==t.componentNode&&(t.props.preventDefault&&e.preventDefault(),t.props.stopPropagation&&e.stopPropagation(),!t.props.excludeScrollbar||!s(e))){var n=e.target;a(n,t.componentNode,t.props.outsideClickIgnoreClass)===document&&t.__outsideClickHandler(e)}},e.forEach(function(e){document.addEventListener(e,y[t._uid],u(t,e))})}},t.disableOnClickOutside=function(){delete v[t._uid];var e=y[t._uid];if(e&&"undefined"!=typeof document){var n=t.props.eventTypes;n.forEach||(n=[n]),n.forEach(function(n){return document.removeEventListener(n,e,u(t,n))}),delete y[t._uid]}},t.getRef=function(e){return t.instanceRef=e},t._uid=m(),t}r(i,n);var c=i.prototype;return c.getInstance=function(){if(!e.prototype.isReactComponent)return this;var t=this.instanceRef;return t.getInstance?t.getInstance():t},c.componentDidMount=function(){if("undefined"!=typeof document&&document.createElement){var e=this.getInstance();if(t&&"function"==typeof t.handleClickOutside&&(this.__clickOutsideHandlerProp=t.handleClickOutside(e),"function"!=typeof this.__clickOutsideHandlerProp))throw new Error("WrappedComponent lacks a function for processing outside click events specified by the handleClickOutside config option.");this.componentNode=f.findDOMNode(this.getInstance()),this.enableOnClickOutside()}},c.componentDidUpdate=function(){this.componentNode=f.findDOMNode(this.getInstance())},c.componentWillUnmount=function(){this.disableOnClickOutside()},c.render=function(){var t=this.props,n=(t.excludeScrollbar,o(t,["excludeScrollbar"]));return e.prototype.isReactComponent?n.ref=this.getRef:n.wrappedRef=this.getRef,n.disableOnClickOutside=this.disableOnClickOutside,n.enableOnClickOutside=this.enableOnClickOutside,d.createElement(e,n)},i}(d.Component),n.displayName="OnClickOutside("+(e.displayName||e.name||"Component")+")",n.defaultProps={eventTypes:["mousedown","touchstart"],excludeScrollbar:t&&t.excludeScrollbar||!1,outsideClickIgnoreClass:E,preventDefault:!1,stopPropagation:!1},n.getClass=function(){return e.getClass?e.getClass():e},i}Object.defineProperty(t,"__esModule",{value:!0});var p,d=n(10),f=n(23),h=function(){if("undefined"!=typeof window&&"function"==typeof window.addEventListener){var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}}),n=function(){};return window.addEventListener("testPassiveEventSupport",n,t),window.removeEventListener("testPassiveEventSupport",n,t),e}},m=c(),y={},v={},g=["touchstart","touchmove"],E="ignore-react-onclickoutside";t.IGNORE_CLASS_NAME=E,t["default"]=l},function(e,t){e.exports=n}])}); //# sourceMappingURL=react-datetime.min.js.map
client_src/component/UserNotLoged.js
frauca/votelist
import React from 'react' /** * it will always be called on first instance if user is loged and action will be launch to change the user **/ class UserNotLoged extends React.Component{ constructor(props) { super(props); } onFailure(error) { console.log(error); } renderButton() { console.log('Set google button'); let logUser=this.props.userLoged; gapi.signin2.render('googleSigIn', { 'scope': 'profile email', 'width': 240, 'height': 50, 'longtitle': true, 'theme': 'dark', 'onsuccess': this.onSuccess.bind(this), 'onfailure': this.onFailure }); } onSuccess(googleUser) { console.log('Logged in as: ' + googleUser.getBasicProfile().getName()); this.props.userLoged(googleUser); } componentDidMount(){ console.log('Load Googles api login'); let notLogedComponent=this; $.getScript( "https://apis.google.com/js/platform.js" ) .done(function( script, textStatus ) { notLogedComponent.renderButton(); }) .fail(function( jqxhr, settings, exception ) { console.log('ERROR NO LOGIN COULD BE DONE'); }); } componentDidUpdate(){ console.log('Did update'); } render(){ return <div id="googleSigIn"></div> } } export default UserNotLoged
packages/material-ui-icons/src/Gif.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M11.5 9H13v6h-1.5zM9 9H6c-.6 0-1 .5-1 1v4c0 .5.4 1 1 1h3c.6 0 1-.5 1-1v-2H8.5v1.5h-2v-3H10V10c0-.5-.4-1-1-1zm10 1.5V9h-4.5v6H16v-2h2v-1.5h-2v-1z" /></g> , 'Gif');
DEM_MVC_UI/src/scripts/containers/TermItem/test.js
AndreyShpilevoy/DemProject
/*eslint no-undef: "off"*/ /* eslint import/no-extraneous-dependencies: "off" */ import React from 'react'; import {shallow} from 'enzyme'; import {sharedFakeStore, validFakeStoreData} from 'store/__mocks__/sharedFakeStore'; import TermItem from './index'; jest.mock('../../services/translations/TermTranslation', ()=>({ getTermTranslation: ()=>('TestTerm') })); describe('TermItem', () => { function setup(mockConfigId){ const props = { store: sharedFakeStore(mockConfigId), term: { id: 1, value: 'TestTermDefault' } }; return shallow(<TermItem {...props}/>); } it('should get "currentLocale.locale" from "localeReducer" and recieve expected result', () => { expect(setup(1).prop('locale')).toEqual(validFakeStoreData.localeReducer.currentLocale.locale); }); it('should get "currentLocale.locale" from "localeReducer" and recieve "eng"', () => { expect(setup(0).prop('locale')).toEqual('eng'); }); it('should create TermItem component with props.term equal to "TestTerm"', () => { expect(setup(1).shallow().prop('spanContent')).toEqual('TestTerm'); }); });
src/renderer/components/MapFilter/ExportButton.js
digidem/ecuador-map-editor
import React from 'react' import IconButton from '@material-ui/core/IconButton' import Tooltip from '@material-ui/core/Tooltip' import ExportIcon from '@material-ui/icons/MoreVert' import { defineMessages, useIntl, FormattedMessage } from 'react-intl' import Menu from '@material-ui/core/Menu' import MenuItem from '@material-ui/core/MenuItem' const m = defineMessages({ exportButton: 'Export Observation Data', exportMap: 'Export Webmap…', exportData: 'Export Observations…' }) const ExportButton = ({ onExport }) => { const { formatMessage: t } = useIntl() const [menuAnchor, setMenuAnchor] = React.useState(null) const handleExportClick = event => { setMenuAnchor(event.currentTarget) } const handleMenuItemClick = id => () => { setMenuAnchor(null) if (id) onExport(id) } return ( <> <Tooltip title={t(m.exportButton)}> <IconButton aria-label='export' color='inherit' onClick={handleExportClick} aria-controls='export-menu' aria-haspopup='true' > <ExportIcon /> </IconButton> </Tooltip> <Menu id='export-menu' anchorEl={menuAnchor} open={Boolean(menuAnchor)} onClose={handleMenuItemClick(null)} > <MenuItem onClick={handleMenuItemClick('map')}> <FormattedMessage {...m.exportMap} /> </MenuItem> <MenuItem onClick={handleMenuItemClick('data')}> <FormattedMessage {...m.exportData} /> </MenuItem> </Menu> </> ) } export default ExportButton
src/routes/error/ErrorPage.js
jtiscione/redux-chess
/** * 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 PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './ErrorPage.css'; class ErrorPage extends React.Component { static propTypes = { error: PropTypes.shape({ name: PropTypes.string.isRequired, message: PropTypes.string.isRequired, stack: PropTypes.string.isRequired, }).isRequired, }; render() { if (__DEV__) { const { error } = this.props; return ( <div> <h1>{error.name}</h1> <p>{error.message}</p> <pre>{error.stack}</pre> </div> ); } return ( <div> <h1>Error</h1> <p>Sorry, a critical error occurred on this page.</p> </div> ); } } export { ErrorPage as ErrorPageWithoutStyle }; export default withStyles(s)(ErrorPage);
src/components/page-number-pager.js
zooniverse-ui/pagerz
import React from 'react'; import BasicPager from './basic-pager'; export default class PageNumberPager extends BasicPager { get displayName() { return 'Paginator'; } getPage(activePage, previous) { super.getPage(activePage, previous); if (this.props.scrollOnChange) { window.scrollTo(0,0); } } onSelectPage(e) { let selectedPage = this.refs.pageSelect.getDOMNode().value; let previous = false; if (selectedPage < this.props.currentPage) { previous = true; } this.getPage(selectedPage, previous); } pageOption(n, i) { return (<option key={i} value={n+1}> {n+1} </option>); } firstButton(page) { if (this.props.firstAndLast) { return (<button className="paginator-first" onClick={() => this.getPage(1, true)} disabled={page === 1}> <i className="fa fa-fast-backward" /> First </button> ); } else { return null; } } lastButton(page, pageCount) { if (this.props.firstAndLast) { return ( <button className="paginator-last" onClick={this.getPage.bind(this, pageCount, false)} disabled={page === pageCount}> Last <i className="fa fa-fast-forward" /> </button> ); } else { return null; } } render() { let {currentPage, pageCount} = this.props; return(<div className="paginator"> {super.render()} {this.firstButton(currentPage)} <button className="paginator-prev" onClick={this.getPage.bind(this, this.props.currentPage - 1, true)} disabled={currentPage === 1}> <i className="fa fa-long-arrow-left" /> Previous </button> <div className="paginator-page-selector"> Page&nbsp; <select value={currentPage} onChange={this.onSelectPage} ref="pageSelect"> {Array.from(Array(pageCount).keys()).map(this.pageOption)} </select> of {pageCount} </div> <button className="paginator-next" onClick={this.getPage.bind(this, this.props.currentPage + 1, false)} disabled={currentPage === pageCount}> Next <i className="fa fa-long-arrow-right" /> </button> {this.lastButton(currentPage, pageCount)} </div>); } }; PageNumberPager.defaultProps = Object.assign({}, BasicPager.getDefaultProps(), { firstAndLast: true, scrollOnChange: true }); //PageNumberPager.propTypes = { //pageCount: React.PropTypes.number, //page: React.PropTypes.number, // page number //onPageChange: React.PropTypes.func.isRequired, // passed (page) on change //firstAndLast: React.PropTypes.bool, // optional, add 'first' & 'last' buttons //scrollOnChange: React.PropTypes.bool // optional, scroll to top of page on change //};
examples/js/column/column-align-table.js
echaouchna/react-bootstrap-tab
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); export default class ColumnAlignTable extends React.Component { render() { return ( <BootstrapTable data={ products }> <TableHeaderColumn dataField='id' isKey={ true } dataAlign='center'>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name' headerAlign='right'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price' headerAlign='center' dataAlign='right'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
ajax/libs/analytics.js/1.3.6/analytics.js
him2him2/cdnjs
;(function(){ /** * Require the given path. * * @param {String} path * @return {Object} exports * @api public */ function require(path, parent, orig) { var resolved = require.resolve(path); // lookup failed if (null == resolved) { orig = orig || path; parent = parent || 'root'; var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); err.path = orig; err.parent = parent; err.require = true; throw err; } var module = require.modules[resolved]; // perform real require() // by invoking the module's // registered function if (!module._resolving && !module.exports) { var mod = {}; mod.exports = {}; mod.client = mod.component = true; module._resolving = true; module.call(this, mod.exports, require.relative(resolved), mod); delete module._resolving; module.exports = mod.exports; } return module.exports; } /** * Registered modules. */ require.modules = {}; /** * Registered aliases. */ require.aliases = {}; /** * Resolve `path`. * * Lookup: * * - PATH/index.js * - PATH.js * - PATH * * @param {String} path * @return {String} path or null * @api private */ require.resolve = function(path) { if (path.charAt(0) === '/') path = path.slice(1); var paths = [ path, path + '.js', path + '.json', path + '/index.js', path + '/index.json' ]; for (var i = 0; i < paths.length; i++) { var path = paths[i]; if (require.modules.hasOwnProperty(path)) return path; if (require.aliases.hasOwnProperty(path)) return require.aliases[path]; } }; /** * Normalize `path` relative to the current path. * * @param {String} curr * @param {String} path * @return {String} * @api private */ require.normalize = function(curr, path) { var segs = []; if ('.' != path.charAt(0)) return path; curr = curr.split('/'); path = path.split('/'); for (var i = 0; i < path.length; ++i) { if ('..' == path[i]) { curr.pop(); } else if ('.' != path[i] && '' != path[i]) { segs.push(path[i]); } } return curr.concat(segs).join('/'); }; /** * Register module at `path` with callback `definition`. * * @param {String} path * @param {Function} definition * @api private */ require.register = function(path, definition) { require.modules[path] = definition; }; /** * Alias a module definition. * * @param {String} from * @param {String} to * @api private */ require.alias = function(from, to) { if (!require.modules.hasOwnProperty(from)) { throw new Error('Failed to alias "' + from + '", it does not exist'); } require.aliases[to] = from; }; /** * Return a require function relative to the `parent` path. * * @param {String} parent * @return {Function} * @api private */ require.relative = function(parent) { var p = require.normalize(parent, '..'); /** * lastIndexOf helper. */ function lastIndexOf(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) return i; } return -1; } /** * The relative require() itself. */ function localRequire(path) { var resolved = localRequire.resolve(path); return require(resolved, parent, path); } /** * Resolve relative to the parent. */ localRequire.resolve = function(path) { var c = path.charAt(0); if ('/' == c) return path.slice(1); if ('.' == c) return require.normalize(p, path); // resolve deps by returning // the dep in the nearest "deps" // directory var segs = parent.split('/'); var i = lastIndexOf(segs, 'deps') + 1; if (!i) i = 0; path = segs.slice(0, i + 1).join('/') + '/deps/' + path; return path; }; /** * Check if module is defined at `path`. */ localRequire.exists = function(path) { return require.modules.hasOwnProperty(localRequire.resolve(path)); }; return localRequire; }; require.register("avetisk-defaults/index.js", function(exports, require, module){ 'use strict'; /** * Merge default values. * * @param {Object} dest * @param {Object} defaults * @return {Object} * @api public */ var defaults = function (dest, src, recursive) { for (var prop in src) { if (recursive && dest[prop] instanceof Object && src[prop] instanceof Object) { dest[prop] = defaults(dest[prop], src[prop], true); } else if (! (prop in dest)) { dest[prop] = src[prop]; } } return dest; }; /** * Expose `defaults`. */ module.exports = defaults; }); require.register("component-type/index.js", function(exports, require, module){ /** * toString ref. */ var toString = Object.prototype.toString; /** * Return the type of `val`. * * @param {Mixed} val * @return {String} * @api public */ module.exports = function(val){ switch (toString.call(val)) { case '[object Function]': return 'function'; case '[object Date]': return 'date'; case '[object RegExp]': return 'regexp'; case '[object Arguments]': return 'arguments'; case '[object Array]': return 'array'; case '[object String]': return 'string'; } if (val === null) return 'null'; if (val === undefined) return 'undefined'; if (val && val.nodeType === 1) return 'element'; if (val === Object(val)) return 'object'; return typeof val; }; }); require.register("component-clone/index.js", function(exports, require, module){ /** * Module dependencies. */ var type; try { type = require('type'); } catch(e){ type = require('type-component'); } /** * Module exports. */ module.exports = clone; /** * Clones objects. * * @param {Mixed} any object * @api public */ function clone(obj){ switch (type(obj)) { case 'object': var copy = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { copy[key] = clone(obj[key]); } } return copy; case 'array': var copy = new Array(obj.length); for (var i = 0, l = obj.length; i < l; i++) { copy[i] = clone(obj[i]); } return copy; case 'regexp': // from millermedeiros/amd-utils - MIT var flags = ''; flags += obj.multiline ? 'm' : ''; flags += obj.global ? 'g' : ''; flags += obj.ignoreCase ? 'i' : ''; return new RegExp(obj.source, flags); case 'date': return new Date(obj.getTime()); default: // string, number, boolean, … return obj; } } }); require.register("component-cookie/index.js", function(exports, require, module){ /** * Encode. */ var encode = encodeURIComponent; /** * Decode. */ var decode = decodeURIComponent; /** * Set or get cookie `name` with `value` and `options` object. * * @param {String} name * @param {String} value * @param {Object} options * @return {Mixed} * @api public */ module.exports = function(name, value, options){ switch (arguments.length) { case 3: case 2: return set(name, value, options); case 1: return get(name); default: return all(); } }; /** * Set cookie `name` to `value`. * * @param {String} name * @param {String} value * @param {Object} options * @api private */ function set(name, value, options) { options = options || {}; var str = encode(name) + '=' + encode(value); if (null == value) options.maxage = -1; if (options.maxage) { options.expires = new Date(+new Date + options.maxage); } if (options.path) str += '; path=' + options.path; if (options.domain) str += '; domain=' + options.domain; if (options.expires) str += '; expires=' + options.expires.toGMTString(); if (options.secure) str += '; secure'; document.cookie = str; } /** * Return all cookies. * * @return {Object} * @api private */ function all() { return parse(document.cookie); } /** * Get cookie `name`. * * @param {String} name * @return {String} * @api private */ function get(name) { return all()[name]; } /** * Parse cookie `str`. * * @param {String} str * @return {Object} * @api private */ function parse(str) { var obj = {}; var pairs = str.split(/ *; */); var pair; if ('' == pairs[0]) return obj; for (var i = 0; i < pairs.length; ++i) { pair = pairs[i].split('='); obj[decode(pair[0])] = decode(pair[1]); } return obj; } }); require.register("component-each/index.js", function(exports, require, module){ /** * Module dependencies. */ var type = require('type'); /** * HOP reference. */ var has = Object.prototype.hasOwnProperty; /** * Iterate the given `obj` and invoke `fn(val, i)`. * * @param {String|Array|Object} obj * @param {Function} fn * @api public */ module.exports = function(obj, fn){ switch (type(obj)) { case 'array': return array(obj, fn); case 'object': if ('number' == typeof obj.length) return array(obj, fn); return object(obj, fn); case 'string': return string(obj, fn); } }; /** * Iterate string chars. * * @param {String} obj * @param {Function} fn * @api private */ function string(obj, fn) { for (var i = 0; i < obj.length; ++i) { fn(obj.charAt(i), i); } } /** * Iterate object keys. * * @param {Object} obj * @param {Function} fn * @api private */ function object(obj, fn) { for (var key in obj) { if (has.call(obj, key)) { fn(key, obj[key]); } } } /** * Iterate array-ish. * * @param {Array|Object} obj * @param {Function} fn * @api private */ function array(obj, fn) { for (var i = 0; i < obj.length; ++i) { fn(obj[i], i); } } }); require.register("component-indexof/index.js", function(exports, require, module){ module.exports = function(arr, obj){ if (arr.indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; }); require.register("component-emitter/index.js", function(exports, require, module){ /** * Module dependencies. */ var index = require('indexof'); /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } fn._off = on; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var i = index(callbacks, fn._off || fn); if (~i) callbacks.splice(i, 1); return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; }); require.register("component-event/index.js", function(exports, require, module){ /** * Bind `el` event `type` to `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.bind = function(el, type, fn, capture){ if (el.addEventListener) { el.addEventListener(type, fn, capture || false); } else { el.attachEvent('on' + type, fn); } return fn; }; /** * Unbind `el` event `type`'s callback `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.unbind = function(el, type, fn, capture){ if (el.removeEventListener) { el.removeEventListener(type, fn, capture || false); } else { el.detachEvent('on' + type, fn); } return fn; }; }); require.register("component-inherit/index.js", function(exports, require, module){ module.exports = function(a, b){ var fn = function(){}; fn.prototype = b.prototype; a.prototype = new fn; a.prototype.constructor = a; }; }); require.register("component-object/index.js", function(exports, require, module){ /** * HOP ref. */ var has = Object.prototype.hasOwnProperty; /** * Return own keys in `obj`. * * @param {Object} obj * @return {Array} * @api public */ exports.keys = Object.keys || function(obj){ var keys = []; for (var key in obj) { if (has.call(obj, key)) { keys.push(key); } } return keys; }; /** * Return own values in `obj`. * * @param {Object} obj * @return {Array} * @api public */ exports.values = function(obj){ var vals = []; for (var key in obj) { if (has.call(obj, key)) { vals.push(obj[key]); } } return vals; }; /** * Merge `b` into `a`. * * @param {Object} a * @param {Object} b * @return {Object} a * @api public */ exports.merge = function(a, b){ for (var key in b) { if (has.call(b, key)) { a[key] = b[key]; } } return a; }; /** * Return length of `obj`. * * @param {Object} obj * @return {Number} * @api public */ exports.length = function(obj){ return exports.keys(obj).length; }; /** * Check if `obj` is empty. * * @param {Object} obj * @return {Boolean} * @api public */ exports.isEmpty = function(obj){ return 0 == exports.length(obj); }; }); require.register("component-trim/index.js", function(exports, require, module){ exports = module.exports = trim; function trim(str){ if (str.trim) return str.trim(); return str.replace(/^\s*|\s*$/g, ''); } exports.left = function(str){ if (str.trimLeft) return str.trimLeft(); return str.replace(/^\s*/, ''); }; exports.right = function(str){ if (str.trimRight) return str.trimRight(); return str.replace(/\s*$/, ''); }; }); require.register("component-querystring/index.js", function(exports, require, module){ /** * Module dependencies. */ var trim = require('trim'); /** * Parse the given query `str`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(str){ if ('string' != typeof str) return {}; str = trim(str); if ('' == str) return {}; var obj = {}; var pairs = str.split('&'); for (var i = 0; i < pairs.length; i++) { var parts = pairs[i].split('='); obj[parts[0]] = null == parts[1] ? '' : decodeURIComponent(parts[1]); } return obj; }; /** * Stringify the given `obj`. * * @param {Object} obj * @return {String} * @api public */ exports.stringify = function(obj){ if (!obj) return ''; var pairs = []; for (var key in obj) { pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])); } return pairs.join('&'); }; }); require.register("component-url/index.js", function(exports, require, module){ /** * Parse the given `url`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(url){ var a = document.createElement('a'); a.href = url; return { href: a.href, host: a.host, port: a.port, hash: a.hash, hostname: a.hostname, pathname: a.pathname, protocol: a.protocol, search: a.search, query: a.search.slice(1) } }; /** * Check if `url` is absolute. * * @param {String} url * @return {Boolean} * @api public */ exports.isAbsolute = function(url){ if (0 == url.indexOf('//')) return true; if (~url.indexOf('://')) return true; return false; }; /** * Check if `url` is relative. * * @param {String} url * @return {Boolean} * @api public */ exports.isRelative = function(url){ return ! exports.isAbsolute(url); }; /** * Check if `url` is cross domain. * * @param {String} url * @return {Boolean} * @api public */ exports.isCrossDomain = function(url){ url = exports.parse(url); return url.hostname != location.hostname || url.port != location.port || url.protocol != location.protocol; }; }); require.register("component-bind/index.js", function(exports, require, module){ /** * Slice reference. */ var slice = [].slice; /** * Bind `obj` to `fn`. * * @param {Object} obj * @param {Function|String} fn or string * @return {Function} * @api public */ module.exports = function(obj, fn){ if ('string' == typeof fn) fn = obj[fn]; if ('function' != typeof fn) throw new Error('bind() requires a function'); var args = slice.call(arguments, 2); return function(){ return fn.apply(obj, args.concat(slice.call(arguments))); } }; }); require.register("segmentio-bind-all/index.js", function(exports, require, module){ try { var bind = require('bind'); var type = require('type'); } catch (e) { var bind = require('bind-component'); var type = require('type-component'); } module.exports = function (obj) { for (var key in obj) { var val = obj[key]; if (type(val) === 'function') obj[key] = bind(obj, obj[key]); } return obj; }; }); require.register("ianstormtaylor-bind/index.js", function(exports, require, module){ try { var bind = require('bind'); } catch (e) { var bind = require('bind-component'); } var bindAll = require('bind-all'); /** * Expose `bind`. */ module.exports = exports = bind; /** * Expose `bindAll`. */ exports.all = bindAll; /** * Expose `bindMethods`. */ exports.methods = bindMethods; /** * Bind `methods` on `obj` to always be called with the `obj` as context. * * @param {Object} obj * @param {String} methods... */ function bindMethods (obj, methods) { methods = [].slice.call(arguments, 1); for (var i = 0, method; method = methods[i]; i++) { obj[method] = bind(obj, obj[method]); } return obj; } }); require.register("timoxley-next-tick/index.js", function(exports, require, module){ "use strict" if (typeof setImmediate == 'function') { module.exports = function(f){ setImmediate(f) } } // legacy node.js else if (typeof process != 'undefined' && typeof process.nextTick == 'function') { module.exports = process.nextTick } // fallback for other environments / postMessage behaves badly on IE8 else if (typeof window == 'undefined' || window.ActiveXObject || !window.postMessage) { module.exports = function(f){ setTimeout(f) }; } else { var q = []; window.addEventListener('message', function(){ var i = 0; while (i < q.length) { try { q[i++](); } catch (e) { q = q.slice(i); window.postMessage('tic!', '*'); throw e; } } q.length = 0; }, true); module.exports = function(fn){ if (!q.length) window.postMessage('tic!', '*'); q.push(fn); } } }); require.register("ianstormtaylor-callback/index.js", function(exports, require, module){ var next = require('next-tick'); /** * Expose `callback`. */ module.exports = callback; /** * Call an `fn` back synchronously if it exists. * * @param {Function} fn */ function callback (fn) { if ('function' === typeof fn) fn(); } /** * Call an `fn` back asynchronously if it exists. If `wait` is ommitted, the * `fn` will be called on next tick. * * @param {Function} fn * @param {Number} wait (optional) */ callback.async = function (fn, wait) { if ('function' !== typeof fn) return; if (!wait) return next(fn); setTimeout(fn, wait); }; /** * Symmetry. */ callback.sync = callback; }); require.register("ianstormtaylor-is-empty/index.js", function(exports, require, module){ /** * Expose `isEmpty`. */ module.exports = isEmpty; /** * Has. */ var has = Object.prototype.hasOwnProperty; /** * Test whether a value is "empty". * * @param {Mixed} val * @return {Boolean} */ function isEmpty (val) { if (null == val) return true; if ('number' == typeof val) return 0 === val; if (undefined !== val.length) return 0 === val.length; for (var key in val) if (has.call(val, key)) return false; return true; } }); require.register("ianstormtaylor-is/index.js", function(exports, require, module){ var isEmpty = require('is-empty'); try { var typeOf = require('type'); } catch (e) { var typeOf = require('component-type'); } /** * Types. */ var types = [ 'arguments', 'array', 'boolean', 'date', 'element', 'function', 'null', 'number', 'object', 'regexp', 'string', 'undefined' ]; /** * Expose type checkers. * * @param {Mixed} value * @return {Boolean} */ for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type); /** * Add alias for `function` for old browsers. */ exports.fn = exports['function']; /** * Expose `empty` check. */ exports.empty = isEmpty; /** * Expose `nan` check. */ exports.nan = function (val) { return exports.number(val) && val != val; }; /** * Generate a type checker. * * @param {String} type * @return {Function} */ function generate (type) { return function (value) { return type === typeOf(value); }; } }); require.register("segmentio-after/index.js", function(exports, require, module){ module.exports = function after (times, func) { // After 0, really? if (times <= 0) return func(); // That's more like it. return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; }); require.register("yields-slug/index.js", function(exports, require, module){ /** * Generate a slug from the given `str`. * * example: * * generate('foo bar'); * // > foo-bar * * @param {String} str * @param {Object} options * @config {String|RegExp} [replace] characters to replace, defaulted to `/[^a-z0-9]/g` * @config {String} [separator] separator to insert, defaulted to `-` * @return {String} */ module.exports = function (str, options) { options || (options = {}); return str.toLowerCase() .replace(options.replace || /[^a-z0-9]/g, ' ') .replace(/^ +| +$/g, '') .replace(/ +/g, options.separator || '-') }; }); require.register("segmentio-analytics.js-integration/lib/index.js", function(exports, require, module){ var bind = require('bind'); var callback = require('callback'); var clone = require('clone'); var debug = require('debug'); var defaults = require('defaults'); var protos = require('./protos'); var slug = require('slug'); var statics = require('./statics'); /** * Expose `createIntegration`. */ module.exports = createIntegration; /** * Create a new Integration constructor. * * @param {String} name */ function createIntegration (name) { /** * Initialize a new `Integration`. * * @param {Object} options */ function Integration (options) { this.debug = debug('analytics:integration:' + slug(name)); this.options = defaults(clone(options) || {}, this.defaults); this._queue = []; this.once('ready', bind(this, this.flush)); Integration.emit('construct', this); this._wrapInitialize(); this._wrapLoad(); this._wrapPage(); this._wrapTrack(); } Integration.prototype.defaults = {}; Integration.prototype.globals = []; Integration.prototype.name = name; for (var key in statics) Integration[key] = statics[key]; for (var key in protos) Integration.prototype[key] = protos[key]; return Integration; } }); require.register("segmentio-analytics.js-integration/lib/protos.js", function(exports, require, module){ var after = require('after'); var callback = require('callback'); var Emitter = require('emitter'); var tick = require('next-tick'); var events = require('./events'); /** * Mixin emitter. */ Emitter(exports); /** * Initialize. */ exports.initialize = function () { this.load(); }; /** * Loaded? * * @return {Boolean} * @api private */ exports.loaded = function () { return false; }; /** * Load. * * @param {Function} cb */ exports.load = function (cb) { callback.async(cb); }; /** * Page. * * @param {Page} page */ exports.page = function(page){}; /** * Track. * * @param {Track} track */ exports.track = function(track){}; /** * Invoke a `method` that may or may not exist on the prototype with `args`, * queueing or not depending on whether the integration is "ready". Don't * trust the method call, since it contains integration party code. * * @param {String} method * @param {Mixed} args... * @api private */ exports.invoke = function (method) { if (!this[method]) return; var args = [].slice.call(arguments, 1); if (!this._ready) return this.queue(method, args); try { this.debug('%s with %o', method, args); this[method].apply(this, args); } catch (e) { this.debug('error %o calling %s with %o', e, method, args); } }; /** * Queue a `method` with `args`. If the integration assumes an initial * pageview, then let the first call to `page` pass through. * * @param {String} method * @param {Array} args * @api private */ exports.queue = function (method, args) { if ('page' == method && this._assumesPageview && !this._initialized) { return this.page.apply(this, args); } this._queue.push({ method: method, args: args }); }; /** * Flush the internal queue. * * @api private */ exports.flush = function () { this._ready = true; var call; while (call = this._queue.shift()) this[call.method].apply(this, call.args); }; /** * Reset the integration, removing its global variables. * * @api private */ exports.reset = function () { for (var i = 0, key; key = this.globals[i]; i++) window[key] = undefined; }; /** * Wrap the initialize method in an exists check, so we don't have to do it for * every single integration. * * @api private */ exports._wrapInitialize = function () { var initialize = this.initialize; this.initialize = function () { this.debug('initialize'); this._initialized = true; initialize.apply(this, arguments); this.emit('initialize'); var self = this; if (this._readyOnInitialize) { tick(function () { self.emit('ready'); }); } }; if (this._assumesPageview) this.initialize = after(2, this.initialize); }; /** * Wrap the load method in `debug` calls, so every integration gets them * automatically. * * @api private */ exports._wrapLoad = function () { var load = this.load; this.load = function (callback) { var self = this; this.debug('loading'); if (this.loaded()) { this.debug('already loaded'); tick(function () { if (self._readyOnLoad) self.emit('ready'); callback && callback(); }); return; } load.call(this, function (err, e) { self.debug('loaded'); self.emit('load'); if (self._readyOnLoad) self.emit('ready'); callback && callback(err, e); }); }; }; /** * Wrap the page method to call `initialize` instead if the integration assumes * a pageview. * * @api private */ exports._wrapPage = function () { var page = this.page; this.page = function () { if (this._assumesPageview && !this._initialized) { return this.initialize({ category: arguments[0], name: arguments[1], properties: arguments[2], options: arguments[3] }); } page.apply(this, arguments); }; }; /** * Wrap the track method to call other ecommerce methods if * available depending on the `track.event()`. * * @api private */ exports._wrapTrack = function(){ var t = this.track; this.track = function(track){ var event = track.event(); var called; for (var method in events) { var regexp = events[method]; if (!this[method]) continue; if (!regexp.test(event)) continue; this[method].apply(this, arguments); called = true; break; } if (!called) t.apply(this, arguments); }; }; }); require.register("segmentio-analytics.js-integration/lib/events.js", function(exports, require, module){ /** * Expose `events` */ module.exports = { removedProduct: /removed product/i, viewedProduct: /viewed product/i, addedProduct: /added product/i, completedOrder: /completed order/i }; }); require.register("segmentio-analytics.js-integration/lib/statics.js", function(exports, require, module){ var after = require('after'); var Emitter = require('emitter'); /** * Mixin emitter. */ Emitter(exports); /** * Add a new option to the integration by `key` with default `value`. * * @param {String} key * @param {Mixed} value * @return {Integration} */ exports.option = function (key, value) { this.prototype.defaults[key] = value; return this; }; /** * Register a new global variable `key` owned by the integration, which will be * used to test whether the integration is already on the page. * * @param {String} global * @return {Integration} */ exports.global = function (key) { this.prototype.globals.push(key); return this; }; /** * Mark the integration as assuming an initial pageview, so to defer loading * the script until the first `page` call, noop the first `initialize`. * * @return {Integration} */ exports.assumesPageview = function () { this.prototype._assumesPageview = true; return this; }; /** * Mark the integration as being "ready" once `load` is called. * * @return {Integration} */ exports.readyOnLoad = function () { this.prototype._readyOnLoad = true; return this; }; /** * Mark the integration as being "ready" once `load` is called. * * @return {Integration} */ exports.readyOnInitialize = function () { this.prototype._readyOnInitialize = true; return this; }; }); require.register("component-domify/index.js", function(exports, require, module){ /** * Expose `parse`. */ module.exports = parse; /** * Wrap map from jquery. */ var map = { legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], _default: [0, '', ''] }; map.td = map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>']; map.option = map.optgroup = [1, '<select multiple="multiple">', '</select>']; map.thead = map.tbody = map.colgroup = map.caption = map.tfoot = [1, '<table>', '</table>']; map.text = map.circle = map.ellipse = map.line = map.path = map.polygon = map.polyline = map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>']; /** * Parse `html` and return the children. * * @param {String} html * @return {Array} * @api private */ function parse(html) { if ('string' != typeof html) throw new TypeError('String expected'); html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace // tag name var m = /<([\w:]+)/.exec(html); if (!m) return document.createTextNode(html); var tag = m[1]; // body support if (tag == 'body') { var el = document.createElement('html'); el.innerHTML = html; return el.removeChild(el.lastChild); } // wrap map var wrap = map[tag] || map._default; var depth = wrap[0]; var prefix = wrap[1]; var suffix = wrap[2]; var el = document.createElement('div'); el.innerHTML = prefix + html + suffix; while (depth--) el = el.lastChild; // one element if (el.firstChild == el.lastChild) { return el.removeChild(el.firstChild); } // several elements var fragment = document.createDocumentFragment(); while (el.firstChild) { fragment.appendChild(el.removeChild(el.firstChild)); } return fragment; } }); require.register("component-once/index.js", function(exports, require, module){ /** * Identifier. */ var n = 0; /** * Global. */ var global = (function(){ return this })(); /** * Make `fn` callable only once. * * @param {Function} fn * @return {Function} * @api public */ module.exports = function(fn) { var id = n++; function once(){ // no receiver if (this == global) { if (once.called) return; once.called = true; return fn.apply(this, arguments); } // receiver var key = '__called_' + id + '__'; if (this[key]) return; this[key] = true; return fn.apply(this, arguments); } return once; }; }); require.register("segmentio-alias/index.js", function(exports, require, module){ var type = require('type'); try { var clone = require('clone'); } catch (e) { var clone = require('clone-component'); } /** * Expose `alias`. */ module.exports = alias; /** * Alias an `object`. * * @param {Object} obj * @param {Mixed} method */ function alias (obj, method) { switch (type(method)) { case 'object': return aliasByDictionary(clone(obj), method); case 'function': return aliasByFunction(clone(obj), method); } } /** * Convert the keys in an `obj` using a dictionary of `aliases`. * * @param {Object} obj * @param {Object} aliases */ function aliasByDictionary (obj, aliases) { for (var key in aliases) { if (undefined === obj[key]) continue; obj[aliases[key]] = obj[key]; delete obj[key]; } return obj; } /** * Convert the keys in an `obj` using a `convert` function. * * @param {Object} obj * @param {Function} convert */ function aliasByFunction (obj, convert) { // have to create another object so that ie8 won't infinite loop on keys var output = {}; for (var key in obj) output[convert(key)] = obj[key]; return output; } }); require.register("segmentio-convert-dates/index.js", function(exports, require, module){ var is = require('is'); try { var clone = require('clone'); } catch (e) { var clone = require('clone-component'); } /** * Expose `convertDates`. */ module.exports = convertDates; /** * Recursively convert an `obj`'s dates to new values. * * @param {Object} obj * @param {Function} convert * @return {Object} */ function convertDates (obj, convert) { obj = clone(obj); for (var key in obj) { var val = obj[key]; if (is.date(val)) obj[key] = convert(val); if (is.object(val)) obj[key] = convertDates(val, convert); } return obj; } }); require.register("segmentio-global-queue/index.js", function(exports, require, module){ /** * Expose `generate`. */ module.exports = generate; /** * Generate a global queue pushing method with `name`. * * @param {String} name * @param {Object} options * @property {Boolean} wrap * @return {Function} */ function generate (name, options) { options = options || {}; return function (args) { args = [].slice.call(arguments); window[name] || (window[name] = []); options.wrap === false ? window[name].push.apply(window[name], args) : window[name].push(args); }; } }); require.register("segmentio-load-date/index.js", function(exports, require, module){ /* * Load date. * * For reference: http://www.html5rocks.com/en/tutorials/webperformance/basics/ */ var time = new Date() , perf = window.performance; if (perf && perf.timing && perf.timing.responseEnd) { time = new Date(perf.timing.responseEnd); } module.exports = time; }); require.register("segmentio-load-script/index.js", function(exports, require, module){ var type = require('type'); module.exports = function loadScript (options, callback) { if (!options) throw new Error('Cant load nothing...'); // Allow for the simplest case, just passing a `src` string. if (type(options) === 'string') options = { src : options }; var https = document.location.protocol === 'https:' || document.location.protocol === 'chrome-extension:'; // If you use protocol relative URLs, third-party scripts like Google // Analytics break when testing with `file:` so this fixes that. if (options.src && options.src.indexOf('//') === 0) { options.src = https ? 'https:' + options.src : 'http:' + options.src; } // Allow them to pass in different URLs depending on the protocol. if (https && options.https) options.src = options.https; else if (!https && options.http) options.src = options.http; // Make the `<script>` element and insert it before the first script on the // page, which is guaranteed to exist since this Javascript is running. var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = options.src; var firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(script, firstScript); // If we have a callback, attach event handlers, even in IE. Based off of // the Third-Party Javascript script loading example: // https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html if (callback && type(callback) === 'function') { if (script.addEventListener) { script.addEventListener('load', function (event) { callback(null, event); }, false); script.addEventListener('error', function (event) { callback(new Error('Failed to load the script.'), event); }, false); } else if (script.attachEvent) { script.attachEvent('onreadystatechange', function (event) { if (/complete|loaded/.test(script.readyState)) { callback(null, event); } }); } } // Return the script element in case they want to do anything special, like // give it an ID or attributes. return script; }; }); require.register("segmentio-on-body/index.js", function(exports, require, module){ var each = require('each'); /** * Cache whether `<body>` exists. */ var body = false; /** * Callbacks to call when the body exists. */ var callbacks = []; /** * Export a way to add handlers to be invoked once the body exists. * * @param {Function} callback A function to call when the body exists. */ module.exports = function onBody (callback) { if (body) { call(callback); } else { callbacks.push(callback); } }; /** * Set an interval to check for `document.body`. */ var interval = setInterval(function () { if (!document.body) return; body = true; each(callbacks, call); clearInterval(interval); }, 5); /** * Call a callback, passing it the body. * * @param {Function} callback The callback to call. */ function call (callback) { callback(document.body); } }); require.register("segmentio-on-error/index.js", function(exports, require, module){ /** * Expose `onError`. */ module.exports = onError; /** * Callbacks. */ var callbacks = []; /** * Preserve existing handler. */ if ('function' == typeof window.onerror) callbacks.push(window.onerror); /** * Bind to `window.onerror`. */ window.onerror = handler; /** * Error handler. */ function handler () { for (var i = 0, fn; fn = callbacks[i]; i++) fn.apply(this, arguments); } /** * Call a `fn` on `window.onerror`. * * @param {Function} fn */ function onError (fn) { callbacks.push(fn); if (window.onerror != handler) { callbacks.push(window.onerror); window.onerror = handler; } } }); require.register("segmentio-to-iso-string/index.js", function(exports, require, module){ /** * Expose `toIsoString`. */ module.exports = toIsoString; /** * Turn a `date` into an ISO string. * * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString * * @param {Date} date * @return {String} */ function toIsoString (date) { return date.getUTCFullYear() + '-' + pad(date.getUTCMonth() + 1) + '-' + pad(date.getUTCDate()) + 'T' + pad(date.getUTCHours()) + ':' + pad(date.getUTCMinutes()) + ':' + pad(date.getUTCSeconds()) + '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5) + 'Z'; } /** * Pad a `number` with a ten's place zero. * * @param {Number} number * @return {String} */ function pad (number) { var n = number.toString(); return n.length === 1 ? '0' + n : n; } }); require.register("segmentio-to-unix-timestamp/index.js", function(exports, require, module){ /** * Expose `toUnixTimestamp`. */ module.exports = toUnixTimestamp; /** * Convert a `date` into a Unix timestamp. * * @param {Date} * @return {Number} */ function toUnixTimestamp (date) { return Math.floor(date.getTime() / 1000); } }); require.register("segmentio-use-https/index.js", function(exports, require, module){ /** * Protocol. */ module.exports = function (url) { switch (arguments.length) { case 0: return check(); case 1: return transform(url); } }; /** * Transform a protocol-relative `url` to the use the proper protocol. * * @param {String} url * @return {String} */ function transform (url) { return check() ? 'https:' + url : 'http:' + url; } /** * Check whether `https:` be used for loading scripts. * * @return {Boolean} */ function check () { return ( location.protocol == 'https:' || location.protocol == 'chrome-extension:' ); } }); require.register("visionmedia-batch/index.js", function(exports, require, module){ /** * Module dependencies. */ try { var EventEmitter = require('events').EventEmitter; } catch (err) { var Emitter = require('emitter'); } /** * Noop. */ function noop(){} /** * Expose `Batch`. */ module.exports = Batch; /** * Create a new Batch. */ function Batch() { if (!(this instanceof Batch)) return new Batch; this.fns = []; this.concurrency(Infinity); this.throws(true); for (var i = 0, len = arguments.length; i < len; ++i) { this.push(arguments[i]); } } /** * Inherit from `EventEmitter.prototype`. */ if (EventEmitter) { Batch.prototype.__proto__ = EventEmitter.prototype; } else { Emitter(Batch.prototype); } /** * Set concurrency to `n`. * * @param {Number} n * @return {Batch} * @api public */ Batch.prototype.concurrency = function(n){ this.n = n; return this; }; /** * Queue a function. * * @param {Function} fn * @return {Batch} * @api public */ Batch.prototype.push = function(fn){ this.fns.push(fn); return this; }; /** * Set wether Batch will or will not throw up. * * @param {Boolean} throws * @return {Batch} * @api public */ Batch.prototype.throws = function(throws) { this.e = !!throws; return this; }; /** * Execute all queued functions in parallel, * executing `cb(err, results)`. * * @param {Function} cb * @return {Batch} * @api public */ Batch.prototype.end = function(cb){ var self = this , total = this.fns.length , pending = total , results = [] , errors = [] , cb = cb || noop , fns = this.fns , max = this.n , throws = this.e , index = 0 , done; // empty if (!fns.length) return cb(null, results); // process function next() { var i = index++; var fn = fns[i]; if (!fn) return; var start = new Date; try { fn(callback); } catch (err) { callback(err); } function callback(err, res){ if (done) return; if (err && throws) return done = true, cb(err); var complete = total - pending + 1; var end = new Date; results[i] = res; errors[i] = err; self.emit('progress', { index: i, value: res, error: err, pending: pending, total: total, complete: complete, percent: complete / total * 100 | 0, start: start, end: end, duration: end - start }); if (--pending) next() else if(!throws) cb(errors, results); else cb(null, results); } } // concurrency for (var i = 0; i < fns.length; i++) { if (i == max) break; next(); } return this; }; }); require.register("segmentio-substitute/index.js", function(exports, require, module){ /** * Expose `substitute` */ module.exports = substitute; /** * Substitute `:prop` with the given `obj` in `str` * * @param {String} str * @param {Object} obj * @param {RegExp} expr * @return {String} * @api public */ function substitute(str, obj, expr){ if (!obj) throw new TypeError('expected an object'); expr = expr || /:(\w+)/g; return str.replace(expr, function(_, prop){ return null != obj[prop] ? obj[prop] : _; }); } }); require.register("segmentio-load-pixel/index.js", function(exports, require, module){ /** * Module dependencies. */ var stringify = require('querystring').stringify; var sub = require('substitute'); /** * Factory function to create a pixel loader. * * @param {String} path * @return {Function} * @api public */ module.exports = function(path){ return function(query, obj, fn){ if ('function' == typeof obj) fn = obj, obj = {}; obj = obj || {}; fn = fn || function(){}; var url = sub(path, obj); var img = new Image; img.onerror = error(fn, 'failed to load pixel', img); img.onload = function(){ fn(); }; query = stringify(query); if (query) query = '?' + query; img.src = url + query; img.width = 1; img.height = 1; return img; }; }; /** * Create an error handler. * * @param {Fucntion} fn * @param {String} message * @param {Image} img * @return {Function} * @api private */ function error(fn, message, img){ return function(e){ e = e || window.event; var err = new Error(message); err.event = e; err.source = img; fn(err); }; } }); require.register("segmentio-analytics.js-integrations/index.js", function(exports, require, module){ var integrations = require('./lib/slugs'); var each = require('each'); /** * Expose the integrations, using their own `name` from their `prototype`. */ each(integrations, function (slug) { var plugin = require('./lib/' + slug); var name = plugin.Integration.prototype.name; exports[name] = plugin; }); }); require.register("segmentio-analytics.js-integrations/lib/adroll.js", function(exports, require, module){ var integration = require('integration'); var is = require('is'); var load = require('load-script'); /** * User reference. */ var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(AdRoll); user = analytics.user(); // store for later }; /** * Expose `AdRoll` integration. */ var AdRoll = exports.Integration = integration('AdRoll') .assumesPageview() .readyOnLoad() .global('__adroll_loaded') .global('adroll_adv_id') .global('adroll_pix_id') .global('adroll_custom_data') .option('advId', '') .option('pixId', ''); /** * Initialize. * * http://support.adroll.com/getting-started-in-4-easy-steps/#step-one * http://support.adroll.com/enhanced-conversion-tracking/ * * @param {Object} page */ AdRoll.prototype.initialize = function (page) { window.adroll_adv_id = this.options.advId; window.adroll_pix_id = this.options.pixId; if (user.id()) window.adroll_custom_data = { USER_ID: user.id() }; window.__adroll_loaded = true; this.load(); }; /** * Loaded? * * @return {Boolean} */ AdRoll.prototype.loaded = function () { return window.__adroll; }; /** * Load the AdRoll library. * * @param {Function} callback */ AdRoll.prototype.load = function (callback) { load({ http: 'http://a.adroll.com/j/roundtrip.js', https: 'https://s.adroll.com/j/roundtrip.js' }, callback); }; }); require.register("segmentio-analytics.js-integrations/lib/adwords.js", function(exports, require, module){ var load = require('load-pixel')('//www.googleadservices.com/pagead/conversion/:id'); var integration = require('integration'); /** * Expose plugin */ module.exports = exports = function(analytics){ analytics.addIntegration(AdWords); }; /** * Expose `load`. */ exports.load = load; /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `AdWords` */ var AdWords = exports.Integration = integration('AdWords') .readyOnInitialize() .option('conversionId', '') .option('events', {}); /** * Track. * * @param {Track} */ AdWords.prototype.track = function(track){ var id = this.options.conversionId; var events = this.options.events; var event = track.event(); if (!has.call(events, event)) return; return exports.load({ value: track.revenue() || 0, label: events[event], script: 0 }, { id: id }); }; }); require.register("segmentio-analytics.js-integrations/lib/amplitude.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Amplitude); }; /** * Expose `Amplitude` integration. */ var Amplitude = exports.Integration = integration('Amplitude') .assumesPageview() .readyOnInitialize() .global('amplitude') .option('apiKey', '') .option('trackAllPages', false) .option('trackNamedPages', true) .option('trackCategorizedPages', true); /** * Initialize. * * https://github.com/amplitude/Amplitude-Javascript * * @param {Object} page */ Amplitude.prototype.initialize = function (page) { (function(e,t){var r=e.amplitude||{}; r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)));};} var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName"]; for(var c=0;c<s.length;c++){i(s[c]);}e.amplitude=r;})(window,document); window.amplitude.init(this.options.apiKey); this.load(); }; /** * Loaded? * * @return {Boolean} */ Amplitude.prototype.loaded = function () { return !! (window.amplitude && window.amplitude.options); }; /** * Load the Amplitude library. * * @param {Function} callback */ Amplitude.prototype.load = function (callback) { load('https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.0-min.js', callback); }; /** * Page. * * @param {Page} page */ Amplitude.prototype.page = function (page) { var properties = page.properties(); var category = page.category(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Identify. * * @param {Facade} identify */ Amplitude.prototype.identify = function (identify) { var id = identify.userId(); var traits = identify.traits(); if (id) window.amplitude.setUserId(id); if (traits) window.amplitude.setGlobalUserProperties(traits); }; /** * Track. * * @param {Track} event */ Amplitude.prototype.track = function (track) { var props = track.properties(); var event = track.event(); window.amplitude.logEvent(event, props); }; }); require.register("segmentio-analytics.js-integrations/lib/awesm.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); /** * User reference. */ var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Awesm); user = analytics.user(); // store for later }; /** * Expose `Awesm` integration. */ var Awesm = exports.Integration = integration('awe.sm') .assumesPageview() .readyOnLoad() .global('AWESM') .option('apiKey', '') .option('events', {}); /** * Initialize. * * http://developers.awe.sm/guides/javascript/ * * @param {Object} page */ Awesm.prototype.initialize = function (page) { window.AWESM = { api_key: this.options.apiKey }; this.load(); }; /** * Loaded? * * @return {Boolean} */ Awesm.prototype.loaded = function () { return !! window.AWESM._exists; }; /** * Load. * * @param {Function} callback */ Awesm.prototype.load = function (callback) { var key = this.options.apiKey; load('//widgets.awe.sm/v3/widgets.js?key=' + key + '&async=true', callback); }; /** * Track. * * @param {Track} track */ Awesm.prototype.track = function (track) { var event = track.event(); var goal = this.options.events[event]; if (!goal) return; window.AWESM.convert(goal, track.cents(), null, user.id()); }; }); require.register("segmentio-analytics.js-integrations/lib/awesomatic.js", function(exports, require, module){ var integration = require('integration'); var is = require('is'); var load = require('load-script'); var noop = function(){}; var onBody = require('on-body'); /** * User reference. */ var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Awesomatic); user = analytics.user(); // store for later }; /** * Expose `Awesomatic` integration. */ var Awesomatic = exports.Integration = integration('Awesomatic') .assumesPageview() .global('Awesomatic') .global('AwesomaticSettings') .global('AwsmSetup') .global('AwsmTmp') .option('appId', ''); /** * Initialize. * * @param {Object} page */ Awesomatic.prototype.initialize = function (page) { var self = this; var id = user.id(); var options = user.traits(); options.appId = this.options.appId; if (id) options.user_id = id; this.load(function () { window.Awesomatic.initialize(options, function () { self.emit('ready'); // need to wait for initialize to callback }); }); }; /** * Loaded? * * @return {Boolean} */ Awesomatic.prototype.loaded = function () { return is.object(window.Awesomatic); }; /** * Load the Awesomatic library. * * @param {Function} callback */ Awesomatic.prototype.load = function (callback) { var url = 'https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js'; load(url, callback); }; }); require.register("segmentio-analytics.js-integrations/lib/bing-ads.js", function(exports, require, module){ var integration = require('integration'); /** * Expose plugin */ module.exports = exports = function(analytics){ analytics.addIntegration(Bing); }; /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `Bing` */ var Bing = exports.Integration = integration('Bing Ads') .readyOnInitialize() .option('siteId', '') .option('domainId', '') .option('goals', {}); /** * Track. * * @param {Track} track */ Bing.prototype.track = function(track){ var goals = this.options.goals; var traits = track.traits(); var event = track.event(); if (!has.call(goals, event)) return; var goal = goals[event]; return exports.load(goal, track.revenue(), this.options); }; /** * Load conversion. * * @param {Mixed} goal * @param {Number} revenue * @param {String} currency * @return {IFrame} * @api private */ exports.load = function(goal, revenue, options){ var iframe = document.createElement('iframe'); iframe.src = '//flex.msn.com/mstag/tag/' + options.siteId + '/analytics.html' + '?domainId=' + options.domainId + '&revenue=' + revenue || 0 + '&actionid=' + goal; + '&dedup=1' + '&type=1' iframe.width = 1; iframe.height = 1; return iframe; }; }); require.register("segmentio-analytics.js-integrations/lib/bronto.js", function(exports, require, module){ /** * Module dependencies. */ var integration = require('integration'); var Track = require('facade').Track; var load = require('load-script'); var each = require('each'); /** * Expose plugin. */ module.exports = exports = function(analytics){ analytics.addIntegration(Bronto); }; /** * Expose `Bronto` integration. */ var Bronto = exports.Integration = integration('Bronto') .readyOnLoad() .global('__bta') .option('siteId', '') .option('host', ''); /** * Initialize. * * http://bronto.com/product-blog/features/using-conversion-tracking-private-domain#.Ut_Vk2T8KqB * http://bronto.com/product-blog/features/javascript-conversion-tracking-setup-and-reporting#.Ut_VhmT8KqB * * @param {Object} page */ Bronto.prototype.initialize = function(page){ this.load(); }; /** * Loaded? * * @return {Boolean} */ Bronto.prototype.loaded = function(){ return this.bta; }; /** * Load the Bronto library. * * @param {Function} fn */ Bronto.prototype.load = function(fn){ var self = this; load('//p.bm23.com/bta.js', function(err){ if (err) return fn(err); var opts = self.options; self.bta = new window.__bta(opts.siteId); if (opts.host) self.bta.setHost(opts.host); fn(); }); }; /** * Track. * * @param {Track} event */ Bronto.prototype.track = function(track){ var revenue = track.revenue(); var event = track.event(); var type = 'number' == typeof revenue ? '$' : 't'; this.bta.addConversionLegacy(type, event, revenue); }; /** * Completed order. * * @param {Track} track * @api private */ Bronto.prototype.completedOrder = function(track){ var products = track.products(); var props = track.properties(); var items = []; // items each(products, function(product){ var track = new Track({ properties: product }); items.push({ item_id: track.id() || track.sku(), desc: product.description || track.name(), quantity: track.quantity(), amount: track.price(), }); }); // add conversion this.bta.addConversion({ order_id: track.orderId(), date: props.date || new Date, items: items }); }; }); require.register("segmentio-analytics.js-integrations/lib/bugherd.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(BugHerd); }; /** * Expose `BugHerd` integration. */ var BugHerd = exports.Integration = integration('BugHerd') .assumesPageview() .readyOnLoad() .global('BugHerdConfig') .global('_bugHerd') .option('apiKey', '') .option('showFeedbackTab', true); /** * Initialize. * * http://support.bugherd.com/home * * @param {Object} page */ BugHerd.prototype.initialize = function (page) { window.BugHerdConfig = { feedback: { hide: !this.options.showFeedbackTab }}; this.load(); }; /** * Loaded? * * @return {Boolean} */ BugHerd.prototype.loaded = function () { return !! window._bugHerd; }; /** * Load the BugHerd library. * * @param {Function} callback */ BugHerd.prototype.load = function (callback) { load('//www.bugherd.com/sidebarv2.js?apikey=' + this.options.apiKey, callback); }; }); require.register("segmentio-analytics.js-integrations/lib/bugsnag.js", function(exports, require, module){ var integration = require('integration'); var is = require('is'); var extend = require('extend'); var load = require('load-script'); var onError = require('on-error'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Bugsnag); }; /** * Expose `Bugsnag` integration. */ var Bugsnag = exports.Integration = integration('Bugsnag') .readyOnLoad() .global('Bugsnag') .option('apiKey', ''); /** * Initialize. * * https://bugsnag.com/docs/notifiers/js * * @param {Object} page */ Bugsnag.prototype.initialize = function (page) { this.load(); }; /** * Loaded? * * @return {Boolean} */ Bugsnag.prototype.loaded = function () { return is.object(window.Bugsnag); }; /** * Load. * * @param {Function} callback (optional) */ Bugsnag.prototype.load = function (callback) { var apiKey = this.options.apiKey; load('//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js', function(err){ if (err) return callback(err); window.Bugsnag.apiKey = apiKey; callback(); }); }; /** * Identify. * * @param {Identify} identify */ Bugsnag.prototype.identify = function (identify) { window.Bugsnag.metaData = window.Bugsnag.metaData || {}; extend(window.Bugsnag.metaData, identify.traits()); }; }); require.register("segmentio-analytics.js-integrations/lib/chartbeat.js", function(exports, require, module){ var integration = require('integration'); var onBody = require('on-body'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Chartbeat); }; /** * Expose `Chartbeat` integration. */ var Chartbeat = exports.Integration = integration('Chartbeat') .assumesPageview() .readyOnLoad() .global('_sf_async_config') .global('_sf_endpt') .global('pSUPERFLY') .option('domain', '') .option('uid', null); /** * Initialize. * * http://chartbeat.com/docs/configuration_variables/ * * @param {Object} page */ Chartbeat.prototype.initialize = function (page) { window._sf_async_config = this.options; onBody(function () { window._sf_endpt = new Date().getTime(); }); this.load(); }; /** * Loaded? * * @return {Boolean} */ Chartbeat.prototype.loaded = function () { return !! window.pSUPERFLY; }; /** * Load the Chartbeat library. * * http://chartbeat.com/docs/adding_the_code/ * * @param {Function} callback */ Chartbeat.prototype.load = function (callback) { load({ https: 'https://a248.e.akamai.net/chartbeat.download.akamai.com/102508/js/chartbeat.js', http: 'http://static.chartbeat.com/js/chartbeat.js' }, callback); }; /** * Page. * * http://chartbeat.com/docs/handling_virtual_page_changes/ * * @param {Page} page */ Chartbeat.prototype.page = function (page) { var props = page.properties(); var name = page.fullName(); window.pSUPERFLY.virtualPage(props.path, name || props.title); }; }); require.register("segmentio-analytics.js-integrations/lib/churnbee.js", function(exports, require, module){ /** * Module dependencies. */ var push = require('global-queue')('_cbq'); var integration = require('integration'); var load = require('load-script'); /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Supported events */ var supported = { activation: true, changePlan: true, register: true, refund: true, charge: true, cancel: true, login: true, }; /** * Expose plugin. */ module.exports = exports = function(analytics){ analytics.addIntegration(ChurnBee); }; /** * Expose `ChurnBee` integration. */ var ChurnBee = exports.Integration = integration('ChurnBee') .readyOnInitialize() .global('_cbq') .global('ChurnBee') .option('events', {}) .option('apiKey', ''); /** * Initialize. * * https://churnbee.com/docs * * @param {Object} page */ ChurnBee.prototype.initialize = function(page){ push('_setApiKey', this.options.apiKey); this.load(); }; /** * Loaded? * * @return {Boolean} */ ChurnBee.prototype.loaded = function(){ return !! window.ChurnBee; }; /** * Load the ChurnBee library. * * @param {Function} fn */ ChurnBee.prototype.load = function(fn){ load('//api.churnbee.com/cb.js', fn); }; /** * Track. * * @param {Track} event */ ChurnBee.prototype.track = function(track){ var events = this.options.events; var event = track.event(); if (has.call(events, event)) event = events[event]; if (true != supported[event]) return; push(event, track.properties({ revenue: 'amount' })); }; }); require.register("segmentio-analytics.js-integrations/lib/clicktale.js", function(exports, require, module){ var date = require('load-date'); var domify = require('domify'); var each = require('each'); var integration = require('integration'); var is = require('is'); var useHttps = require('use-https'); var load = require('load-script'); var onBody = require('on-body'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(ClickTale); }; /** * Expose `ClickTale` integration. */ var ClickTale = exports.Integration = integration('ClickTale') .assumesPageview() .readyOnLoad() .global('WRInitTime') .global('ClickTale') .global('ClickTaleSetUID') .global('ClickTaleField') .global('ClickTaleEvent') .option('httpCdnUrl', 'http://s.clicktale.net/WRe0.js') .option('httpsCdnUrl', '') .option('projectId', '') .option('recordingRatio', 0.01) .option('partitionId', ''); /** * Initialize. * * http://wiki.clicktale.com/Article/JavaScript_API * * @param {Object} page */ ClickTale.prototype.initialize = function (page) { var options = this.options; window.WRInitTime = date.getTime(); onBody(function (body) { body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">')); }); this.load(function () { window.ClickTale(options.projectId, options.recordingRatio, options.partitionId); }); }; /** * Loaded? * * @return {Boolean} */ ClickTale.prototype.loaded = function () { return is.fn(window.ClickTale); }; /** * Load the ClickTale library. * * @param {Function} callback */ ClickTale.prototype.load = function (callback) { var http = this.options.httpCdnUrl; var https = this.options.httpsCdnUrl; if (useHttps() && !https) return this.debug('https option required'); load({ http: http, https: https }, callback); }; /** * Identify. * * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleSetUID * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleField * * @param {Identify} identify */ ClickTale.prototype.identify = function (identify) { var id = identify.userId(); window.ClickTaleSetUID(id); each(identify.traits(), function (key, value) { window.ClickTaleField(key, value); }); }; /** * Track. * * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleEvent * * @param {Track} track */ ClickTale.prototype.track = function (track) { window.ClickTaleEvent(track.event()); }; }); require.register("segmentio-analytics.js-integrations/lib/clicky.js", function(exports, require, module){ var Identify = require('facade').Identify; var extend = require('extend'); var integration = require('integration'); var is = require('is'); var load = require('load-script'); /** * User reference. */ var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Clicky); user = analytics.user(); // store for later }; /** * Expose `Clicky` integration. */ var Clicky = exports.Integration = integration('Clicky') .assumesPageview() .readyOnLoad() .global('clicky') .global('clicky_site_ids') .global('clicky_custom') .option('siteId', null); /** * Initialize. * * http://clicky.com/help/customization * * @param {Object} page */ Clicky.prototype.initialize = function (page) { window.clicky_site_ids = window.clicky_site_ids || [this.options.siteId]; this.identify(new Identify({ userId: user.id(), traits: user.traits() })); this.load(); }; /** * Loaded? * * @return {Boolean} */ Clicky.prototype.loaded = function () { return is.object(window.clicky); }; /** * Load the Clicky library. * * @param {Function} callback */ Clicky.prototype.load = function (callback) { load('//static.getclicky.com/js', callback); }; /** * Page. * * http://clicky.com/help/customization#/help/custom/manual * * @param {Page} page */ Clicky.prototype.page = function (page) { var properties = page.properties(); var category = page.category(); var name = page.fullName(); window.clicky.log(properties.path, name || properties.title); }; /** * Identify. * * @param {Identify} id (optional) */ Clicky.prototype.identify = function (identify) { window.clicky_custom = window.clicky_custom || {}; window.clicky_custom.session = window.clicky_custom.session || {}; extend(window.clicky_custom.session, identify.traits()); }; /** * Track. * * http://clicky.com/help/customization#/help/custom/manual * * @param {Track} event */ Clicky.prototype.track = function (track) { window.clicky.goal(track.event(), track.revenue()); }; }); require.register("segmentio-analytics.js-integrations/lib/comscore.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Comscore); }; /** * Expose `Comscore` integration. */ var Comscore = exports.Integration = integration('comScore') .assumesPageview() .readyOnLoad() .global('_comscore') .global('COMSCORE') .option('c1', '2') .option('c2', ''); /** * Initialize. * * @param {Object} page */ Comscore.prototype.initialize = function (page) { window._comscore = window._comscore || [this.options]; this.load(); }; /** * Loaded? * * @return {Boolean} */ Comscore.prototype.loaded = function () { return !! window.COMSCORE; }; /** * Load. * * @param {Function} callback */ Comscore.prototype.load = function (callback) { load({ http: 'http://b.scorecardresearch.com/beacon.js', https: 'https://sb.scorecardresearch.com/beacon.js' }, callback); }; }); require.register("segmentio-analytics.js-integrations/lib/crazy-egg.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(CrazyEgg); }; /** * Expose `CrazyEgg` integration. */ var CrazyEgg = exports.Integration = integration('Crazy Egg') .assumesPageview() .readyOnLoad() .global('CE2') .option('accountNumber', ''); /** * Initialize. * * @param {Object} page */ CrazyEgg.prototype.initialize = function (page) { this.load(); }; /** * Loaded? * * @return {Boolean} */ CrazyEgg.prototype.loaded = function () { return !! window.CE2; }; /** * Load the Crazy Egg library. * * @param {Function} callback */ CrazyEgg.prototype.load = function (callback) { var number = this.options.accountNumber; var path = number.slice(0,4) + '/' + number.slice(4); var cache = Math.floor(new Date().getTime()/3600000); var url = '//dnn506yrbagrg.cloudfront.net/pages/scripts/' + path + '.js?' + cache; load(url, callback); }; }); require.register("segmentio-analytics.js-integrations/lib/curebit.js", function(exports, require, module){ var push = require('global-queue')('_curebitq'); var Identify = require('facade').Identify; var integration = require('integration'); var Track = require('facade').Track; var iso = require('to-iso-string'); var load = require('load-script'); var extend = require('extend'); var clone = require('clone'); var each = require('each'); /** * User reference */ var user; /** * Expose plugin */ module.exports = exports = function(analytics){ analytics.addIntegration(Curebit); user = analytics.user(); }; /** * Expose `Curebit` integration */ var Curebit = exports.Integration = integration('Curebit') .readyOnInitialize() .global('_curebitq') .global('curebit') .option('siteId', '') .option('iframeWidth', 0) .option('iframeHeight', 0) .option('iframeBorder', 0) .option('iframeId', '') .option('responsive', true) .option('device', '') .option('server', 'https://www.curebit.com'); /** * Initialize * * @param {Object} page */ Curebit.prototype.initialize = function(){ push('init', { site_id: this.options.siteId, server: this.options.server }); this.load(); }; /** * Loaded? * * @return {Boolean} */ Curebit.prototype.loaded = function(){ return !! window.curebit; }; /** * Load * * @param {Function} fn * @api private */ Curebit.prototype.load = function(fn){ load('//d2jjzw81hqbuqv.cloudfront.net/assets/api/all-0.6.js', fn); }; /** * Identify. * * http://www.curebit.com/docs/affiliate/registration * * @param {Identify} identify * @api public */ Curebit.prototype.identify = function(identify){ push('register_affiliate', { responsive: this.options.responsive, device: this.options.device, iframe: { width: this.options.iframeWidth, height: this.options.iframeHeight, id: this.options.iframeId, frameborder: this.options.iframeBorder }, affiliate_member: { email: identify.email(), first_name: identify.firstName(), last_name: identify.lastName(), customer_id: identify.userId() }, }); }; /** * Completed order * * https://www.curebit.com/docs/ecommerce/custom * * @param {Track} track * @api private */ Curebit.prototype.completedOrder = function(track){ var orderId = track.orderId(); var products = track.products(); var props = track.properties(); var items = []; // identify var identify = new Identify({ traits: user.traits(), userId: user.id() }); // items each(products, function(product){ var track = new Track({ properties: product }); items.push({ product_id: track.id() || track.sku(), quantity: track.quantity(), image_url: product.image, price: track.price(), title: track.name(), url: product.url, }); }); // transaction push('register_purchase', { order_date: iso(props.date || new Date), order_number: orderId, coupon_code: track.coupon(), subtotal: track.total(), customer_id: identify.userId(), first_name: identify.firstName(), last_name: identify.lastName(), email: identify.email(), items: items }); }; }); require.register("segmentio-analytics.js-integrations/lib/customerio.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var convertDates = require('convert-dates'); var Identify = require('facade').Identify; var integration = require('integration'); var load = require('load-script'); /** * User reference. */ var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Customerio); user = analytics.user(); // store for later }; /** * Expose `Customerio` integration. */ var Customerio = exports.Integration = integration('Customer.io') .assumesPageview() .readyOnInitialize() .global('_cio') .option('siteId', ''); /** * Initialize. * * http://customer.io/docs/api/javascript.html * * @param {Object} page */ Customerio.prototype.initialize = function (page) { window._cio = window._cio || []; (function() {var a,b,c; a = function (f) {return function () {window._cio.push([f].concat(Array.prototype.slice.call(arguments,0))); }; }; b = ['identify', 'track']; for (c = 0; c < b.length; c++) {window._cio[b[c]] = a(b[c]); } })(); this.load(); }; /** * Loaded? * * @return {Boolean} */ Customerio.prototype.loaded = function () { return !! (window._cio && window._cio.pageHasLoaded); }; /** * Load. * * @param {Function} callback */ Customerio.prototype.load = function (callback) { var script = load('https://assets.customer.io/assets/track.js', callback); script.id = 'cio-tracker'; script.setAttribute('data-site-id', this.options.siteId); }; /** * Identify. * * http://customer.io/docs/api/javascript.html#section-Identify_customers * * @param {Identify} identify */ Customerio.prototype.identify = function (identify) { if (!identify.userId()) return this.debug('user id required'); var traits = identify.traits({ created: 'created_at' }); traits = convertDates(traits, convertDate); window._cio.identify(traits); }; /** * Group. * * @param {Group} group */ Customerio.prototype.group = function (group) { var traits = group.traits(); traits = alias(traits, function (trait) { return 'Group ' + trait; }); this.identify(new Identify({ userId: user.id(), traits: traits })); }; /** * Track. * * http://customer.io/docs/api/javascript.html#section-Track_a_custom_event * * @param {Track} track */ Customerio.prototype.track = function (track) { var properties = track.properties(); properties = convertDates(properties, convertDate); window._cio.track(track.event(), properties); }; /** * Convert a date to the format Customer.io supports. * * @param {Date} date * @return {Number} */ function convertDate (date) { return Math.floor(date.getTime() / 1000); } }); require.register("segmentio-analytics.js-integrations/lib/drip.js", function(exports, require, module){ var alias = require('alias'); var integration = require('integration'); var is = require('is'); var load = require('load-script'); var push = require('global-queue')('_dcq'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Drip); }; /** * Expose `Drip` integration. */ var Drip = exports.Integration = integration('Drip') .assumesPageview() .readyOnLoad() .global('dc') .global('_dcq') .global('_dcs') .option('account', ''); /** * Initialize. * * @param {Object} page */ Drip.prototype.initialize = function (page) { window._dcq = window._dcq || []; window._dcs = window._dcs || {}; window._dcs.account = this.options.account; this.load(); }; /** * Loaded? * * @return {Boolean} */ Drip.prototype.loaded = function () { return is.object(window.dc); }; /** * Load. * * @param {Function} callback */ Drip.prototype.load = function (callback) { load('//tag.getdrip.com/' + this.options.account + '.js', callback); }; /** * Track. * * @param {Track} track */ Drip.prototype.track = function (track) { var props = track.properties(); var cents = Math.round(track.cents()); props.action = track.event(); if (cents) props.value = cents; delete props.revenue; push('track', props); }; }); require.register("segmentio-analytics.js-integrations/lib/errorception.js", function(exports, require, module){ var callback = require('callback'); var extend = require('extend'); var integration = require('integration'); var load = require('load-script'); var onError = require('on-error'); var push = require('global-queue')('_errs'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Errorception); }; /** * Expose `Errorception` integration. */ var Errorception = exports.Integration = integration('Errorception') .assumesPageview() .readyOnInitialize() .global('_errs') .option('projectId', '') .option('meta', true); /** * Initialize. * * https://github.com/amplitude/Errorception-Javascript * * @param {Object} page */ Errorception.prototype.initialize = function (page) { window._errs = window._errs || [this.options.projectId]; onError(push); this.load(); }; /** * Loaded? * * @return {Boolean} */ Errorception.prototype.loaded = function () { return !! (window._errs && window._errs.push !== Array.prototype.push); }; /** * Load the Errorception library. * * @param {Function} callback */ Errorception.prototype.load = function (callback) { load('//beacon.errorception.com/' + this.options.projectId + '.js', callback); }; /** * Identify. * * http://blog.errorception.com/2012/11/capture-custom-data-with-your-errors.html * * @param {Object} identify */ Errorception.prototype.identify = function (identify) { if (!this.options.meta) return; var traits = identify.traits(); window._errs = window._errs || []; window._errs.meta = window._errs.meta || {}; extend(window._errs.meta, traits); }; }); require.register("segmentio-analytics.js-integrations/lib/evergage.js", function(exports, require, module){ var each = require('each'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_aaq'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Evergage); }; /** * Expose `Evergage` integration.integration. */ var Evergage = exports.Integration = integration('Evergage') .assumesPageview() .readyOnInitialize() .global('_aaq') .option('account', '') .option('dataset', ''); /** * Initialize. * * @param {Object} page */ Evergage.prototype.initialize = function (page) { var account = this.options.account; var dataset = this.options.dataset; window._aaq = window._aaq || []; push('setEvergageAccount', account); push('setDataset', dataset); push('setUseSiteConfig', true); this.load(); }; /** * Loaded? * * @return {Boolean} */ Evergage.prototype.loaded = function () { return !! (window._aaq && window._aaq.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Evergage.prototype.load = function (callback) { var account = this.options.account; var dataset = this.options.dataset; var url = '//cdn.evergage.com/beacon/' + account + '/' + dataset + '/scripts/evergage.min.js'; load(url, callback); }; /** * Page. * * @param {Page} page */ Evergage.prototype.page = function (page) { var props = page.properties(); var name = page.name(); if (name) push('namePage', name); each(props, function(key, value) { push('setCustomField', key, value, 'page'); }); window.Evergage.init(true); }; /** * Identify. * * @param {Identify} identify */ Evergage.prototype.identify = function (identify) { var id = identify.userId(); if (!id) return; push('setUser', id); var traits = identify.traits({ email: 'userEmail', name: 'userName' });; each(traits, function (key, value) { push('setUserField', key, value, 'page'); }); }; /** * Group. * * @param {Group} group */ Evergage.prototype.group = function (group) { var props = group.traits(); var id = group.groupId(); if (!id) return; push('setCompany', id); each(props, function(key, value) { push('setAccountField', key, value, 'page'); }); }; /** * Track. * * @param {Track} track */ Evergage.prototype.track = function (track) { push('trackAction', track.event(), track.properties()); }; }); require.register("segmentio-analytics.js-integrations/lib/facebook-ads.js", function(exports, require, module){ var load = require('load-pixel')('//www.facebook.com/offsite_event.php'); var integration = require('integration'); /** * Expose plugin */ module.exports = exports = function(analytics){ analytics.addIntegration(Facebook); }; /** * Expose `load`. */ exports.load = load; /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `Facebook` */ var Facebook = exports.Integration = integration('Facebook Ads') .readyOnInitialize() .option('currency', 'USD') .option('events', {}); /** * Track. * * @param {Track} track */ Facebook.prototype.track = function(track){ var events = this.options.events; var traits = track.traits(); var event = track.event(); if (!has.call(events, event)) return; return exports.load({ currency: this.options.currency, value: track.revenue() || 0, id: events[event] }); }; }); require.register("segmentio-analytics.js-integrations/lib/foxmetrics.js", function(exports, require, module){ var push = require('global-queue')('_fxm'); var integration = require('integration'); var Track = require('facade').Track; var callback = require('callback'); var load = require('load-script'); var each = require('each'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(FoxMetrics); }; /** * Expose `FoxMetrics` integration. */ var FoxMetrics = exports.Integration = integration('FoxMetrics') .assumesPageview() .readyOnInitialize() .global('_fxm') .option('appId', ''); /** * Initialize. * * http://foxmetrics.com/documentation/apijavascript * * @param {Object} page */ FoxMetrics.prototype.initialize = function(page){ window._fxm = window._fxm || []; this.load(); }; /** * Loaded? * * @return {Boolean} */ FoxMetrics.prototype.loaded = function(){ return !! (window._fxm && window._fxm.appId); }; /** * Load the FoxMetrics library. * * @param {Function} callback */ FoxMetrics.prototype.load = function(callback){ var id = this.options.appId; load('//d35tca7vmefkrc.cloudfront.net/scripts/' + id + '.js', callback); }; /** * Page. * * @param {Page} page */ FoxMetrics.prototype.page = function(page){ var properties = page.proxy('properties'); var category = page.category(); var name = page.name(); this._category = category; // store for later push( '_fxm.pages.view', properties.title, // title name, // name category, // category properties.url, // url properties.referrer // referrer ); }; /** * Identify. * * @param {Identify} identify */ FoxMetrics.prototype.identify = function(identify){ var id = identify.userId(); if (!id) return; push( '_fxm.visitor.profile', id, // user id identify.firstName(), // first name identify.lastName(), // last name identify.email(), // email identify.address(), // address undefined, // social undefined, // partners identify.traits() // attributes ); }; /** * Track. * * @param {Track} track */ FoxMetrics.prototype.track = function(track){ var props = track.properties(); var category = this._category || props.category; push(track.event(), category, props); }; /** * Viewed product. * * @param {Track} track * @api private */ FoxMetrics.prototype.viewedProduct = function(track){ ecommerce('productview', track); }; /** * Removed product. * * @param {Track} track * @api private */ FoxMetrics.prototype.removedProduct = function(track){ ecommerce('removecartitem', track); }; /** * Added product. * * @param {Track} track * @api private */ FoxMetrics.prototype.addedProduct = function(track){ ecommerce('cartitem', track); }; /** * Completed Order. * * @param {Track} track * @api private */ FoxMetrics.prototype.completedOrder = function(track){ var orderId = track.orderId(); // transaction push('_fxm.ecommerce.order' , orderId , track.subtotal() , track.shipping() , track.tax() , track.city() , track.state() , track.zip() , track.quantity()); // items each(track.products(), function(product){ var track = new Track({ properties: product }); ecommerce('purchaseitem', track, [ track.quantity(), track.price(), orderId ]); }); }; /** * Track ecommerce `event` with `track` * with optional `arr` to append. * * @param {String} event * @param {Track} track * @param {Array} arr * @api private */ function ecommerce(event, track, arr){ push.apply(null, [ '_fxm.ecommerce.' + event, track.id() || track.sku(), track.name(), track.category() ].concat(arr || [])); }; }); require.register("segmentio-analytics.js-integrations/lib/gauges.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_gauges'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Gauges); }; /** * Expose `Gauges` integration. */ var Gauges = exports.Integration = integration('Gauges') .assumesPageview() .readyOnInitialize() .global('_gauges') .option('siteId', ''); /** * Initialize Gauges. * * http://get.gaug.es/documentation/tracking/ * * @param {Object} page */ Gauges.prototype.initialize = function (page) { window._gauges = window._gauges || []; this.load(); }; /** * Loaded? * * @return {Boolean} */ Gauges.prototype.loaded = function () { return !! (window._gauges && window._gauges.push !== Array.prototype.push); }; /** * Load the Gauges library. * * @param {Function} callback */ Gauges.prototype.load = function (callback) { var id = this.options.siteId; var script = load('//secure.gaug.es/track.js', callback); script.id = 'gauges-tracker'; script.setAttribute('data-site-id', id); }; /** * Page. * * @param {Page} page */ Gauges.prototype.page = function (page) { push('track'); }; }); require.register("segmentio-analytics.js-integrations/lib/get-satisfaction.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); var onBody = require('on-body'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(GetSatisfaction); }; /** * Expose `GetSatisfaction` integration. */ var GetSatisfaction = exports.Integration = integration('Get Satisfaction') .assumesPageview() .readyOnLoad() .global('GSFN') .option('widgetId', ''); /** * Initialize. * * https://console.getsatisfaction.com/start/101022?signup=true#engage * * @param {Object} page */ GetSatisfaction.prototype.initialize = function (page) { var widget = this.options.widgetId; var div = document.createElement('div'); var id = div.id = 'getsat-widget-' + widget; onBody(function (body) { body.appendChild(div); }); // usually the snippet is sync, so wait for it before initializing the tab this.load(function () { window.GSFN.loadWidget(widget, { containerId: id }); }); }; /** * Loaded? * * @return {Boolean} */ GetSatisfaction.prototype.loaded = function () { return !! window.GSFN; }; /** * Load the Get Satisfaction library. * * @param {Function} callback */ GetSatisfaction.prototype.load = function (callback) { load('https://loader.engage.gsfn.us/loader.js', callback); }; }); require.register("segmentio-analytics.js-integrations/lib/google-analytics.js", function(exports, require, module){ var callback = require('callback'); var canonical = require('canonical'); var each = require('each'); var integration = require('integration'); var is = require('is'); var load = require('load-script'); var push = require('global-queue')('_gaq'); var Track = require('facade').Track; var type = require('type'); var url = require('url'); var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(GA); user = analytics.user(); }; /** * Expose `GA` integration. * * http://support.google.com/analytics/bin/answer.py?hl=en&answer=2558867 * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration#_gat.GA_Tracker_._setSiteSpeedSampleRate */ var GA = exports.Integration = integration('Google Analytics') .readyOnLoad() .global('ga') .global('gaplugins') .global('_gaq') .global('GoogleAnalyticsObject') .option('anonymizeIp', false) .option('classic', false) .option('domain', 'none') .option('doubleClick', false) .option('enhancedLinkAttribution', false) .option('ignoreReferrer', null) .option('includeSearch', false) .option('siteSpeedSampleRate', null) .option('trackingId', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .option('sendUserId', false); /** * When in "classic" mode, on `construct` swap all of the method to point to * their classic counterparts. */ GA.on('construct', function (integration) { if (!integration.options.classic) return; integration.initialize = integration.initializeClassic; integration.load = integration.loadClassic; integration.loaded = integration.loadedClassic; integration.page = integration.pageClassic; integration.track = integration.trackClassic; integration.completedOrder = integration.completedOrderClassic; }); /** * Initialize. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced */ GA.prototype.initialize = function () { var opts = this.options; // setup the tracker globals window.GoogleAnalyticsObject = 'ga'; window.ga = window.ga || function () { window.ga.q = window.ga.q || []; window.ga.q.push(arguments); }; window.ga.l = new Date().getTime(); window.ga('create', opts.trackingId, { cookieDomain: opts.domain || GA.prototype.defaults.domain, // to protect against empty string siteSpeedSampleRate: opts.siteSpeedSampleRate, allowLinker: true }); // send global id if (this.options.sendUserId && user.id()) { window.ga('set', '&uid', user.id()); } // anonymize after initializing, otherwise a warning is shown // in google analytics debugger if (opts.anonymizeIp) window.ga('set', 'anonymizeIp', true); this.load(); }; /** * Loaded? * * @return {Boolean} */ GA.prototype.loaded = function () { return !! window.gaplugins; }; /** * Load the Google Analytics library. * * @param {Function} callback */ GA.prototype.load = function (callback) { load('//www.google-analytics.com/analytics.js', callback); }; /** * Page. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/pages * * @param {Page} page */ GA.prototype.page = function (page) { var category = page.category(); var props = page.properties(); var name = page.fullName(); var track; this._category = category; // store for later window.ga('send', 'pageview', { page: path(props, this.options), title: name || props.title, location: props.url }); // categorized pages if (category && this.options.trackCategorizedPages) { track = page.track(category); this.track(track, { noninteraction: true }); } // named pages if (name && this.options.trackNamedPages) { track = page.track(name); this.track(track, { noninteraction: true }); } }; /** * Track. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/events * https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference * * @param {Track} event */ GA.prototype.track = function (track, options) { var opts = options || track.options(this.name); var props = track.properties(); var revenue = track.revenue(); var event = track.event(); window.ga('send', 'event', { eventAction: event, eventCategory: this._category || props.category || 'All', eventLabel: props.label, eventValue: formatValue(props.value || revenue), nonInteraction: props.noninteraction || opts.noninteraction }); }; /** * Completed order. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce * * @param {Track} track * @api private */ GA.prototype.completedOrder = function(track){ var orderId = track.orderId(); var products = track.products(); var props = track.properties(); // orderId is required. if (!orderId) return; // require ecommerce if (!this.ecommerce) { window.ga('require', 'ecommerce', 'ecommerce.js'); this.ecommerce = true; } // add transaction window.ga('ecommerce:addTransaction', { affiliation: props.affiliation, shipping: track.shipping(), revenue: track.total(), tax: track.tax(), id: orderId }); // add products each(products, function(product){ var track = new Track({ properties: product }); window.ga('ecommerce:addItem', { category: track.category(), quantity: track.quantity(), price: track.price(), name: track.name(), sku: track.sku(), id: orderId }); }); // send window.ga('ecommerce:send'); }; /** * Initialize (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration */ GA.prototype.initializeClassic = function () { var opts = this.options; var anonymize = opts.anonymizeIp; var db = opts.doubleClick; var domain = opts.domain; var enhanced = opts.enhancedLinkAttribution; var ignore = opts.ignoreReferrer; var sample = opts.siteSpeedSampleRate; window._gaq = window._gaq || []; push('_setAccount', opts.trackingId); push('_setAllowLinker', true); if (anonymize) push('_gat._anonymizeIp'); if (domain) push('_setDomainName', domain); if (sample) push('_setSiteSpeedSampleRate', sample); if (enhanced) { var protocol = 'https:' === document.location.protocol ? 'https:' : 'http:'; var pluginUrl = protocol + '//www.google-analytics.com/plugins/ga/inpage_linkid.js'; push('_require', 'inpage_linkid', pluginUrl); } if (ignore) { if (!is.array(ignore)) ignore = [ignore]; each(ignore, function (domain) { push('_addIgnoredRef', domain); }); } this.load(); }; /** * Loaded? (classic) * * @return {Boolean} */ GA.prototype.loadedClassic = function () { return !! (window._gaq && window._gaq.push !== Array.prototype.push); }; /** * Load the classic Google Analytics library. * * @param {Function} callback */ GA.prototype.loadClassic = function (callback) { if (this.options.doubleClick) { load('//stats.g.doubleclick.net/dc.js', callback); } else { load({ http: 'http://www.google-analytics.com/ga.js', https: 'https://ssl.google-analytics.com/ga.js' }, callback); } }; /** * Page (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration * * @param {Page} page */ GA.prototype.pageClassic = function (page) { var opts = page.options(this.name); var category = page.category(); var props = page.properties(); var name = page.fullName(); var track; push('_trackPageview', path(props, this.options)); // categorized pages if (category && this.options.trackCategorizedPages) { track = page.track(category); this.track(track, { noninteraction: true }); } // named pages if (name && this.options.trackNamedPages) { track = page.track(name); this.track(track, { noninteraction: true }); } }; /** * Track (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiEventTracking * * @param {Track} track */ GA.prototype.trackClassic = function (track, options) { var opts = options || track.options(this.name); var props = track.properties(); var revenue = track.revenue(); var event = track.event(); var category = this._category || props.category || 'All'; var label = props.label; var value = formatValue(revenue || props.value); var noninteraction = props.noninteraction || opts.noninteraction; push('_trackEvent', category, event, label, value, noninteraction); }; /** * Completed order. * * https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce * * @param {Track} track * @api private */ GA.prototype.completedOrderClassic = function(track){ var orderId = track.orderId(); var products = track.products() || []; var props = track.properties(); // required if (!orderId) return; // add transaction push('_addTrans' , orderId , props.affiliation , track.total() , track.tax() , track.shipping() , track.city() , track.state() , track.country()); // add items each(products, function(product){ var track = new Track({ properties: product }); push('_addItem' , orderId , track.sku() , track.name() , track.category() , track.price() , track.quantity()); }) // send push('_trackTrans'); }; /** * Return the path based on `properties` and `options`. * * @param {Object} properties * @param {Object} options */ function path (properties, options) { if (!properties) return; var str = properties.path; if (options.includeSearch && properties.search) str += properties.search; return str; } /** * Format the value property to Google's liking. * * @param {Number} value * @return {Number} */ function formatValue (value) { if (!value || value < 0) return 0; return Math.round(value); } }); require.register("segmentio-analytics.js-integrations/lib/google-tag-manager.js", function(exports, require, module){ var push = require('global-queue')('dataLayer', { wrap: false }); var integration = require('integration'); var load = require('load-script'); /** * Expose plugin */ module.exports = exports = function(analytics){ analytics.addIntegration(GTM); }; /** * Expose `GTM` */ var GTM = exports.Integration = integration('Google Tag Manager') .assumesPageview() .readyOnLoad() .global('dataLayer') .global('google_tag_manager') .option('containerId', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) /** * Initialize * * https://developers.google.com/tag-manager * * @param {Object} page */ GTM.prototype.initialize = function(){ this.load(); }; /** * Loaded * * @return {Boolean} */ GTM.prototype.loaded = function(){ return !! (window.dataLayer && [].push != window.dataLayer.push); }; /** * Load. * * @param {Function} fn */ GTM.prototype.load = function(fn){ var id = this.options.containerId; push({ 'gtm.start': +new Date, event: 'gtm.js' }); load('//www.googletagmanager.com/gtm.js?id=' + id + '&l=dataLayer', fn); }; /** * Page. * * @param {Page} page * @api public */ GTM.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); var opts = this.options; var track; // all if (opts.trackAllPages) { this.track(page.track()); } // categorized if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Track. * * https://developers.google.com/tag-manager/devguide#events * * @param {Track} track * @api public */ GTM.prototype.track = function(track){ var props = track.properties(); props.event = track.event(); push(props); }; }); require.register("segmentio-analytics.js-integrations/lib/gosquared.js", function(exports, require, module){ var Identify = require('facade').Identify; var Track = require('facade').Track; var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); var onBody = require('on-body'); var each = require('each'); /** * User reference. */ var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(GoSquared); user = analytics.user(); // store reference for later }; /** * Expose `GoSquared` integration. */ var GoSquared = exports.Integration = integration('GoSquared') .assumesPageview() .readyOnLoad() .global('_gs') .option('siteToken', '') .option('anonymizeIP', false) .option('cookieDomain', null) .option('useCookies', true) .option('trackHash', false) .option('trackLocal', false) .option('trackParams', true); /** * Initialize. * * https://www.gosquared.com/developer/tracker * Options: https://www.gosquared.com/developer/tracker/configuration * * @param {Object} page */ GoSquared.prototype.initialize = function (page) { var self = this; var options = this.options; push(options.siteToken); each(options, function(name, value){ if ('siteToken' == name) return; if (null == value) return; push('set', name, value); }); self.identify(new Identify({ traits: user.traits(), userId: user.id() })); self.load(); }; /** * Loaded? (checks if the tracker version is set) * * @return {Boolean} */ GoSquared.prototype.loaded = function () { return !! (window._gs && window._gs.v); }; /** * Load the GoSquared library. * * @param {Function} callback */ GoSquared.prototype.load = function (callback) { load('//d1l6p2sc9645hc.cloudfront.net/tracker.js', callback); }; /** * Page. * * https://www.gosquared.com/developer/tracker/pageviews * * @param {Page} page */ GoSquared.prototype.page = function (page) { var props = page.properties(); var name = page.fullName(); push('track', props.path, name || props.title) }; /** * Identify. * * https://www.gosquared.com/developer/tracker/tagging * * @param {Identify} identify */ GoSquared.prototype.identify = function (identify) { var traits = identify.traits({ userId: 'userID' }); var username = identify.username(); var email = identify.email(); var id = identify.userId(); if (id) push('set', 'visitorID', id); var name = email || username || id; if (name) push('set', 'visitorName', name); push('set', 'visitor', traits); }; /** * Track. * * https://www.gosquared.com/developer/tracker/events * * @param {Track} track */ GoSquared.prototype.track = function (track) { push('event', track.event(), track.properties()); }; /** * Checked out. * * @param {Track} track * @api private */ GoSquared.prototype.completedOrder = function(track){ var products = track.products(); var items = []; each(products, function(product){ var track = new Track({ properties: product }); items.push({ category: track.category(), quantity: track.quantity(), price: track.price(), name: track.name(), }); }) push('transaction', track.orderId(), { revenue: track.total(), track: true }, items); }; /** * Push to `_gs.q`. * * @param {...} args * @api private */ function push(){ var _gs = window._gs = window._gs || function(){ (_gs.q = _gs.q || []).push(arguments); }; _gs.apply(null, arguments); } }); require.register("segmentio-analytics.js-integrations/lib/heap.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Heap); }; /** * Expose `Heap` integration. */ var Heap = exports.Integration = integration('Heap') .assumesPageview() .readyOnInitialize() .global('heap') .global('_heapid') .option('apiKey', ''); /** * Initialize. * * https://heapanalytics.com/docs#installWeb * * @param {Object} page */ Heap.prototype.initialize = function (page) { window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var d=function(a){return function(){window.heap.push([a].concat(Array.prototype.slice.call(arguments,0)));};},e=["identify","track"];for(var f=0;f<e.length;f++)window.heap[e[f]]=d(e[f]);}; window.heap.load(this.options.apiKey); this.load(); }; /** * Loaded? * * @return {Boolean} */ Heap.prototype.loaded = function () { return (window.heap && window.heap.appid); }; /** * Load the Heap library. * * @param {Function} callback */ Heap.prototype.load = function (callback) { load('//d36lvucg9kzous.cloudfront.net', callback); }; /** * Identify. * * https://heapanalytics.com/docs#identify * * @param {Identify} identify */ Heap.prototype.identify = function (identify) { var traits = identify.traits(); var username = identify.username(); var id = identify.userId(); var handle = username || id; if (handle) traits.handle = handle; delete traits.username; window.heap.identify(traits); }; /** * Track. * * https://heapanalytics.com/docs#track * * @param {Track} track */ Heap.prototype.track = function (track) { window.heap.track(track.event(), track.properties()); }; }); require.register("segmentio-analytics.js-integrations/lib/hittail.js", function(exports, require, module){ var integration = require('integration'); var is = require('is'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(HitTail); }; /** * Expose `HitTail` integration. */ var HitTail = exports.Integration = integration('HitTail') .assumesPageview() .readyOnLoad() .global('htk') .option('siteId', ''); /** * Initialize. * * @param {Object} page */ HitTail.prototype.initialize = function (page) { this.load(); }; /** * Loaded? * * @return {Boolean} */ HitTail.prototype.loaded = function () { return is.fn(window.htk); }; /** * Load the HitTail library. * * @param {Function} callback */ HitTail.prototype.load = function (callback) { var id = this.options.siteId; load('//' + id + '.hittail.com/mlt.js', callback); }; }); require.register("segmentio-analytics.js-integrations/lib/hubspot.js", function(exports, require, module){ var callback = require('callback'); var convert = require('convert-dates'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_hsq'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(HubSpot); }; /** * Expose `HubSpot` integration. */ var HubSpot = exports.Integration = integration('HubSpot') .assumesPageview() .readyOnInitialize() .global('_hsq') .option('portalId', null); /** * Initialize. * * @param {Object} page */ HubSpot.prototype.initialize = function (page) { window._hsq = []; this.load(); }; /** * Loaded? * * @return {Boolean} */ HubSpot.prototype.loaded = function () { return !! (window._hsq && window._hsq.push !== Array.prototype.push); }; /** * Load the HubSpot library. * * @param {Function} fn */ HubSpot.prototype.load = function (fn) { if (document.getElementById('hs-analytics')) return callback.async(fn); var id = this.options.portalId; var cache = Math.ceil(new Date() / 300000) * 300000; var url = 'https://js.hs-analytics.net/analytics/' + cache + '/' + id + '.js'; var script = load(url, fn); script.id = 'hs-analytics'; }; /** * Page. * * @param {String} category (optional) * @param {String} name (optional) * @param {Object} properties (optional) * @param {Object} options (optional) */ HubSpot.prototype.page = function (page) { push('_trackPageview'); }; /** * Identify. * * @param {Identify} identify */ HubSpot.prototype.identify = function (identify) { if (!identify.email()) return; var traits = identify.traits(); traits = convertDates(traits); push('identify', traits); }; /** * Track. * * @param {Track} track */ HubSpot.prototype.track = function (track) { var props = track.properties(); props = convertDates(props); push('trackEvent', track.event(), props); }; /** * Convert all the dates in the HubSpot properties to millisecond times * * @param {Object} properties */ function convertDates (properties) { return convert(properties, function (date) { return date.getTime(); }); } }); require.register("segmentio-analytics.js-integrations/lib/improvely.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Improvely); }; /** * Expose `Improvely` integration. */ var Improvely = exports.Integration = integration('Improvely') .assumesPageview() .readyOnInitialize() .global('_improvely') .global('improvely') .option('domain', '') .option('projectId', null); /** * Initialize. * * http://www.improvely.com/docs/landing-page-code * * @param {Object} page */ Improvely.prototype.initialize = function (page) { window._improvely = []; window.improvely = {init: function (e, t) { window._improvely.push(["init", e, t]); }, goal: function (e) { window._improvely.push(["goal", e]); }, label: function (e) { window._improvely.push(["label", e]); } }; var domain = this.options.domain; var id = this.options.projectId; window.improvely.init(domain, id); this.load(); }; /** * Loaded? * * @return {Boolean} */ Improvely.prototype.loaded = function () { return !! (window.improvely && window.improvely.identify); }; /** * Load the Improvely library. * * @param {Function} callback */ Improvely.prototype.load = function (callback) { var domain = this.options.domain; load('//' + domain + '.iljmp.com/improvely.js', callback); }; /** * Identify. * * http://www.improvely.com/docs/labeling-visitors * * @param {Identify} identify */ Improvely.prototype.identify = function (identify) { var id = identify.userId(); if (id) window.improvely.label(id); }; /** * Track. * * http://www.improvely.com/docs/conversion-code * * @param {Track} track */ Improvely.prototype.track = function (track) { var props = track.properties({ revenue: 'amount' }); props.type = track.event(); window.improvely.goal(props); }; }); require.register("segmentio-analytics.js-integrations/lib/inspectlet.js", function(exports, require, module){ var integration = require('integration'); var alias = require('alias'); var clone = require('clone'); var load = require('load-script'); var push = require('global-queue')('__insp'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Inspectlet); }; /** * Expose `Inspectlet` integration. */ var Inspectlet = exports.Integration = integration('Inspectlet') .assumesPageview() .readyOnLoad() .global('__insp') .global('__insp_') .option('wid', ''); /** * Initialize. * * https://www.inspectlet.com/dashboard/embedcode/1492461759/initial * * @param {Object} page */ Inspectlet.prototype.initialize = function (page) { push('wid', this.options.wid); this.load(); }; /** * Loaded? * * @return {Boolean} */ Inspectlet.prototype.loaded = function () { return !! window.__insp_; }; /** * Load the Inspectlet library. * * @param {Function} callback */ Inspectlet.prototype.load = function (callback) { load('//www.inspectlet.com/inspectlet.js', callback); }; /** * Track. * * http://www.inspectlet.com/docs/tags * * @param {Track} track */ Inspectlet.prototype.track = function (track) { push('tagSession', track.event()); }; }); require.register("segmentio-analytics.js-integrations/lib/intercom.js", function(exports, require, module){ var alias = require('alias'); var convertDates = require('convert-dates'); var integration = require('integration'); var each = require('each'); var is = require('is'); var isEmail = require('is-email'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Intercom); }; /** * Expose `Intercom` integration. */ var Intercom = exports.Integration = integration('Intercom') .assumesPageview() .readyOnLoad() .global('Intercom') .option('activator', '#IntercomDefaultWidget') .option('appId', '') .option('inbox', false); /** * Initialize. * * http://docs.intercom.io/ * http://docs.intercom.io/#IntercomJS * * @param {Object} page */ Intercom.prototype.initialize = function (page) { this.load(); }; /** * Loaded? * * @return {Boolean} */ Intercom.prototype.loaded = function () { return is.fn(window.Intercom); }; /** * Load the Intercom library. * * @param {Function} callback */ Intercom.prototype.load = function (callback) { load('https://static.intercomcdn.com/intercom.v1.js', callback); }; /** * Identify. * * http://docs.intercom.io/#IntercomJS * * @param {Identify} identify */ Intercom.prototype.identify = function (identify) { var traits = identify.traits({ userId: 'user_id' }); var opts = identify.options(this.name); var companyCreated = identify.companyCreated(); var created = identify.created(); var email = identify.email(); var name = identify.name(); var id = identify.userId(); if (!id && !traits.email) return; // one is required traits.app_id = this.options.appId; // name if (name) traits.name = name; // handle dates if (companyCreated) traits.company.created = companyCreated; if (created) traits.created = created; // convert dates traits = convertDates(traits, formatDate); traits = alias(traits, { created: 'created_at'}); // company if (traits.company) { traits.company = alias(traits.company, { created: 'created_at' }); } // handle options if (opts.increments) traits.increments = opts.increments; if (opts.userHash) traits.user_hash = opts.userHash; if (opts.user_hash) traits.user_hash = opts.user_hash; if (this.options.inbox) { traits.widget = { activator: this.options.activator }; } var method = this._id !== id ? 'boot': 'update'; this._id = id; // cache for next time window.Intercom(method, traits); }; /** * Group. * * @param {Group} group */ Intercom.prototype.group = function (group) { var props = group.properties(); var id = group.groupId(); if (id) props.id = id; window.Intercom('update', { company: props }); }; /** * Track. * * @param {Track} track */ Intercom.prototype.track = function(track){ window.Intercom('trackUserEvent', track.event(), track.traits()); }; /** * Format a date to Intercom's liking. * * @param {Date} date * @return {Number} */ function formatDate (date) { return Math.floor(date / 1000); } }); require.register("segmentio-analytics.js-integrations/lib/keen-io.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Keen); }; /** * Expose `Keen IO` integration. */ var Keen = exports.Integration = integration('Keen IO') .readyOnInitialize() .global('Keen') .option('projectId', '') .option('readKey', '') .option('writeKey', '') .option('trackNamedPages', true) .option('trackAllPages', false) .option('trackCategorizedPages', true); /** * Initialize. * * https://keen.io/docs/ */ Keen.prototype.initialize = function () { var options = this.options; window.Keen = window.Keen||{configure:function(e){this._cf=e;},addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i]);},setGlobalProperties:function(e){this._gp=e;},onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e);}}; window.Keen.configure({ projectId: options.projectId, writeKey: options.writeKey, readKey: options.readKey }); this.load(); }; /** * Loaded? * * @return {Boolean} */ Keen.prototype.loaded = function () { return !! (window.Keen && window.Keen.Base64); }; /** * Load the Keen IO library. * * @param {Function} callback */ Keen.prototype.load = function (callback) { load('//dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js', callback); }; /** * Page. * * @param {Page} page */ Keen.prototype.page = function (page) { var category = page.category(); var props = page.properties(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Identify. * * TODO: migrate from old `userId` to simpler `id` * * @param {Identify} identify */ Keen.prototype.identify = function (identify) { var traits = identify.traits(); var id = identify.userId(); var user = {}; if (id) user.userId = id; if (traits) user.traits = traits; window.Keen.setGlobalProperties(function() { return { user: user }; }); }; /** * Track. * * @param {Track} track */ Keen.prototype.track = function (track) { window.Keen.addEvent(track.event(), track.properties()); }; }); require.register("segmentio-analytics.js-integrations/lib/kissmetrics.js", function(exports, require, module){ var alias = require('alias'); var Batch = require('batch'); var callback = require('callback'); var integration = require('integration'); var is = require('is'); var load = require('load-script'); var push = require('global-queue')('_kmq'); var Track = require('facade').Track; var each = require('each'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(KISSmetrics); }; /** * Expose `KISSmetrics` integration. */ var KISSmetrics = exports.Integration = integration('KISSmetrics') .assumesPageview() .readyOnInitialize() .global('_kmq') .global('KM') .global('_kmil') .option('apiKey', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true); /** * Initialize. * * http://support.kissmetrics.com/apis/javascript * * @param {Object} page */ KISSmetrics.prototype.initialize = function (page) { window._kmq = []; this.load(); }; /** * Loaded? * * @return {Boolean} */ KISSmetrics.prototype.loaded = function () { return is.object(window.KM); }; /** * Load. * * @param {Function} callback */ KISSmetrics.prototype.load = function (callback) { var key = this.options.apiKey; var useless = '//i.kissmetrics.com/i.js'; var library = '//doug1izaerwt3.cloudfront.net/' + key + '.1.js'; new Batch() .push(function (done) { load(useless, done); }) // :) .push(function (done) { load(library, done); }) .end(callback); }; /** * Page. * * @param {String} category (optional) * @param {String} name (optional) * @param {Object} properties (optional) * @param {Object} options (optional) */ KISSmetrics.prototype.page = function (page) { var category = page.category(); var name = page.fullName(); var opts = this.options; // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Identify. * * @param {Identify} identify */ KISSmetrics.prototype.identify = function (identify) { var traits = identify.traits(); var id = identify.userId(); if (id) push('identify', id); if (traits) push('set', traits); }; /** * Track. * * @param {Track} track */ KISSmetrics.prototype.track = function (track) { var props = track.properties({ revenue: 'Billing Amount' }); push('record', track.event(), props); }; /** * Alias. * * @param {Alias} to */ KISSmetrics.prototype.alias = function (alias) { push('alias', alias.to(), alias.from()); }; /** * Viewed product. * * @param {Track} track * @api private */ KISSmetrics.prototype.viewedProduct = function(track){ push('record', 'Product Viewed', toProduct(track)); }; /** * Product added. * * @param {Track} track * @api private */ KISSmetrics.prototype.addedProduct = function(track){ push('record', 'Product Added', toProduct(track)); }; /** * Completed order. * * @param {Track} track * @api private */ KISSmetrics.prototype.completedOrder = function(track){ var orderId = track.orderId(); var products = track.products(); // transaction push('record', 'Purchased', { 'Order ID': track.orderId(), 'Order Total': track.total() }); // items window._kmq.push(function(){ var km = window.KM; each(products, function(product, i){ var track = new Track({ properties: product }); var item = toProduct(track); item['Order ID'] = orderId; item._t = km.ts() + i; item._d = 1; km.set(item); }); }); }; /** * Get a product from the given `track`. * * @param {Track} track * @return {Object} * @api private */ function toProduct(track){ return { Quantity: track.quantity(), Price: track.price(), Name: track.name(), SKU: track.sku() }; } }); require.register("segmentio-analytics.js-integrations/lib/klaviyo.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_learnq'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Klaviyo); }; /** * Expose `Klaviyo` integration. */ var Klaviyo = exports.Integration = integration('Klaviyo') .assumesPageview() .readyOnInitialize() .global('_learnq') .option('apiKey', ''); /** * Initialize. * * https://www.klaviyo.com/docs/getting-started * * @param {Object} page */ Klaviyo.prototype.initialize = function (page) { push('account', this.options.apiKey); this.load(); }; /** * Loaded? * * @return {Boolean} */ Klaviyo.prototype.loaded = function () { return !! (window._learnq && window._learnq.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Klaviyo.prototype.load = function (callback) { load('//a.klaviyo.com/media/js/learnmarklet.js', callback); }; /** * Trait aliases. */ var aliases = { id: '$id', email: '$email', firstName: '$first_name', lastName: '$last_name', phone: '$phone_number', title: '$title' }; /** * Identify. * * @param {Identify} identify */ Klaviyo.prototype.identify = function (identify) { var traits = identify.traits(aliases); if (!traits.$id && !traits.$email) return; push('identify', traits); }; /** * Group. * * @param {Group} group */ Klaviyo.prototype.group = function (group) { var props = group.properties(); if (!props.name) return; push('identify', { $organization: props.name }); }; /** * Track. * * @param {Track} track */ Klaviyo.prototype.track = function (track) { push('track', track.event(), track.properties()); }; }); require.register("segmentio-analytics.js-integrations/lib/leadlander.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(LeadLander); }; /** * Expose `LeadLander` integration. */ var LeadLander = exports.Integration = integration('LeadLander') .assumesPageview() .readyOnLoad() .global('llactid') .global('trackalyzer') .option('accountId', null); /** * Initialize. * * @param {Object} page */ LeadLander.prototype.initialize = function (page) { window.llactid = this.options.accountId; this.load(); }; /** * Loaded? * * @return {Boolean} */ LeadLander.prototype.loaded = function () { return !! window.trackalyzer; }; /** * Load. * * @param {Function} callback */ LeadLander.prototype.load = function (callback) { load('http://t6.trackalyzer.com/trackalyze-nodoc.js', callback); }; }); require.register("segmentio-analytics.js-integrations/lib/livechat.js", function(exports, require, module){ var each = require('each'); var integration = require('integration'); var load = require('load-script'); var clone = require('clone'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(LiveChat); }; /** * Expose `LiveChat` integration. */ var LiveChat = exports.Integration = integration('LiveChat') .assumesPageview() .readyOnLoad() .global('__lc') .option('group', 0) .option('license', ''); /** * Initialize. * * http://www.livechatinc.com/api/javascript-api * * @param {Object} page */ LiveChat.prototype.initialize = function (page) { window.__lc = clone(this.options); this.isLoaded = false; this.load(); }; /** * Loaded? * * @return {Boolean} */ LiveChat.prototype.loaded = function () { return this.isLoaded; }; /** * Load. * * @param {Function} callback */ LiveChat.prototype.load = function (callback) { var self = this; load('//cdn.livechatinc.com/tracking.js', function(err){ if (err) return callback(err); self.isLoaded = true; callback(); }); }; /** * Identify. * * @param {Identify} identify */ LiveChat.prototype.identify = function (identify) { var traits = identify.traits({ userId: 'User ID' }); window.LC_API.set_custom_variables(convert(traits)); }; /** * Convert a traits object into the format LiveChat requires. * * @param {Object} traits * @return {Array} */ function convert (traits) { var arr = []; each(traits, function (key, value) { arr.push({ name: key, value: value }); }); return arr; } }); require.register("segmentio-analytics.js-integrations/lib/lucky-orange.js", function(exports, require, module){ var Identify = require('facade').Identify; var integration = require('integration'); var load = require('load-script'); /** * User ref */ var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(LuckyOrange); user = analytics.user(); }; /** * Expose `LuckyOrange` integration. */ var LuckyOrange = exports.Integration = integration('Lucky Orange') .assumesPageview() .readyOnLoad() .global('_loq') .global('__wtw_watcher_added') .global('__wtw_lucky_site_id') .global('__wtw_lucky_is_segment_io') .global('__wtw_custom_user_data') .option('siteId', null); /** * Initialize. * * @param {Object} page */ LuckyOrange.prototype.initialize = function (page) { window._loq || (window._loq = []); window.__wtw_lucky_site_id = this.options.siteId; this.identify(new Identify({ traits: user.traits(), userId: user.id() })); this.load(); }; /** * Loaded? * * @return {Boolean} */ LuckyOrange.prototype.loaded = function () { return !! window.__wtw_watcher_added; }; /** * Load. * * @param {Function} callback */ LuckyOrange.prototype.load = function (callback) { var cache = Math.floor(new Date().getTime() / 60000); load({ http: 'http://www.luckyorange.com/w.js?' + cache, https: 'https://ssl.luckyorange.com/w.js?' + cache }, callback); }; /** * Identify. * * @param {Identify} identify */ LuckyOrange.prototype.identify = function (identify) { var traits = window.__wtw_custom_user_data = identify.traits(); var email = identify.email(); var name = identify.name(); if (name) traits.name = name; if (email) traits.email = email; }; }); require.register("segmentio-analytics.js-integrations/lib/lytics.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Lytics); }; /** * Expose `Lytics` integration. */ var Lytics = exports.Integration = integration('Lytics') .readyOnInitialize() .global('jstag') .option('cid', '') .option('cookie', 'seerid') .option('delay', 2000) .option('sessionTimeout', 1800) .option('url', '//c.lytics.io'); /** * Options aliases. */ var aliases = { sessionTimeout: 'sessecs' }; /** * Initialize. * * http://admin.lytics.io/doc#jstag * * @param {Object} page */ Lytics.prototype.initialize = function (page) { var options = alias(this.options, aliases); window.jstag = (function () {var t = {_q: [], _c: options, ts: (new Date()).getTime() }; t.send = function() {this._q.push([ 'ready', 'send', Array.prototype.slice.call(arguments) ]); return this; }; return t; })(); this.load(); }; /** * Loaded? * * @return {Boolean} */ Lytics.prototype.loaded = function () { return !! (window.jstag && window.jstag.bind); }; /** * Load the Lytics library. * * @param {Function} callback */ Lytics.prototype.load = function (callback) { load('//c.lytics.io/static/io.min.js', callback); }; /** * Page. * * @param {Page} page */ Lytics.prototype.page = function (page) { window.jstag.send(page.properties()); }; /** * Idenfity. * * @param {Identify} identify */ Lytics.prototype.identify = function (identify) { var traits = identify.traits({ userId: '_uid' }); window.jstag.send(traits); }; /** * Track. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) */ Lytics.prototype.track = function (track) { var props = track.properties(); props._e = track.event(); window.jstag.send(props); }; }); require.register("segmentio-analytics.js-integrations/lib/mixpanel.js", function(exports, require, module){ var alias = require('alias'); var clone = require('clone'); var dates = require('convert-dates'); var integration = require('integration'); var iso = require('to-iso-string'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Mixpanel); }; /** * Expose `Mixpanel` integration. */ var Mixpanel = exports.Integration = integration('Mixpanel') .readyOnLoad() .global('mixpanel') .option('cookieName', '') .option('nameTag', true) .option('pageview', false) .option('people', false) .option('token', '') .option('trackAllPages', false) .option('trackNamedPages', true) .option('trackCategorizedPages', true); /** * Options aliases. */ var optionsAliases = { cookieName: 'cookie_name' }; /** * Initialize. * * https://mixpanel.com/help/reference/javascript#installing * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.init */ Mixpanel.prototype.initialize = function () { (function (c, a) {window.mixpanel = a; var b, d, h, e; a._i = []; a.init = function (b, c, f) {function d(a, b) {var c = b.split('.'); 2 == c.length && (a = a[c[0]], b = c[1]); a[b] = function () {a.push([b].concat(Array.prototype.slice.call(arguments, 0))); }; } var g = a; 'undefined' !== typeof f ? g = a[f] = [] : f = 'mixpanel'; g.people = g.people || []; h = ['disable', 'track', 'track_pageview', 'track_links', 'track_forms', 'register', 'register_once', 'unregister', 'identify', 'alias', 'name_tag', 'set_config', 'people.set', 'people.increment', 'people.track_charge', 'people.append']; for (e = 0; e < h.length; e++) d(g, h[e]); a._i.push([b, c, f]); }; a.__SV = 1.2; })(document, window.mixpanel || []); var options = alias(this.options, optionsAliases); window.mixpanel.init(options.token, options); this.load(); }; /** * Loaded? * * @return {Boolean} */ Mixpanel.prototype.loaded = function () { return !! (window.mixpanel && window.mixpanel.config); }; /** * Load. * * @param {Function} callback */ Mixpanel.prototype.load = function (callback) { load('//cdn.mxpnl.com/libs/mixpanel-2.2.min.js', callback); }; /** * Page. * * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.track_pageview * * @param {String} category (optional) * @param {String} name (optional) * @param {Object} properties (optional) * @param {Object} options (optional) */ Mixpanel.prototype.page = function (page) { var category = page.category(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Trait aliases. */ var traitAliases = { created: '$created', email: '$email', firstName: '$first_name', lastName: '$last_name', lastSeen: '$last_seen', name: '$name', username: '$username', phone: '$phone' }; /** * Identify. * * https://mixpanel.com/help/reference/javascript#super-properties * https://mixpanel.com/help/reference/javascript#user-identity * https://mixpanel.com/help/reference/javascript#storing-user-profiles * * @param {Identify} identify */ Mixpanel.prototype.identify = function (identify) { var username = identify.username(); var email = identify.email(); var id = identify.userId(); // id if (id) window.mixpanel.identify(id); // name tag var nametag = email || username || id; if (nametag) window.mixpanel.name_tag(nametag); // traits traits = identify.traits(traitAliases); window.mixpanel.register(traits); if (this.options.people) window.mixpanel.people.set(traits); }; /** * Track. * * https://mixpanel.com/help/reference/javascript#sending-events * https://mixpanel.com/help/reference/javascript#tracking-revenue * * @param {Track} track */ Mixpanel.prototype.track = function (track) { var props = track.properties(); var revenue = track.revenue(); props = dates(props, iso); window.mixpanel.track(track.event(), props); if (revenue && this.options.people) { window.mixpanel.people.track_charge(revenue); } }; /** * Alias. * * https://mixpanel.com/help/reference/javascript#user-identity * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.alias * * @param {Alias} alias */ Mixpanel.prototype.alias = function (alias) { var mp = window.mixpanel; var to = alias.to(); if (mp.get_distinct_id && mp.get_distinct_id() === to) return; // HACK: internal mixpanel API to ensure we don't overwrite if (mp.get_property && mp.get_property('$people_distinct_id') === to) return; // although undocumented, mixpanel takes an optional original id mp.alias(to, alias.from()); }; }); require.register("segmentio-analytics.js-integrations/lib/mojn.js", function(exports, require, module){ /** * Module dependencies. */ var integration = require('integration'); var load = require('load-script'); var is = require('is'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Mojn); }; /** * Expose `Mojn` */ var Mojn = exports.Integration = integration('Mojn') .option('customerCode', '') .global('_agTrack') .readyOnInitialize(); /** * Initialize. * * @param {Object} page */ Mojn.prototype.initialize = function(){ window._agTrack = window._agTrack || []; window._agTrack.push({ cid: this.options.customerCode }); this.load(); }; /** * Load the Mojn script. * * @param {Function} fn */ Mojn.prototype.load = function(fn) { load('https://track.idtargeting.com/' + this.options.customerCode + '/track.js', fn); }; /** * Loaded? * * @return {Boolean} */ Mojn.prototype.loaded = function () { return is.object(window._agTrack); }; /** * Identify. * * @param {Identify} identify */ Mojn.prototype.identify = function(identify) { var email = identify.email(); if (!email) return; var img = new Image(); img.src = '//matcher.idtargeting.com/analytics.gif?cid=' + this.options.customerCode + '&_mjnctid='+email; img.width = 1; img.height = 1; return img; }; /** * Track. * * @param {Track} event */ Mojn.prototype.track = function(track) { var properties = track.properties(); var revenue = properties.revenue; var currency = properties.currency || ''; var conv = currency + revenue; if (!revenue) return; window._agTrack.push({ conv: conv }); return conv; }; }); require.register("segmentio-analytics.js-integrations/lib/mouseflow.js", function(exports, require, module){ var push = require('global-queue')('_mfq'); var integration = require('integration'); var load = require('load-script'); var each = require('each'); /** * Expose plugin */ module.exports = exports = function(analytics){ analytics.addIntegration(Mouseflow); }; /** * Expose `Mouseflow` */ var Mouseflow = exports.Integration = integration('Mouseflow') .assumesPageview() .readyOnLoad() .global('mouseflow') .global('_mfq') .option('apiKey', '') .option('mouseflowHtmlDelay', 0); /** * Iniitalize * * @param {Object} page */ Mouseflow.prototype.initialize = function(page){ this.load(); }; /** * Loaded? * * @return {Boolean} */ Mouseflow.prototype.loaded = function(){ return !! (window._mfq && [].push != window._mfq.push); }; /** * Load mouseflow. * * @param {Function} fn */ Mouseflow.prototype.load = function(fn){ var apiKey = this.options.apiKey; window.mouseflowHtmlDelay = this.options.mouseflowHtmlDelay; load('//cdn.mouseflow.com/projects/' + apiKey + '.js', fn); }; /** * Page. * * //mouseflow.zendesk.com/entries/22528817-Single-page-websites * * @param {Page} page */ Mouseflow.prototype.page = function(page){ if (!window.mouseflow) return; if ('function' != typeof mouseflow.newPageView) return; mouseflow.newPageView(); }; /** * Identify. * * //mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging * * @param {Identify} identify */ Mouseflow.prototype.identify = function(identify){ set(identify.traits()); }; /** * Track. * * //mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging * * @param {Track} track */ Mouseflow.prototype.track = function(track){ var props = track.properties(); props.event = track.event(); set(props); }; /** * Push the given `hash`. * * @param {Object} hash */ function set(hash){ each(hash, function(k, v){ push('setVariable', k, v); }); } }); require.register("segmentio-analytics.js-integrations/lib/mousestats.js", function(exports, require, module){ var each = require('each'); var integration = require('integration'); var is = require('is'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(MouseStats); }; /** * Expose `MouseStats` integration. */ var MouseStats = exports.Integration = integration('MouseStats') .assumesPageview() .readyOnLoad() .global('msaa') .option('accountNumber', ''); /** * Initialize. * * http://www.mousestats.com/docs/pages/allpages * * @param {Object} page */ MouseStats.prototype.initialize = function (page) { this.load(); }; /** * Loaded? * * @return {Boolean} */ MouseStats.prototype.loaded = function () { return is.fn(window.msaa); }; /** * Load. * * @param {Function} callback */ MouseStats.prototype.load = function (callback) { var number = this.options.accountNumber; var path = number.slice(0,1) + '/' + number.slice(1,2) + '/' + number; var cache = Math.floor(new Date().getTime() / 60000); var partial = '.mousestats.com/js/' + path + '.js?' + cache; var http = 'http://www2' + partial; var https = 'https://ssl' + partial; load({ http: http, https: https }, callback); }; /** * Identify. * * http://www.mousestats.com/docs/wiki/7/how-to-add-custom-data-to-visitor-playbacks * * @param {Identify} identify */ MouseStats.prototype.identify = function (identify) { each(identify.traits(), function (key, value) { window.MouseStatsVisitorPlaybacks.customVariable(key, value); }); }; }); require.register("segmentio-analytics.js-integrations/lib/olark.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var https = require('use-https'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Olark); }; /** * Expose `Olark` integration. */ var Olark = exports.Integration = integration('Olark') .assumesPageview() .readyOnInitialize() .global('olark') .option('identify', true) .option('page', true) .option('siteId', '') .option('track', false); /** * Initialize. * * http://www.olark.com/documentation * * @param {Object} page */ Olark.prototype.initialize = function (page) { window.olark||(function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i,' onl' + 'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()})({loader: "static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]}); window.olark.identify(this.options.siteId); // keep track of the widget's open state var self = this; box('onExpand', function () { self._open = true; }); box('onShrink', function () { self._open = false; }); }; /** * Page. * * @param {Page} page */ Olark.prototype.page = function (page) { if (!this.options.page || !this._open) return; var props = page.properties(); var name = page.fullName(); if (!name && !props.url) return; var msg = name ? name.toLowerCase() + ' page' : props.url; chat('sendNotificationToOperator', { body: 'looking at ' + msg // lowercase since olark does }); }; /** * Identify. * * @param {String} id (optional) * @param {Object} traits (optional) * @param {Object} options (optional) */ Olark.prototype.identify = function (identify) { if (!this.options.identify) return; var username = identify.username(); var traits = identify.traits(); var id = identify.userId(); var email = identify.email(); var phone = identify.phone(); var name = identify.name() || identify.firstName(); visitor('updateCustomFields', traits); if (email) visitor('updateEmailAddress', { emailAddress: email }); if (phone) visitor('updatePhoneNumber', { phoneNumber: phone }); // figure out best name if (name) visitor('updateFullName', { fullName: name }); // figure out best nickname var nickname = name || email || username || id; if (name && email) nickname += ' (' + email + ')'; if (nickname) chat('updateVisitorNickname', { snippet: nickname }); }; /** * Track. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) */ Olark.prototype.track = function (track) { if (!this.options.track || !this._open) return; chat('sendNotificationToOperator', { body: 'visitor triggered "' + track.event() + '"' // lowercase since olark does }); }; /** * Helper method for Olark box API calls. * * @param {String} action * @param {Object} value */ function box (action, value) { window.olark('api.box.' + action, value); } /** * Helper method for Olark visitor API calls. * * @param {String} action * @param {Object} value */ function visitor (action, value) { window.olark('api.visitor.' + action, value); } /** * Helper method for Olark chat API calls. * * @param {String} action * @param {Object} value */ function chat (action, value) { window.olark('api.chat.' + action, value); } }); require.register("segmentio-analytics.js-integrations/lib/optimizely.js", function(exports, require, module){ var bind = require('bind'); var callback = require('callback'); var each = require('each'); var integration = require('integration'); var push = require('global-queue')('optimizely'); var tick = require('next-tick'); /** * Analytics reference. */ var analytics; /** * Expose plugin. */ module.exports = exports = function (ajs) { ajs.addIntegration(Optimizely); analytics = ajs; // store for later }; /** * Expose `Optimizely` integration. */ var Optimizely = exports.Integration = integration('Optimizely') .readyOnInitialize() .option('variations', true) .option('trackNamedPages', true) .option('trackCategorizedPages', true); /** * Initialize. * * https://www.optimizely.com/docs/api#function-calls */ Optimizely.prototype.initialize = function () { if (this.options.variations) tick(this.replay); }; /** * Track. * * https://www.optimizely.com/docs/api#track-event * * @param {Track} track */ Optimizely.prototype.track = function (track) { var props = track.properties(); if (props.revenue) props.revenue *= 100; push('trackEvent', track.event(), props); }; /** * Page. * * https://www.optimizely.com/docs/api#track-event * * @param {Page} page */ Optimizely.prototype.page = function (page) { var category = page.category(); var name = page.fullName(); var opts = this.options; // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Replay experiment data as traits to other enabled providers. * * https://www.optimizely.com/docs/api#data-object */ Optimizely.prototype.replay = function () { if (!window.optimizely) return; // in case the snippet isnt on the page var data = window.optimizely.data; if (!data) return; var experiments = data.experiments; var map = data.state.variationNamesMap; var traits = {}; each(map, function (experimentId, variation) { var experiment = experiments[experimentId].name; traits['Experiment: ' + experiment] = variation; }); analytics.identify(traits); }; }); require.register("segmentio-analytics.js-integrations/lib/perfect-audience.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(PerfectAudience); }; /** * Expose `PerfectAudience` integration. */ var PerfectAudience = exports.Integration = integration('Perfect Audience') .assumesPageview() .readyOnLoad() .global('_pa') .option('siteId', ''); /** * Initialize. * * https://www.perfectaudience.com/docs#javascript_api_autoopen * * @param {Object} page */ PerfectAudience.prototype.initialize = function (page) { window._pa = window._pa || {}; this.load(); }; /** * Loaded? * * @return {Boolean} */ PerfectAudience.prototype.loaded = function () { return !! (window._pa && window._pa.track); }; /** * Load. * * @param {Function} callback */ PerfectAudience.prototype.load = function (callback) { var id = this.options.siteId; load('//tag.perfectaudience.com/serve/' + id + '.js', callback); }; /** * Track. * * @param {Track} event */ PerfectAudience.prototype.track = function (track) { window._pa.track(track.event(), track.properties()); }; }); require.register("segmentio-analytics.js-integrations/lib/pingdom.js", function(exports, require, module){ var date = require('load-date'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_prum'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Pingdom); }; /** * Expose `Pingdom` integration. */ var Pingdom = exports.Integration = integration('Pingdom') .assumesPageview() .readyOnLoad() .global('_prum') .option('id', ''); /** * Initialize. * * @param {Object} page */ Pingdom.prototype.initialize = function (page) { window._prum = window._prum || []; push('id', this.options.id); push('mark', 'firstbyte', date.getTime()); this.load(); }; /** * Loaded? * * @return {Boolean} */ Pingdom.prototype.loaded = function () { return !! (window._prum && window._prum.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Pingdom.prototype.load = function (callback) { load('//rum-static.pingdom.net/prum.min.js', callback); }; }); require.register("segmentio-analytics.js-integrations/lib/preact.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var convertDates = require('convert-dates'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_lnq'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Preact); }; /** * Expose `Preact` integration. */ var Preact = exports.Integration = integration('Preact') .assumesPageview() .readyOnInitialize() .global('_lnq') .option('projectCode', ''); /** * Initialize. * * http://www.preact.io/api/javascript * * @param {Object} page */ Preact.prototype.initialize = function (page) { window._lnq = window._lnq || []; push('_setCode', this.options.projectCode); this.load(); }; /** * Loaded? * * @return {Boolean} */ Preact.prototype.loaded = function () { return !! (window._lnq && window._lnq.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Preact.prototype.load = function (callback) { load('//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js', callback); }; /** * Identify. * * @param {Identify} identify */ Preact.prototype.identify = function (identify) { if (!identify.userId()) return; var traits = identify.traits({ created: 'created_at' }); traits = convertDates(traits, convertDate); push('_setPersonData', { name: identify.name(), email: identify.email(), uid: identify.userId(), properties: traits }); }; /** * Group. * * @param {String} id * @param {Object} properties (optional) * @param {Object} options (optional) */ Preact.prototype.group = function (group) { if (!group.groupId()) return; push('_setAccount', group.traits()); }; /** * Track. * * @param {Track} track */ Preact.prototype.track = function (track) { var props = track.properties(); var revenue = track.revenue(); var event = track.event(); var special = { name: event }; if (revenue) { special.revenue = revenue * 100; delete props.revenue; } if (props.note) { special.note = props.note; delete props.note; } push('_logEvent', special, props); }; /** * Convert a `date` to a format Preact supports. * * @param {Date} date * @return {Number} */ function convertDate (date) { return Math.floor(date / 1000); } }); require.register("segmentio-analytics.js-integrations/lib/qualaroo.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_kiq'); var Facade = require('facade'); var Identify = Facade.Identify; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Qualaroo); }; /** * Expose `Qualaroo` integration. */ var Qualaroo = exports.Integration = integration('Qualaroo') .assumesPageview() .readyOnInitialize() .global('_kiq') .option('customerId', '') .option('siteToken', '') .option('track', false); /** * Initialize. * * @param {Object} page */ Qualaroo.prototype.initialize = function (page) { window._kiq = window._kiq || []; this.load(); }; /** * Loaded? * * @return {Boolean} */ Qualaroo.prototype.loaded = function () { return !! (window._kiq && window._kiq.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Qualaroo.prototype.load = function (callback) { var token = this.options.siteToken; var id = this.options.customerId; load('//s3.amazonaws.com/ki.js/' + id + '/' + token + '.js', callback); }; /** * Identify. * * http://help.qualaroo.com/customer/portal/articles/731085-identify-survey-nudge-takers * http://help.qualaroo.com/customer/portal/articles/731091-set-additional-user-properties * * @param {Identify} identify */ Qualaroo.prototype.identify = function (identify) { var traits = identify.traits(); var id = identify.userId(); var email = identify.email(); if (email) id = email; if (id) push('identify', id); if (traits) push('set', traits); }; /** * Track. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) */ Qualaroo.prototype.track = function (track) { if (!this.options.track) return; var event = track.event(); var traits = {}; traits['Triggered: ' + event] = true; this.identify(new Identify({ traits: traits })); }; }); require.register("segmentio-analytics.js-integrations/lib/quantcast.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_qevents', { wrap: false }); /** * User reference. */ var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Quantcast); user = analytics.user(); // store for later }; /** * Expose `Quantcast` integration. */ var Quantcast = exports.Integration = integration('Quantcast') .assumesPageview() .readyOnInitialize() .global('_qevents') .global('__qc') .option('pCode', null) .option('labelPages', false); /** * Initialize. * * https://www.quantcast.com/learning-center/guides/using-the-quantcast-asynchronous-tag/ * https://www.quantcast.com/help/cross-platform-audience-measurement-guide/ * * @param {Object} page */ Quantcast.prototype.initialize = function (page) { page = page || {}; window._qevents = window._qevents || []; var opts = this.options; var settings = { qacct: opts.pCode }; if (user.id()) settings.uid = user.id(); push(settings); this.load(); }; /** * Loaded? * * @return {Boolean} */ Quantcast.prototype.loaded = function () { return !! window.__qc; }; /** * Load. * * @param {Function} callback */ Quantcast.prototype.load = function (callback) { load({ http: 'http://edge.quantserve.com/quant.js', https: 'https://secure.quantserve.com/quant.js' }, callback); }; /** * Page. * * https://cloudup.com/cBRRFAfq6mf * * @param {Page} page */ Quantcast.prototype.page = function (page) { var settings = { event: 'refresh', qacct: this.options.pCode, }; if (user.id()) settings.uid = user.id(); push(settings); }; /** * Identify. * * https://www.quantcast.com/help/cross-platform-audience-measurement-guide/ * * @param {String} id (optional) */ Quantcast.prototype.identify = function (identify) { // edit the initial quantcast settings var id = identify.userId(); if (id) window._qevents[0].uid = id; }; /** * Track. * * https://cloudup.com/cBRRFAfq6mf * * @param {Track} track */ Quantcast.prototype.track = function (track) { var settings = { event: 'click', qacct: this.options.pCode }; if (user.id()) settings.uid = user.id(); push(settings); }; }); require.register("segmentio-analytics.js-integrations/lib/rollbar.js", function(exports, require, module){ var callback = require('callback'); var clone = require('clone'); var extend = require('extend'); var integration = require('integration'); var load = require('load-script'); var onError = require('on-error'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Rollbar); }; /** * Expose `Rollbar` integration. */ var Rollbar = exports.Integration = integration('Rollbar') .readyOnInitialize() .assumesPageview() .global('_rollbar') .option('accessToken', '') .option('identify', true); /** * Initialize. * * https://rollbar.com/docs/notifier/rollbar.js/ * * @param {Object} page */ Rollbar.prototype.initialize = function (page) { var options = this.options; window._rollbar = window._rollbar || window._ratchet || [options.accessToken, options]; onError(function() { window._rollbar.push.apply(window._rollbar, arguments); }); this.load(); }; /** * Loaded? * * @return {Boolean} */ Rollbar.prototype.loaded = function () { return !! (window._rollbar && window._rollbar.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Rollbar.prototype.load = function (callback) { load('//d37gvrvc0wt4s1.cloudfront.net/js/1/rollbar.min.js', callback); }; /** * Identify. * * @param {Identify} identify */ Rollbar.prototype.identify = function (identify) { if (!this.options.identify) return; var traits = identify.traits(); var rollbar = window._rollbar; var params = rollbar.shift ? rollbar[1] = rollbar[1] || {} : rollbar.extraParams = rollbar.extraParams || {}; params.person = params.person || {}; extend(params.person, traits); }; }); require.register("segmentio-analytics.js-integrations/lib/saasquatch.js", function(exports, require, module){ /** * Module dependencies. */ var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function(analytics){ analytics.addIntegration(SaaSquatch); }; /** * Expose `SaaSquatch` integration. */ var SaaSquatch = exports.Integration = integration('SaaSquatch') .readyOnInitialize() .option('tenantAlias', '') .global('_sqh'); /** * Initialize * * @param {Page} page */ SaaSquatch.prototype.initialize = function(page){}; /** * Loaded? * * @return {Boolean} */ SaaSquatch.prototype.loaded = function(){ return window._sqh && window._sqh.push != [].push; }; /** * Load the SaaSquatch library. * * @param {Function} fn */ SaaSquatch.prototype.load = function(fn){ load('//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js', fn); }; /** * Identify. * * @param {Facade} identify */ SaaSquatch.prototype.identify = function(identify){ var sqh = window._sqh = window._sqh || []; var accountId = identify.proxy('traits.accountId'); var image = identify.proxy('traits.referralImage'); var opts = identify.options(this.name); var id = identify.userId(); var email = identify.email(); if (!(id || email)) return; if (this.called) return; var init = { tenant_alias: this.options.tenantAlias, first_name: identify.firstName(), last_name: identify.lastName(), user_image: identify.avatar(), email: email, user_id: id, }; if (accountId) init.account_id = accountId; if (opts.checksum) init.checksum = opts.checksum; if (image) init.fb_share_image = image; sqh.push(['init', init]); this.called = true; this.load(); }; }); require.register("segmentio-analytics.js-integrations/lib/sentry.js", function(exports, require, module){ var integration = require('integration'); var is = require('is'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Sentry); }; /** * Expose `Sentry` integration. */ var Sentry = exports.Integration = integration('Sentry') .readyOnLoad() .global('Raven') .option('config', ''); /** * Initialize. * * http://raven-js.readthedocs.org/en/latest/config/index.html */ Sentry.prototype.initialize = function () { var config = this.options.config; this.load(function () { // for now, raven basically requires `install` to be called // https://github.com/getsentry/raven-js/blob/master/src/raven.js#L113 window.Raven.config(config).install(); }); }; /** * Loaded? * * @return {Boolean} */ Sentry.prototype.loaded = function () { return is.object(window.Raven); }; /** * Load. * * @param {Function} callback */ Sentry.prototype.load = function (callback) { load('//cdn.ravenjs.com/1.1.10/native/raven.min.js', callback); }; /** * Identify. * * @param {Identify} identify */ Sentry.prototype.identify = function (identify) { window.Raven.setUser(identify.traits()); }; }); require.register("segmentio-analytics.js-integrations/lib/snapengage.js", function(exports, require, module){ var integration = require('integration'); var is = require('is'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(SnapEngage); }; /** * Expose `SnapEngage` integration. */ var SnapEngage = exports.Integration = integration('SnapEngage') .assumesPageview() .readyOnLoad() .global('SnapABug') .option('apiKey', ''); /** * Initialize. * * http://help.snapengage.com/installation-guide-getting-started-in-a-snap/ * * @param {Object} page */ SnapEngage.prototype.initialize = function (page) { this.load(); }; /** * Loaded? * * @return {Boolean} */ SnapEngage.prototype.loaded = function () { return is.object(window.SnapABug); }; /** * Load. * * @param {Function} callback */ SnapEngage.prototype.load = function (callback) { var key = this.options.apiKey; var url = '//commondatastorage.googleapis.com/code.snapengage.com/js/' + key + '.js'; load(url, callback); }; /** * Identify. * * @param {Identify} identify */ SnapEngage.prototype.identify = function (identify) { var email = identify.email(); if (!email) return; window.SnapABug.setUserEmail(email); }; }); require.register("segmentio-analytics.js-integrations/lib/spinnakr.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Spinnakr); }; /** * Expose `Spinnakr` integration. */ var Spinnakr = exports.Integration = integration('Spinnakr') .assumesPageview() .readyOnLoad() .global('_spinnakr_site_id') .global('_spinnakr') .option('siteId', ''); /** * Initialize. * * @param {Object} page */ Spinnakr.prototype.initialize = function (page) { window._spinnakr_site_id = this.options.siteId; this.load(); }; /** * Loaded? * * @return {Boolean} */ Spinnakr.prototype.loaded = function () { return !! window._spinnakr; }; /** * Load. * * @param {Function} callback */ Spinnakr.prototype.load = function (callback) { load('//d3ojzyhbolvoi5.cloudfront.net/js/so.js', callback); }; }); require.register("segmentio-analytics.js-integrations/lib/tapstream.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); var slug = require('slug'); var push = require('global-queue')('_tsq'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Tapstream); }; /** * Expose `Tapstream` integration. */ var Tapstream = exports.Integration = integration('Tapstream') .assumesPageview() .readyOnInitialize() .global('_tsq') .option('accountName', '') .option('trackAllPages', true) .option('trackNamedPages', true) .option('trackCategorizedPages', true); /** * Initialize. * * @param {Object} page */ Tapstream.prototype.initialize = function (page) { window._tsq = window._tsq || []; push('setAccountName', this.options.accountName); this.load(); }; /** * Loaded? * * @return {Boolean} */ Tapstream.prototype.loaded = function () { return !! (window._tsq && window._tsq.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Tapstream.prototype.load = function (callback) { load('//cdn.tapstream.com/static/js/tapstream.js', callback); }; /** * Page. * * @param {Page} page */ Tapstream.prototype.page = function (page) { var category = page.category(); var opts = this.options; var name = page.fullName(); // all pages if (opts.trackAllPages) { this.track(page.track()); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Track. * * @param {Track} track */ Tapstream.prototype.track = function (track) { var props = track.properties(); push('fireHit', slug(track.event()), [props.url]); // needs events as slugs }; }); require.register("segmentio-analytics.js-integrations/lib/trakio.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var clone = require('clone'); var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Trakio); }; /** * Expose `Trakio` integration. */ var Trakio = exports.Integration = integration('trak.io') .assumesPageview() .readyOnInitialize() .global('trak') .option('token', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true); /** * Options aliases. */ var optionsAliases = { initialPageview: 'auto_track_page_view' }; /** * Initialize. * * https://docs.trak.io * * @param {Object} page */ Trakio.prototype.initialize = function (page) { var self = this; var options = this.options; window.trak = window.trak || []; window.trak.io = window.trak.io || {}; window.trak.io.load = function(e) {self.load(); var r = function(e) {return function() {window.trak.push([e].concat(Array.prototype.slice.call(arguments,0))); }; } ,i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"]; for (var s=0;s<i.length;s++) window.trak.io[i[s]]=r(i[s]); window.trak.io.initialize.apply(window.trak.io,arguments); }; window.trak.io.load(options.token, alias(options, optionsAliases)); this.load(); }; /** * Loaded? * * @return {Boolean} */ Trakio.prototype.loaded = function () { return !! (window.trak && window.trak.loaded); }; /** * Load the trak.io library. * * @param {Function} callback */ Trakio.prototype.load = function (callback) { load('//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js', callback); }; /** * Page. * * @param {Page} page */ Trakio.prototype.page = function (page) { var category = page.category(); var props = page.properties(); var name = page.fullName(); window.trak.io.page_view(props.path, name || props.title); // named pages if (name && this.options.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && this.options.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Trait aliases. * * http://docs.trak.io/properties.html#special */ var traitAliases = { avatar: 'avatar_url', firstName: 'first_name', lastName: 'last_name' }; /** * Identify. * * @param {Identify} identify */ Trakio.prototype.identify = function (identify) { var traits = identify.traits(traitAliases); var id = identify.userId(); if (id) { window.trak.io.identify(id, traits); } else { window.trak.io.identify(traits); } }; /** * Group. * * @param {String} id (optional) * @param {Object} properties (optional) * @param {Object} options (optional) * * TODO: add group * TODO: add `trait.company/organization` from trak.io docs http://docs.trak.io/properties.html#special */ /** * Track. * * @param {Track} track */ Trakio.prototype.track = function (track) { window.trak.io.track(track.event(), track.properties()); }; /** * Alias. * * @param {Alias} alias */ Trakio.prototype.alias = function (alias) { if (!window.trak.io.distinct_id) return; var from = alias.from(); var to = alias.to(); if (to === window.trak.io.distinct_id()) return; if (from) { window.trak.io.alias(from, to); } else { window.trak.io.alias(to); } }; }); require.register("segmentio-analytics.js-integrations/lib/twitter-ads.js", function(exports, require, module){ var pixel = require('load-pixel')('//analytics.twitter.com/i/adsct'); var integration = require('integration'); /** * Expose plugin */ module.exports = exports = function(analytics){ analytics.addIntegration(TwitterAds); }; /** * Expose `load` */ exports.load = pixel; /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `TwitterAds` */ var TwitterAds = exports.Integration = integration('Twitter Ads') .readyOnInitialize() .option('events', {}); /** * Track. * * @param {Track} track */ TwitterAds.prototype.track = function(track){ var events = this.options.events; var event = track.event(); if (!has.call(events, event)) return; return exports.load({ txn_id: events[event], p_id: 'Twitter' }); }; }); require.register("segmentio-analytics.js-integrations/lib/usercycle.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_uc'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Usercycle); }; /** * Expose `Usercycle` integration. */ var Usercycle = exports.Integration = integration('USERcycle') .assumesPageview() .readyOnInitialize() .global('_uc') .option('key', ''); /** * Initialize. * * http://docs.usercycle.com/javascript_api * * @param {Object} page */ Usercycle.prototype.initialize = function (page) { push('_key', this.options.key); this.load(); }; /** * Loaded? * * @return {Boolean} */ Usercycle.prototype.loaded = function () { return !! (window._uc && window._uc.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Usercycle.prototype.load = function (callback) { load('//api.usercycle.com/javascripts/track.js', callback); }; /** * Identify. * * @param {Identify} identify */ Usercycle.prototype.identify = function (identify) { var traits = identify.traits(); var id = identify.userId(); if (id) push('uid', id); // there's a special `came_back` event used for retention and traits push('action', 'came_back', traits); }; /** * Track. * * @param {Track} track */ Usercycle.prototype.track = function (track) { push('action', track.event(), track.properties({ revenue: 'revenue_amount' })); }; }); require.register("segmentio-analytics.js-integrations/lib/userfox.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var convertDates = require('convert-dates'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_ufq'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Userfox); }; /** * Expose `Userfox` integration. */ var Userfox = exports.Integration = integration('userfox') .assumesPageview() .readyOnInitialize() .global('_ufq') .option('clientId', ''); /** * Initialize. * * https://www.userfox.com/docs/ * * @param {Object} page */ Userfox.prototype.initialize = function (page) { window._ufq = []; this.load(); }; /** * Loaded? * * @return {Boolean} */ Userfox.prototype.loaded = function () { return !! (window._ufq && window._ufq.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Userfox.prototype.load = function (callback) { load('//d2y71mjhnajxcg.cloudfront.net/js/userfox-stable.js', callback); }; /** * Identify. * * https://www.userfox.com/docs/#custom-data * * @param {Identify} identify */ Userfox.prototype.identify = function (identify) { var traits = identify.traits({ created: 'signup_date' }); var email = identify.email(); if (!email) return; // initialize the library with the email now that we have it push('init', { clientId: this.options.clientId, email: email }); traits = convertDates(traits, formatDate); push('track', traits); }; /** * Convert a `date` to a format userfox supports. * * @param {Date} date * @return {String} */ function formatDate (date) { return Math.round(date.getTime() / 1000).toString(); } }); require.register("segmentio-analytics.js-integrations/lib/uservoice.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var clone = require('clone'); var convertDates = require('convert-dates'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('UserVoice'); var unix = require('to-unix-timestamp'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(UserVoice); }; /** * Expose `UserVoice` integration. */ var UserVoice = exports.Integration = integration('UserVoice') .assumesPageview() .readyOnInitialize() .global('UserVoice') .global('showClassicWidget') .option('apiKey', '') .option('classic', false) .option('forumId', null) .option('showWidget', true) .option('mode', 'contact') .option('accentColor', '#448dd6') .option('smartvote', true) .option('trigger', null) .option('triggerPosition', 'bottom-right') .option('triggerColor', '#ffffff') .option('triggerBackgroundColor', 'rgba(46, 49, 51, 0.6)') // BACKWARDS COMPATIBILITY: classic options .option('classicMode', 'full') .option('primaryColor', '#cc6d00') .option('linkColor', '#007dbf') .option('defaultMode', 'support') .option('tabLabel', 'Feedback & Support') .option('tabColor', '#cc6d00') .option('tabPosition', 'middle-right') .option('tabInverted', false); /** * When in "classic" mode, on `construct` swap all of the method to point to * their classic counterparts. */ UserVoice.on('construct', function (integration) { if (!integration.options.classic) return; integration.group = undefined; integration.identify = integration.identifyClassic; integration.initialize = integration.initializeClassic; }); /** * Initialize. * * @param {Object} page */ UserVoice.prototype.initialize = function (page) { var options = this.options; var opts = formatOptions(options); push('set', opts); push('autoprompt', {}); if (options.showWidget) { options.trigger ? push('addTrigger', options.trigger, opts) : push('addTrigger', opts); } this.load(); }; /** * Loaded? * * @return {Boolean} */ UserVoice.prototype.loaded = function () { return !! (window.UserVoice && window.UserVoice.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ UserVoice.prototype.load = function (callback) { var key = this.options.apiKey; load('//widget.uservoice.com/' + key + '.js', callback); }; /** * Identify. * * @param {Identify} identify */ UserVoice.prototype.identify = function (identify) { var traits = identify.traits({ created: 'created_at' }); traits = convertDates(traits, unix); push('identify', traits); }; /** * Group. * * @param {Group} group */ UserVoice.prototype.group = function (group) { var traits = group.traits({ created: 'created_at' }); traits = convertDates(traits, unix); push('identify', { account: traits }); }; /** * Initialize (classic). * * @param {Object} options * @param {Function} ready */ UserVoice.prototype.initializeClassic = function () { var options = this.options; window.showClassicWidget = showClassicWidget; // part of public api if (options.showWidget) showClassicWidget('showTab', formatClassicOptions(options)); this.load(); }; /** * Identify (classic). * * @param {Identify} identify */ UserVoice.prototype.identifyClassic = function (identify) { push('setCustomFields', identify.traits()); }; /** * Format the options for UserVoice. * * @param {Object} options * @return {Object} */ function formatOptions (options) { return alias(options, { forumId: 'forum_id', accentColor: 'accent_color', smartvote: 'smartvote_enabled', triggerColor: 'trigger_color', triggerBackgroundColor: 'trigger_background_color', triggerPosition: 'trigger_position' }); } /** * Format the classic options for UserVoice. * * @param {Object} options * @return {Object} */ function formatClassicOptions (options) { return alias(options, { forumId: 'forum_id', classicMode: 'mode', primaryColor: 'primary_color', tabPosition: 'tab_position', tabColor: 'tab_color', linkColor: 'link_color', defaultMode: 'default_mode', tabLabel: 'tab_label', tabInverted: 'tab_inverted' }); } /** * Show the classic version of the UserVoice widget. This method is usually part * of UserVoice classic's public API. * * @param {String} type ('showTab' or 'showLightbox') * @param {Object} options (optional) */ function showClassicWidget (type, options) { type = type || 'showLightbox'; push(type, 'classic_widget', options); } }); require.register("segmentio-analytics.js-integrations/lib/vero.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_veroq'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Vero); }; /** * Expose `Vero` integration. */ var Vero = exports.Integration = integration('Vero') .assumesPageview() .readyOnInitialize() .global('_veroq') .option('apiKey', ''); /** * Initialize. * * https://github.com/getvero/vero-api/blob/master/sections/js.md * * @param {Object} page */ Vero.prototype.initialize = function (pgae) { push('init', { api_key: this.options.apiKey }); this.load(); }; /** * Loaded? * * @return {Boolean} */ Vero.prototype.loaded = function () { return !! (window._veroq && window._veroq.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Vero.prototype.load = function (callback) { load('//d3qxef4rp70elm.cloudfront.net/m.js', callback); }; /** * Identify. * * https://github.com/getvero/vero-api/blob/master/sections/js.md#user-identification * * @param {Identify} identify */ Vero.prototype.identify = function (identify) { var traits = identify.traits(); var email = identify.email(); var id = identify.userId(); if (!id || !email) return; // both required push('user', traits); }; /** * Track. * * https://github.com/getvero/vero-api/blob/master/sections/js.md#tracking-events * * @param {Track} track */ Vero.prototype.track = function (track) { push('track', track.event(), track.properties()); }; }); require.register("segmentio-analytics.js-integrations/lib/visual-website-optimizer.js", function(exports, require, module){ var callback = require('callback'); var each = require('each'); var integration = require('integration'); var tick = require('next-tick'); /** * Analytics reference. */ var analytics; /** * Expose plugin. */ module.exports = exports = function (ajs) { ajs.addIntegration(VWO); analytics = ajs; }; /** * Expose `VWO` integration. */ var VWO = exports.Integration = integration('Visual Website Optimizer') .readyOnInitialize() .option('replay', true); /** * Initialize. * * http://v2.visualwebsiteoptimizer.com/tools/get_tracking_code.php */ VWO.prototype.initialize = function () { if (this.options.replay) this.replay(); }; /** * Replay the experiments the user has seen as traits to all other integrations. * Wait for the next tick to replay so that the `analytics` object and all of * the integrations are fully initialized. */ VWO.prototype.replay = function () { tick(function () { experiments(function (err, traits) { if (traits) analytics.identify(traits); }); }); }; /** * Get dictionary of experiment keys and variations. * * http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/ * * @param {Function} callback * @return {Object} */ function experiments (callback) { enqueue(function () { var data = {}; var ids = window._vwo_exp_ids; if (!ids) return callback(); each(ids, function (id) { var name = variation(id); if (name) data['Experiment: ' + id] = name; }); callback(null, data); }); } /** * Add a `fn` to the VWO queue, creating one if it doesn't exist. * * @param {Function} fn */ function enqueue (fn) { window._vis_opt_queue = window._vis_opt_queue || []; window._vis_opt_queue.push(fn); } /** * Get the chosen variation's name from an experiment `id`. * * http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/ * * @param {String} id * @return {String} */ function variation (id) { var experiments = window._vwo_exp; if (!experiments) return null; var experiment = experiments[id]; var variationId = experiment.combination_chosen; return variationId ? experiment.comb_n[variationId] : null; } }); require.register("segmentio-analytics.js-integrations/lib/webengage.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); /** * Expose plugin */ module.exports = exports = function(analytics){ analytics.addIntegration(WebEngage); }; /** * Expose `WebEngage` integration */ var WebEngage = exports.Integration = integration('WebEngage') .assumesPageview() .readyOnLoad() .global('_weq') .global('webengage') .option('widgetVersion', '4.0') .option('licenseCode', ''); /** * Initialize. * * @param {Object} page */ WebEngage.prototype.initialize = function(page){ var _weq = window._weq = window._weq || {}; _weq['webengage.licenseCode'] = this.options.licenseCode; _weq['webengage.widgetVersion'] = this.options.widgetVersion; this.load(); }; /** * Loaded? * * @return {Boolean} */ WebEngage.prototype.loaded = function(){ return !! window.webengage; }; /** * Load * * @param {Function} fn */ WebEngage.prototype.load = function(fn){ var path = '/js/widget/webengage-min-v-4.0.js'; load({ https: 'https://ssl.widgets.webengage.com' + path, http: 'http://cdn.widgets.webengage.com' + path }, fn); }; }); require.register("segmentio-analytics.js-integrations/lib/woopra.js", function(exports, require, module){ var each = require('each'); var extend = require('extend'); var integration = require('integration'); var isEmail = require('is-email'); var load = require('load-script'); var type = require('type'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Woopra); }; /** * Expose `Woopra` integration. */ var Woopra = exports.Integration = integration('Woopra') .readyOnLoad() .global('woopra') .option('domain', ''); /** * Initialize. * * http://www.woopra.com/docs/setup/javascript-tracking/ * * @param {Object} page */ Woopra.prototype.initialize = function (page) { (function () {var i, s, z, w = window, d = document, a = arguments, q = 'script', f = ['config', 'track', 'identify', 'visit', 'push', 'call'], c = function () {var i, self = this; self._e = []; for (i = 0; i < f.length; i++) {(function (f) {self[f] = function () {self._e.push([f].concat(Array.prototype.slice.call(arguments, 0))); return self; }; })(f[i]); } }; w._w = w._w || {}; for (i = 0; i < a.length; i++) { w._w[a[i]] = w[a[i]] = w[a[i]] || new c(); } })('woopra'); window.woopra.config({ domain: this.options.domain }); this.load(); }; /** * Loaded? * * @return {Boolean} */ Woopra.prototype.loaded = function () { return !! (window.woopra && window.woopra.loaded); }; /** * Load. * * @param {Function} callback */ Woopra.prototype.load = function (callback) { load('//static.woopra.com/js/w.js', callback); }; /** * Page. * * @param {String} category (optional) */ Woopra.prototype.page = function (page) { var props = page.properties(); var name = page.fullName(); if (name) props.title = name; window.woopra.track('pv', props); }; /** * Identify. * * @param {Identify} identify */ Woopra.prototype.identify = function (identify) { window.woopra.identify(identify.traits()).push(); // `push` sends it off async }; /** * Track. * * @param {Track} track */ Woopra.prototype.track = function (track) { window.woopra.track(track.event(), track.properties()); }; }); require.register("segmentio-analytics.js-integrations/lib/yandex-metrica.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Yandex); }; /** * Expose `Yandex` integration. */ var Yandex = exports.Integration = integration('Yandex Metrica') .assumesPageview() .readyOnInitialize() .global('yandex_metrika_callbacks') .global('Ya') .option('counterId', null); /** * Initialize. * * http://api.yandex.com/metrika/ * https://metrica.yandex.com/22522351?step=2#tab=code * * @param {Object} page */ Yandex.prototype.initialize = function (page) { var id = this.options.counterId; push(function () { window['yaCounter' + id] = new window.Ya.Metrika({ id: id }); }); this.load(); }; /** * Loaded? * * @return {Boolean} */ Yandex.prototype.loaded = function () { return !! (window.Ya && window.Ya.Metrika); }; /** * Load. * * @param {Function} callback */ Yandex.prototype.load = function (callback) { load('//mc.yandex.ru/metrika/watch.js', callback); }; /** * Push a new callback on the global Yandex queue. * * @param {Function} callback */ function push (callback) { window.yandex_metrika_callbacks = window.yandex_metrika_callbacks || []; window.yandex_metrika_callbacks.push(callback); } }); require.register("segmentio-canonical/index.js", function(exports, require, module){ module.exports = function canonical () { var tags = document.getElementsByTagName('link'); for (var i = 0, tag; tag = tags[i]; i++) { if ('canonical' == tag.getAttribute('rel')) return tag.getAttribute('href'); } }; }); require.register("segmentio-extend/index.js", function(exports, require, module){ module.exports = function extend (object) { // Takes an unlimited number of extenders. var args = Array.prototype.slice.call(arguments, 1); // For each extender, copy their properties on our object. for (var i = 0, source; source = args[i]; i++) { if (!source) continue; for (var property in source) { object[property] = source[property]; } } return object; }; }); require.register("camshaft-require-component/index.js", function(exports, require, module){ /** * Require a module with a fallback */ module.exports = function(parent) { function require(name, fallback) { try { return parent(name); } catch (e) { try { return parent(fallback || name+"-component"); } catch(e2) { throw e; } } }; // Merge the old properties for (var key in parent) { require[key] = parent[key]; } return require; }; }); require.register("ianstormtaylor-to-camel-case/index.js", function(exports, require, module){ var toSpace = require('to-space-case'); /** * Expose `toCamelCase`. */ module.exports = toCamelCase; /** * Convert a `string` to camel case. * * @param {String} string * @return {String} */ function toCamelCase (string) { return toSpace(string).replace(/\s(\w)/g, function (matches, letter) { return letter.toUpperCase(); }); } }); require.register("ianstormtaylor-to-capital-case/index.js", function(exports, require, module){ var clean = require('to-no-case'); /** * Expose `toCapitalCase`. */ module.exports = toCapitalCase; /** * Convert a `string` to capital case. * * @param {String} string * @return {String} */ function toCapitalCase (string) { return clean(string).replace(/(^|\s)(\w)/g, function (matches, previous, letter) { return previous + letter.toUpperCase(); }); } }); require.register("ianstormtaylor-to-constant-case/index.js", function(exports, require, module){ var snake = require('to-snake-case'); /** * Expose `toConstantCase`. */ module.exports = toConstantCase; /** * Convert a `string` to constant case. * * @param {String} string * @return {String} */ function toConstantCase (string) { return snake(string).toUpperCase(); } }); require.register("ianstormtaylor-to-dot-case/index.js", function(exports, require, module){ var toSpace = require('to-space-case'); /** * Expose `toDotCase`. */ module.exports = toDotCase; /** * Convert a `string` to slug case. * * @param {String} string * @return {String} */ function toDotCase (string) { return toSpace(string).replace(/\s/g, '.'); } }); require.register("ianstormtaylor-to-no-case/index.js", function(exports, require, module){ /** * Expose `toNoCase`. */ module.exports = toNoCase; /** * Test whether a string is camel-case. */ var hasSpace = /\s/; var hasCamel = /[a-z][A-Z]/; var hasSeparator = /[\W_]/; /** * Remove any starting case from a `string`, like camel or snake, but keep * spaces and punctuation that may be important otherwise. * * @param {String} string * @return {String} */ function toNoCase (string) { if (hasSpace.test(string)) return string.toLowerCase(); if (hasSeparator.test(string)) string = unseparate(string); if (hasCamel.test(string)) string = uncamelize(string); return string.toLowerCase(); } /** * Separator splitter. */ var separatorSplitter = /[\W_]+(.|$)/g; /** * Un-separate a `string`. * * @param {String} string * @return {String} */ function unseparate (string) { return string.replace(separatorSplitter, function (m, next) { return next ? ' ' + next : ''; }); } /** * Camelcase splitter. */ var camelSplitter = /(.)([A-Z]+)/g; /** * Un-camelcase a `string`. * * @param {String} string * @return {String} */ function uncamelize (string) { return string.replace(camelSplitter, function (m, previous, uppers) { return previous + ' ' + uppers.toLowerCase().split('').join(' '); }); } }); require.register("ianstormtaylor-to-pascal-case/index.js", function(exports, require, module){ var toSpace = require('to-space-case'); /** * Expose `toPascalCase`. */ module.exports = toPascalCase; /** * Convert a `string` to pascal case. * * @param {String} string * @return {String} */ function toPascalCase (string) { return toSpace(string).replace(/(?:^|\s)(\w)/g, function (matches, letter) { return letter.toUpperCase(); }); } }); require.register("ianstormtaylor-to-sentence-case/index.js", function(exports, require, module){ var clean = require('to-no-case'); /** * Expose `toSentenceCase`. */ module.exports = toSentenceCase; /** * Convert a `string` to camel case. * * @param {String} string * @return {String} */ function toSentenceCase (string) { return clean(string).replace(/[a-z]/i, function (letter) { return letter.toUpperCase(); }); } }); require.register("ianstormtaylor-to-slug-case/index.js", function(exports, require, module){ var toSpace = require('to-space-case'); /** * Expose `toSlugCase`. */ module.exports = toSlugCase; /** * Convert a `string` to slug case. * * @param {String} string * @return {String} */ function toSlugCase (string) { return toSpace(string).replace(/\s/g, '-'); } }); require.register("ianstormtaylor-to-snake-case/index.js", function(exports, require, module){ var toSpace = require('to-space-case'); /** * Expose `toSnakeCase`. */ module.exports = toSnakeCase; /** * Convert a `string` to snake case. * * @param {String} string * @return {String} */ function toSnakeCase (string) { return toSpace(string).replace(/\s/g, '_'); } }); require.register("ianstormtaylor-to-space-case/index.js", function(exports, require, module){ var clean = require('to-no-case'); /** * Expose `toSpaceCase`. */ module.exports = toSpaceCase; /** * Convert a `string` to space case. * * @param {String} string * @return {String} */ function toSpaceCase (string) { return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) { return match ? ' ' + match : ''; }); } }); require.register("component-escape-regexp/index.js", function(exports, require, module){ /** * Escape regexp special characters in `str`. * * @param {String} str * @return {String} * @api public */ module.exports = function(str){ return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g, '\\$1'); }; }); require.register("ianstormtaylor-map/index.js", function(exports, require, module){ var each = require('each'); /** * Map an array or object. * * @param {Array|Object} obj * @param {Function} iterator * @return {Mixed} */ module.exports = function map (obj, iterator) { var arr = []; each(obj, function (o) { arr.push(iterator.apply(null, arguments)); }); return arr; }; }); require.register("ianstormtaylor-title-case-minors/index.js", function(exports, require, module){ module.exports = [ 'a', 'an', 'and', 'as', 'at', 'but', 'by', 'en', 'for', 'from', 'how', 'if', 'in', 'neither', 'nor', 'of', 'on', 'only', 'onto', 'out', 'or', 'per', 'so', 'than', 'that', 'the', 'to', 'until', 'up', 'upon', 'v', 'v.', 'versus', 'vs', 'vs.', 'via', 'when', 'with', 'without', 'yet' ]; }); require.register("ianstormtaylor-to-title-case/index.js", function(exports, require, module){ var capital = require('to-capital-case') , escape = require('escape-regexp') , map = require('map') , minors = require('title-case-minors'); /** * Expose `toTitleCase`. */ module.exports = toTitleCase; /** * Minors. */ var escaped = map(minors, escape); var minorMatcher = new RegExp('[^^]\\b(' + escaped.join('|') + ')\\b', 'ig'); var colonMatcher = /:\s*(\w)/g; /** * Convert a `string` to camel case. * * @param {String} string * @return {String} */ function toTitleCase (string) { return capital(string) .replace(minorMatcher, function (minor) { return minor.toLowerCase(); }) .replace(colonMatcher, function (letter) { return letter.toUpperCase(); }); } }); require.register("ianstormtaylor-case/lib/index.js", function(exports, require, module){ var cases = require('./cases'); /** * Expose `determineCase`. */ module.exports = exports = determineCase; /** * Determine the case of a `string`. * * @param {String} string * @return {String|Null} */ function determineCase (string) { for (var key in cases) { if (key == 'none') continue; var convert = cases[key]; if (convert(string) == string) return key; } return null; } /** * Define a case by `name` with a `convert` function. * * @param {String} name * @param {Object} convert */ exports.add = function (name, convert) { exports[name] = cases[name] = convert; }; /** * Add all the `cases`. */ for (var key in cases) { exports.add(key, cases[key]); } }); require.register("ianstormtaylor-case/lib/cases.js", function(exports, require, module){ var camel = require('to-camel-case') , capital = require('to-capital-case') , constant = require('to-constant-case') , dot = require('to-dot-case') , none = require('to-no-case') , pascal = require('to-pascal-case') , sentence = require('to-sentence-case') , slug = require('to-slug-case') , snake = require('to-snake-case') , space = require('to-space-case') , title = require('to-title-case'); /** * Camel. */ exports.camel = camel; /** * Pascal. */ exports.pascal = pascal; /** * Dot. Should precede lowercase. */ exports.dot = dot; /** * Slug. Should precede lowercase. */ exports.slug = slug; /** * Snake. Should precede lowercase. */ exports.snake = snake; /** * Space. Should precede lowercase. */ exports.space = space; /** * Constant. Should precede uppercase. */ exports.constant = constant; /** * Capital. Should precede sentence and title. */ exports.capital = capital; /** * Title. */ exports.title = title; /** * Sentence. */ exports.sentence = sentence; /** * Convert a `string` to lower case from camel, slug, etc. Different that the * usual `toLowerCase` in that it will try to break apart the input first. * * @param {String} string * @return {String} */ exports.lower = function (string) { return none(string).toLowerCase(); }; /** * Convert a `string` to upper case from camel, slug, etc. Different that the * usual `toUpperCase` in that it will try to break apart the input first. * * @param {String} string * @return {String} */ exports.upper = function (string) { return none(string).toUpperCase(); }; /** * Invert each character in a `string` from upper to lower and vice versa. * * @param {String} string * @return {String} */ exports.inverse = function (string) { for (var i = 0, char; char = string[i]; i++) { if (!/[a-z]/i.test(char)) continue; var upper = char.toUpperCase(); var lower = char.toLowerCase(); string[i] = char == upper ? lower : upper; } return string; }; /** * None. */ exports.none = none; }); require.register("segmentio-obj-case/index.js", function(exports, require, module){ var Case = require('case'); var cases = [ Case.upper, Case.lower, Case.snake, Case.pascal, Case.camel, Case.constant, Case.title, Case.capital, Case.sentence ]; /** * Module exports, export */ module.exports = module.exports.find = multiple(find); /** * Export the replacement function, return the modified object */ module.exports.replace = function (obj, key, val) { multiple(replace).apply(this, arguments); return obj; }; /** * Export the delete function, return the modified object */ module.exports.del = function (obj, key) { multiple(del).apply(this, arguments); return obj; }; /** * Compose applying the function to a nested key */ function multiple (fn) { return function (obj, key, val) { var keys = key.split('.'); if (keys.length === 0) return; while (keys.length > 1) { key = keys.shift(); obj = find(obj, key); if (obj === null || obj === undefined) return; } key = keys.shift(); return fn(obj, key, val); }; } /** * Find an object by its key * * find({ first_name : 'Calvin' }, 'firstName') */ function find (obj, key) { for (var i = 0; i < cases.length; i++) { var cased = cases[i](key); if (obj.hasOwnProperty(cased)) return obj[cased]; } } /** * Delete a value for a given key * * del({ a : 'b', x : 'y' }, 'X' }) -> { a : 'b' } */ function del (obj, key) { for (var i = 0; i < cases.length; i++) { var cased = cases[i](key); if (obj.hasOwnProperty(cased)) delete obj[cased]; } return obj; } /** * Replace an objects existing value with a new one * * replace({ a : 'b' }, 'a', 'c') -> { a : 'c' } */ function replace (obj, key, val) { for (var i = 0; i < cases.length; i++) { var cased = cases[i](key); if (obj.hasOwnProperty(cased)) obj[cased] = val; } return obj; } }); require.register("segmentio-facade/lib/index.js", function(exports, require, module){ var Facade = require('./facade'); /** * Expose `Facade` facade. */ module.exports = Facade; /** * Expose specific-method facades. */ Facade.Alias = require('./alias'); Facade.Group = require('./group'); Facade.Identify = require('./identify'); Facade.Track = require('./track'); Facade.Page = require('./page'); }); require.register("segmentio-facade/lib/alias.js", function(exports, require, module){ var Facade = require('./facade'); var component = require('require-component')(require); var inherit = component('inherit'); /** * Expose `Alias` facade. */ module.exports = Alias; /** * Initialize a new `Alias` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @property {String} from * @property {String} to * @property {Object} options */ function Alias (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Alias, Facade); /** * Return type of facade. * * @return {String} */ Alias.prototype.action = function () { return 'alias'; }; /** * Setup some basic proxies. */ Alias.prototype.from = Facade.field('from'); Alias.prototype.to = Facade.field('to'); }); require.register("segmentio-facade/lib/facade.js", function(exports, require, module){ var component = require('require-component')(require); var clone = component('clone'); var isEnabled = component('./is-enabled'); var objCase = component('obj-case'); /** * Expose `Facade`. */ module.exports = Facade; /** * Initialize a new `Facade` with an `obj` of arguments. * * @param {Object} obj */ function Facade (obj) { if (!obj.hasOwnProperty('timestamp')) obj.timestamp = new Date(); else obj.timestamp = new Date(obj.timestamp); this.obj = obj; } /** * Return a proxy function for a `field` that will attempt to first use methods, * and fallback to accessing the underlying object directly. You can specify * deeply nested fields too like: * * this.proxy('options.Librato'); * * @param {String} field */ Facade.prototype.proxy = function (field) { var fields = field.split('.'); field = fields.shift(); // Call a function at the beginning to take advantage of facaded fields var obj = this[field] || this.field(field); if (!obj) return obj; if (typeof obj === 'function') obj = obj.call(this) || {}; if (fields.length === 0) return clone(obj); obj = objCase(obj, fields.join('.')); return clone(obj); }; /** * Directly access a specific `field` from the underlying object, returning a * clone so outsiders don't mess with stuff. * * @param {String} field * @return {Mixed} */ Facade.prototype.field = function (field) { return clone(this.obj[field]); }; /** * Utility method to always proxy a particular `field`. You can specify deeply * nested fields too like: * * Facade.proxy('options.Librato'); * * @param {String} field * @return {Function} */ Facade.proxy = function (field) { return function () { return this.proxy(field); }; }; /** * Utility method to directly access a `field`. * * @param {String} field * @return {Function} */ Facade.field = function (field) { return function () { return this.field(field); }; }; /** * Get the basic json object of this facade. * * @return {Object} */ Facade.prototype.json = function () { return clone(this.obj); }; /** * Get the options of a call (formerly called "context"). If you pass an * integration name, it will get the options for that specific integration, or * undefined if the integration is not enabled. * * @param {String} integration (optional) * @return {Object or Null} */ Facade.prototype.options = function (integration) { var options = clone(this.obj.options || this.obj.context) || {}; if (!integration) return clone(options); if (!this.enabled(integration)) return; options = options[integration] || objCase(options, integration) || {}; return typeof options === 'boolean' ? {} : clone(options); }; /** * Check whether an integration is enabled. * * @param {String} integration * @return {Boolean} */ Facade.prototype.enabled = function (integration) { var allEnabled = this.proxy('options.providers.all'); if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('options.all'); if (typeof allEnabled !== 'boolean') allEnabled = true; var enabled = allEnabled && isEnabled(integration); var options = this.options(); // If the integration is explicitly enabled or disabled, use that // First, check options.providers for backwards compatibility if (options.providers && options.providers.hasOwnProperty(integration)) { enabled = options.providers[integration]; } // Next, check for the integration's existence in 'options' to enable it. // If the settings are a boolean, use that, otherwise it should be enabled. if (options.hasOwnProperty(integration)) { var settings = options[integration]; if (typeof settings === 'boolean') { enabled = settings; } else { enabled = true; } } return enabled ? true : false; }; /** * Get the `userAgent` option. * * @return {String} */ Facade.prototype.userAgent = function () {}; /** * Check whether the user is active. * * @return {Boolean} */ Facade.prototype.active = function () { var active = this.proxy('options.active'); if (active === null || active === undefined) active = true; return active; }; /** * Setup some basic proxies. */ Facade.prototype.channel = Facade.field('channel'); Facade.prototype.timestamp = Facade.field('timestamp'); Facade.prototype.ip = Facade.proxy('options.ip'); }); require.register("segmentio-facade/lib/group.js", function(exports, require, module){ var Facade = require('./facade'); var component = require('require-component')(require); var inherit = component('inherit'); var newDate = component('new-date'); /** * Expose `Group` facade. */ module.exports = Group; /** * Initialize a new `Group` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @param {String} userId * @param {String} groupId * @param {Object} properties * @param {Object} options */ function Group (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade` */ inherit(Group, Facade); /** * Get the facade's action. */ Group.prototype.action = function () { return 'group'; }; /** * Setup some basic proxies. */ Group.prototype.groupId = Facade.field('groupId'); Group.prototype.userId = Facade.field('userId'); /** * Get created or createdAt. * * @return {Date} */ Group.prototype.created = function(){ var created = this.proxy('traits.createdAt') || this.proxy('traits.created') || this.proxy('properties.createdAt') || this.proxy('properties.created'); if (created) return newDate(created); }; /** * Get the group's traits. * * @param {Object} aliases * @return {Object} */ Group.prototype.traits = function (aliases) { var ret = this.properties(); var id = this.groupId(); aliases = aliases || {}; if (id) ret.id = id; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('traits.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return ret; }; /** * Get traits or properties. * * TODO: remove me * * @return {Object} */ Group.prototype.properties = function(){ return this.field('traits') || this.field('properties') || {}; }; }); require.register("segmentio-facade/lib/page.js", function(exports, require, module){ var component = require('require-component')(require); var Facade = component('./facade'); var inherit = component('inherit'); var Track = require('./track'); /** * Expose `Page` facade */ module.exports = Page; /** * Initialize new `Page` facade with `dictionary`. * * @param {Object} dictionary * @param {String} category * @param {String} name * @param {Object} traits * @param {Object} options */ function Page(dictionary){ Facade.call(this, dictionary); } /** * Inherit from `Facade` */ inherit(Page, Facade); /** * Get the facade's action. * * @return {String} */ Page.prototype.action = function(){ return 'page'; }; /** * Proxies */ Page.prototype.category = Facade.field('category'); Page.prototype.name = Facade.field('name'); /** * Get the page properties mixing `category` and `name`. * * @return {Object} */ Page.prototype.properties = function(){ var props = this.field('properties') || {}; var category = this.category(); var name = this.name(); if (category) props.category = category; if (name) props.name = name; return props; }; /** * Get the page fullName. * * @return {String} */ Page.prototype.fullName = function(){ var category = this.category(); var name = this.name(); return name && category ? category + ' ' + name : name; }; /** * Get event with `name`. * * @return {String} */ Page.prototype.event = function(name){ return name ? 'Viewed ' + name + ' Page' : 'Loaded a Page'; }; /** * Convert this Page to a Track facade with `name`. * * @param {String} name * @return {Track} */ Page.prototype.track = function(name){ var props = this.properties(); return new Track({ event: this.event(name), properties: props }); }; }); require.register("segmentio-facade/lib/identify.js", function(exports, require, module){ var component = require('require-component')(require); var clone = component('clone'); var Facade = component('./facade'); var inherit = component('inherit'); var isEmail = component('is-email'); var newDate = component('new-date'); var trim = component('trim'); /** * Expose `Idenfity` facade. */ module.exports = Identify; /** * Initialize a new `Identify` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @param {String} userId * @param {String} sessionId * @param {Object} traits * @param {Object} options */ function Identify (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Identify, Facade); /** * Get the facade's action. */ Identify.prototype.action = function () { return 'identify'; }; /** * Setup some basic proxies. */ Identify.prototype.userId = Facade.field('userId'); Identify.prototype.sessionId = Facade.field('sessionId'); /** * Get the user's traits. * * @param {Object} aliases * @return {Object} */ Identify.prototype.traits = function (aliases) { var ret = this.field('traits') || {}; var id = this.userId(); aliases = aliases || {}; if (id) ret.id = id; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('traits.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return ret; }; /** * Get the user's email, falling back to their user ID if it's a valid email. * * @return {String} */ Identify.prototype.email = function () { var email = this.proxy('traits.email'); if (email) return email; var userId = this.userId(); if (isEmail(userId)) return userId; }; /** * Get the user's created date, optionally looking for `createdAt` since lots of * people do that instead. * * @return {Date or Undefined} */ Identify.prototype.created = function () { var created = this.proxy('traits.created') || this.proxy('traits.createdAt'); if (created) return newDate(created); }; /** * Get the company created date. * * @return {Date or undefined} */ Identify.prototype.companyCreated = function(){ var created = this.proxy('traits.company.created') || this.proxy('traits.company.createdAt'); if (created) return newDate(created); }; /** * Get the user's name, optionally combining a first and last name if that's all * that was provided. * * @return {String or Undefined} */ Identify.prototype.name = function () { var name = this.proxy('traits.name'); if (typeof name === 'string') return trim(name); var firstName = this.firstName(); var lastName = this.lastName(); if (firstName && lastName) return trim(firstName + ' ' + lastName); }; /** * Get the user's first name, optionally splitting it out of a single name if * that's all that was provided. * * @return {String or Undefined} */ Identify.prototype.firstName = function () { var firstName = this.proxy('traits.firstName'); if (typeof firstName === 'string') return trim(firstName); var name = this.proxy('traits.name'); if (typeof name === 'string') return trim(name).split(' ')[0]; }; /** * Get the user's last name, optionally splitting it out of a single name if * that's all that was provided. * * @return {String or Undefined} */ Identify.prototype.lastName = function () { var lastName = this.proxy('traits.lastName'); if (typeof lastName === 'string') return trim(lastName); var name = this.proxy('traits.name'); if (typeof name !== 'string') return; var space = trim(name).indexOf(' '); if (space === -1) return; return trim(name.substr(space + 1)); }; /** * Get the user's unique id. * * @return {String or undefined} */ Identify.prototype.uid = function(){ return this.userId() || this.username() || this.email(); }; /** * Get description. * * @return {String} */ Identify.prototype.description = function(){ return this.proxy('traits.description') || this.proxy('traits.background'); }; /** * Setup sme basic "special" trait proxies. */ Identify.prototype.username = Facade.proxy('traits.username'); Identify.prototype.website = Facade.proxy('traits.website'); Identify.prototype.phone = Facade.proxy('traits.phone'); Identify.prototype.address = Facade.proxy('traits.address'); Identify.prototype.avatar = Facade.proxy('traits.avatar'); }); require.register("segmentio-facade/lib/is-enabled.js", function(exports, require, module){ /** * A few integrations are disabled by default. They must be explicitly * enabled by setting options[Provider] = true. */ var disabled = { Salesforce: true, Marketo: true }; /** * Check whether an integration should be enabled by default. * * @param {String} integration * @return {Boolean} */ module.exports = function (integration) { return ! disabled[integration]; }; }); require.register("segmentio-facade/lib/track.js", function(exports, require, module){ var component = require('require-component')(require); var clone = component('clone'); var Facade = component('./facade'); var Identify = component('./identify'); var inherit = component('inherit'); var isEmail = component('is-email'); var traverse = component('isodate-traverse'); /** * Expose `Track` facade. */ module.exports = Track; /** * Initialize a new `Track` facade with a `dictionary` of arguments. * * @param {object} dictionary * @property {String} event * @property {String} userId * @property {String} sessionId * @property {Object} properties * @property {Object} options */ function Track (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Track, Facade); /** * Return the facade's action. * * @return {String} */ Track.prototype.action = function () { return 'track'; }; /** * Setup some basic proxies. */ Track.prototype.userId = Facade.field('userId'); Track.prototype.sessionId = Facade.field('sessionId'); Track.prototype.event = Facade.field('event'); Track.prototype.value = Facade.proxy('properties.value'); /** * Misc */ Track.prototype.category = Facade.proxy('properties.category'); Track.prototype.country = Facade.proxy('properties.country'); Track.prototype.state = Facade.proxy('properties.state'); Track.prototype.city = Facade.proxy('properties.city'); Track.prototype.zip = Facade.proxy('properties.zip'); /** * Ecommerce */ Track.prototype.id = Facade.proxy('properties.id'); Track.prototype.sku = Facade.proxy('properties.sku'); Track.prototype.tax = Facade.proxy('properties.tax'); Track.prototype.name = Facade.proxy('properties.name'); Track.prototype.price = Facade.proxy('properties.price'); Track.prototype.total = Facade.proxy('properties.total'); Track.prototype.coupon = Facade.proxy('properties.coupon'); Track.prototype.orderId = Facade.proxy('properties.orderId'); Track.prototype.shipping = Facade.proxy('properties.shipping'); /** * Get subtotal. * * @return {Number} */ Track.prototype.subtotal = function(){ var subtotal = this.obj.properties.subtotal; var total = this.total(); var n; if (subtotal) return subtotal; if (!total) return 0; if (n = this.tax()) total -= n; if (n = this.shipping()) total -= n; return total; }; /** * Get products. * * @return {Array} */ Track.prototype.products = function(){ var props = this.obj.properties || {}; return props.products || []; }; /** * Get quantity. * * @return {Number} */ Track.prototype.quantity = function(){ var props = this.obj.properties || {}; return props.quantity || 1; }; /** * Get currency. * * @return {String} */ Track.prototype.currency = function(){ var props = this.obj.properties || {}; return props.currency || 'USD'; }; /** * BACKWARDS COMPATIBILITY: should probably re-examine where these come from. */ Track.prototype.referrer = Facade.proxy('properties.referrer'); Track.prototype.query = Facade.proxy('options.query'); /** * Get the call's properties. * * @param {Object} aliases * @return {Object} */ Track.prototype.properties = function (aliases) { var ret = this.field('properties') || {}; aliases = aliases || {}; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('properties.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return clone(traverse(ret)); }; /** * Get the call's "super properties" which are just traits that have been * passed in as if from an identify call. * * @return {Object} */ Track.prototype.traits = function () { return this.proxy('options.traits') || {}; }; /** * Get the call's username. * * @return {String or Undefined} */ Track.prototype.username = function () { return this.proxy('traits.username') || this.proxy('properties.username') || this.userId() || this.sessionId(); }; /** * Get the call's email, using an the user ID if it's a valid email. * * @return {String or Undefined} */ Track.prototype.email = function () { var email = this.proxy('traits.email'); if (email) return email; var userId = this.userId(); if (isEmail(userId)) return userId; }; /** * Get the call's revenue, parsing it from a string with an optional leading * dollar sign. * * @return {String or Undefined} */ Track.prototype.revenue = function () { var revenue = this.proxy('properties.revenue'); if (!revenue) return; if (typeof revenue === 'number') return revenue; if (typeof revenue !== 'string') return; revenue = revenue.replace(/\$/g, ''); revenue = parseFloat(revenue); if (!isNaN(revenue)) return revenue; }; /** * Get cents. * * @return {Number} */ Track.prototype.cents = function(){ var revenue = this.revenue(); return 'number' != typeof revenue ? this.value() || 0 : revenue * 100; }; /** * A utility to turn the pieces of a track call into an identify. Used for * integrations with super properties or rate limits. * * TODO: remove me. * * @return {Facade} */ Track.prototype.identify = function () { var json = this.json(); json.traits = this.traits(); return new Identify(json); }; }); require.register("segmentio-is-email/index.js", function(exports, require, module){ /** * Expose `isEmail`. */ module.exports = isEmail; /** * Email address matcher. */ var matcher = /.+\@.+\..+/; /** * Loosely validate an email address. * * @param {String} string * @return {Boolean} */ function isEmail (string) { return matcher.test(string); } }); require.register("segmentio-is-meta/index.js", function(exports, require, module){ module.exports = function isMeta (e) { if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return true; // Logic that handles checks for the middle mouse button, based // on [jQuery](https://github.com/jquery/jquery/blob/master/src/event.js#L466). var which = e.which, button = e.button; if (!which && button !== undefined) { return (!button & 1) && (!button & 2) && (button & 4); } else if (which === 2) { return true; } return false; }; }); require.register("segmentio-isodate/index.js", function(exports, require, module){ /** * Matcher, slightly modified from: * * https://github.com/csnover/js-iso8601/blob/lax/iso8601.js */ var matcher = /^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/; /** * Convert an ISO date string to a date. Fallback to native `Date.parse`. * * https://github.com/csnover/js-iso8601/blob/lax/iso8601.js * * @param {String} iso * @return {Date} */ exports.parse = function (iso) { var numericKeys = [1, 5, 6, 7, 8, 11, 12]; var arr = matcher.exec(iso); var offset = 0; // fallback to native parsing if (!arr) return new Date(iso); // remove undefined values for (var i = 0, val; val = numericKeys[i]; i++) { arr[val] = parseInt(arr[val], 10) || 0; } // allow undefined days and months arr[2] = parseInt(arr[2], 10) || 1; arr[3] = parseInt(arr[3], 10) || 1; // month is 0-11 arr[2]--; // allow abitrary sub-second precision if (arr[8]) arr[8] = (arr[8] + '00').substring(0, 3); // apply timezone if one exists if (arr[4] == ' ') { offset = new Date().getTimezoneOffset(); } else if (arr[9] !== 'Z' && arr[10]) { offset = arr[11] * 60 + arr[12]; if ('+' == arr[10]) offset = 0 - offset; } var millis = Date.UTC(arr[1], arr[2], arr[3], arr[5], arr[6] + offset, arr[7], arr[8]); return new Date(millis); }; /** * Checks whether a `string` is an ISO date string. `strict` mode requires that * the date string at least have a year, month and date. * * @param {String} string * @param {Boolean} strict * @return {Boolean} */ exports.is = function (string, strict) { if (strict && false === /^\d{4}-\d{2}-\d{2}/.test(string)) return false; return matcher.test(string); }; }); require.register("segmentio-isodate-traverse/index.js", function(exports, require, module){ var is = require('is'); var isodate = require('isodate'); var each; try { each = require('each'); } catch (err) { each = require('each-component'); } /** * Expose `traverse`. */ module.exports = traverse; /** * Traverse an object or array, and return a clone with all ISO strings parsed * into Date objects. * * @param {Object} obj * @return {Object} */ function traverse (input, strict) { if (strict === undefined) strict = true; if (is.object(input)) { return object(input, strict); } else if (is.array(input)) { return array(input, strict); } } /** * Object traverser. * * @param {Object} obj * @param {Boolean} strict * @return {Object} */ function object (obj, strict) { each(obj, function (key, val) { if (isodate.is(val, strict)) { obj[key] = isodate.parse(val); } else if (is.object(val) || is.array(val)) { traverse(val, strict); } }); return obj; } /** * Array traverser. * * @param {Array} arr * @param {Boolean} strict * @return {Array} */ function array (arr, strict) { each(arr, function (val, x) { if (is.object(val)) { traverse(val, strict); } else if (isodate.is(val, strict)) { arr[x] = isodate.parse(val); } }); return arr; } }); require.register("component-json-fallback/index.js", function(exports, require, module){ /* json2.js 2014-02-04 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (typeof JSON !== 'object') { JSON = {}; } (function () { 'use strict'; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function () { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function () { return this.valueOf(); }; } var cx, escapable, gap, indent, meta, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }; JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); module.exports = JSON; }); require.register("segmentio-json/index.js", function(exports, require, module){ module.exports = 'undefined' == typeof JSON ? require('json-fallback') : JSON; }); require.register("segmentio-new-date/lib/index.js", function(exports, require, module){ var is = require('is'); var isodate = require('isodate'); var milliseconds = require('./milliseconds'); var seconds = require('./seconds'); /** * Returns a new Javascript Date object, allowing a variety of extra input types * over the native Date constructor. * * @param {Date|String|Number} val */ module.exports = function newDate (val) { if (is.date(val)) return val; if (is.number(val)) return new Date(toMs(val)); // date strings if (isodate.is(val)) return isodate.parse(val); if (milliseconds.is(val)) return milliseconds.parse(val); if (seconds.is(val)) return seconds.parse(val); // fallback to Date.parse return new Date(val); }; /** * If the number passed val is seconds from the epoch, turn it into milliseconds. * Milliseconds would be greater than 31557600000 (December 31, 1970). * * @param {Number} num */ function toMs (num) { if (num < 31557600000) return num * 1000; return num; } }); require.register("segmentio-new-date/lib/milliseconds.js", function(exports, require, module){ /** * Matcher. */ var matcher = /\d{13}/; /** * Check whether a string is a millisecond date string. * * @param {String} string * @return {Boolean} */ exports.is = function (string) { return matcher.test(string); }; /** * Convert a millisecond string to a date. * * @param {String} millis * @return {Date} */ exports.parse = function (millis) { millis = parseInt(millis, 10); return new Date(millis); }; }); require.register("segmentio-new-date/lib/seconds.js", function(exports, require, module){ /** * Matcher. */ var matcher = /\d{10}/; /** * Check whether a string is a second date string. * * @param {String} string * @return {Boolean} */ exports.is = function (string) { return matcher.test(string); }; /** * Convert a second string to a date. * * @param {String} seconds * @return {Date} */ exports.parse = function (seconds) { var millis = parseInt(seconds, 10) * 1000; return new Date(millis); }; }); require.register("segmentio-store.js/store.js", function(exports, require, module){ ;(function(win){ var store = {}, doc = win.document, localStorageName = 'localStorage', namespace = '__storejs__', storage store.disabled = false store.set = function(key, value) {} store.get = function(key) {} store.remove = function(key) {} store.clear = function() {} store.transact = function(key, defaultVal, transactionFn) { var val = store.get(key) if (transactionFn == null) { transactionFn = defaultVal defaultVal = null } if (typeof val == 'undefined') { val = defaultVal || {} } transactionFn(val) store.set(key, val) } store.getAll = function() {} store.serialize = function(value) { return JSON.stringify(value) } store.deserialize = function(value) { if (typeof value != 'string') { return undefined } try { return JSON.parse(value) } catch(e) { return value || undefined } } // Functions to encapsulate questionable FireFox 3.6.13 behavior // when about.config::dom.storage.enabled === false // See https://github.com/marcuswestin/store.js/issues#issue/13 function isLocalStorageNameSupported() { try { return (localStorageName in win && win[localStorageName]) } catch(err) { return false } } if (isLocalStorageNameSupported()) { storage = win[localStorageName] store.set = function(key, val) { if (val === undefined) { return store.remove(key) } storage.setItem(key, store.serialize(val)) return val } store.get = function(key) { return store.deserialize(storage.getItem(key)) } store.remove = function(key) { storage.removeItem(key) } store.clear = function() { storage.clear() } store.getAll = function() { var ret = {} for (var i=0; i<storage.length; ++i) { var key = storage.key(i) ret[key] = store.get(key) } return ret } } else if (doc.documentElement.addBehavior) { var storageOwner, storageContainer // Since #userData storage applies only to specific paths, we need to // somehow link our data to a specific path. We choose /favicon.ico // as a pretty safe option, since all browsers already make a request to // this URL anyway and being a 404 will not hurt us here. We wrap an // iframe pointing to the favicon in an ActiveXObject(htmlfile) object // (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx) // since the iframe access rules appear to allow direct access and // manipulation of the document element, even for a 404 page. This // document can be used instead of the current document (which would // have been limited to the current path) to perform #userData storage. try { storageContainer = new ActiveXObject('htmlfile') storageContainer.open() storageContainer.write('<s' + 'cript>document.w=window</s' + 'cript><iframe src="/favicon.ico"></iframe>') storageContainer.close() storageOwner = storageContainer.w.frames[0].document storage = storageOwner.createElement('div') } catch(e) { // somehow ActiveXObject instantiation failed (perhaps some special // security settings or otherwse), fall back to per-path storage storage = doc.createElement('div') storageOwner = doc.body } function withIEStorage(storeFunction) { return function() { var args = Array.prototype.slice.call(arguments, 0) args.unshift(storage) // See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx // and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx storageOwner.appendChild(storage) storage.addBehavior('#default#userData') storage.load(localStorageName) var result = storeFunction.apply(store, args) storageOwner.removeChild(storage) return result } } // In IE7, keys may not contain special chars. See all of https://github.com/marcuswestin/store.js/issues/40 var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g") function ieKeyFix(key) { return key.replace(forbiddenCharsRegex, '___') } store.set = withIEStorage(function(storage, key, val) { key = ieKeyFix(key) if (val === undefined) { return store.remove(key) } storage.setAttribute(key, store.serialize(val)) storage.save(localStorageName) return val }) store.get = withIEStorage(function(storage, key) { key = ieKeyFix(key) return store.deserialize(storage.getAttribute(key)) }) store.remove = withIEStorage(function(storage, key) { key = ieKeyFix(key) storage.removeAttribute(key) storage.save(localStorageName) }) store.clear = withIEStorage(function(storage) { var attributes = storage.XMLDocument.documentElement.attributes storage.load(localStorageName) for (var i=0, attr; attr=attributes[i]; i++) { storage.removeAttribute(attr.name) } storage.save(localStorageName) }) store.getAll = withIEStorage(function(storage) { var attributes = storage.XMLDocument.documentElement.attributes var ret = {} for (var i=0, attr; attr=attributes[i]; ++i) { var key = ieKeyFix(attr.name) ret[attr.name] = store.deserialize(storage.getAttribute(key)) } return ret }) } try { store.set(namespace, namespace) if (store.get(namespace) != namespace) { store.disabled = true } store.remove(namespace) } catch(e) { store.disabled = true } store.enabled = !store.disabled if (typeof module != 'undefined' && module.exports) { module.exports = store } else if (typeof define === 'function' && define.amd) { define(store) } else { win.store = store } })(this.window || global); }); require.register("segmentio-top-domain/index.js", function(exports, require, module){ var url = require('url'); // Official Grammar: http://tools.ietf.org/html/rfc883#page-56 // Look for tlds with up to 2-6 characters. module.exports = function (urlStr) { var host = url.parse(urlStr).hostname , topLevel = host.match(/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i); return topLevel ? topLevel[0] : host; }; }); require.register("visionmedia-debug/index.js", function(exports, require, module){ if ('undefined' == typeof window) { module.exports = require('./lib/debug'); } else { module.exports = require('./debug'); } }); require.register("visionmedia-debug/debug.js", function(exports, require, module){ /** * Expose `debug()` as the module. */ module.exports = debug; /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { if (!debug.enabled(name)) return function(){}; return function(fmt){ fmt = coerce(fmt); var curr = new Date; var ms = curr - (debug[name] || curr); debug[name] = curr; fmt = name + ' ' + fmt + ' +' + debug.humanize(ms); // This hackery is required for IE8 // where `console.log` doesn't have 'apply' window.console && console.log && Function.prototype.apply.call(console.log, console, arguments); } } /** * The currently active debug mode names. */ debug.names = []; debug.skips = []; /** * Enables a debug mode by name. This can include modes * separated by a colon and wildcards. * * @param {String} name * @api public */ debug.enable = function(name) { try { localStorage.debug = name; } catch(e){} var split = (name || '').split(/[\s,]+/) , len = split.length; for (var i = 0; i < len; i++) { name = split[i].replace('*', '.*?'); if (name[0] === '-') { debug.skips.push(new RegExp('^' + name.substr(1) + '$')); } else { debug.names.push(new RegExp('^' + name + '$')); } } }; /** * Disable debug output. * * @api public */ debug.disable = function(){ debug.enable(''); }; /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ debug.humanize = function(ms) { var sec = 1000 , min = 60 * 1000 , hour = 60 * min; if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; if (ms >= min) return (ms / min).toFixed(1) + 'm'; if (ms >= sec) return (ms / sec | 0) + 's'; return ms + 'ms'; }; /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ debug.enabled = function(name) { for (var i = 0, len = debug.skips.length; i < len; i++) { if (debug.skips[i].test(name)) { return false; } } for (var i = 0, len = debug.names.length; i < len; i++) { if (debug.names[i].test(name)) { return true; } } return false; }; /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } // persist try { if (window.localStorage) debug.enable(localStorage.debug); } catch(e){} }); require.register("yields-prevent/index.js", function(exports, require, module){ /** * prevent default on the given `e`. * * examples: * * anchor.onclick = prevent; * anchor.onclick = function(e){ * if (something) return prevent(e); * }; * * @param {Event} e */ module.exports = function(e){ e = e || window.event return e.preventDefault ? e.preventDefault() : e.returnValue = false; }; }); require.register("analytics/lib/index.js", function(exports, require, module){ /** * Analytics.js * * (C) 2013 Segment.io Inc. */ var Analytics = require('./analytics'); var createIntegration = require('integration'); var each = require('each'); var Integrations = require('integrations'); /** * Expose the `analytics` singleton. */ var analytics = module.exports = exports = new Analytics(); /** * Expose require */ analytics.require = require; /** * Expose `VERSION`. */ exports.VERSION = '1.3.6'; /** * Add integrations. */ each(Integrations, function (name, Integration) { analytics.use(Integration); }); }); require.register("analytics/lib/analytics.js", function(exports, require, module){ var after = require('after'); var bind = require('bind'); var callback = require('callback'); var canonical = require('canonical'); var clone = require('clone'); var cookie = require('./cookie'); var debug = require('debug'); var defaults = require('defaults'); var each = require('each'); var Emitter = require('emitter'); var group = require('./group'); var is = require('is'); var isEmail = require('is-email'); var isMeta = require('is-meta'); var newDate = require('new-date'); var on = require('event').bind; var prevent = require('prevent'); var querystring = require('querystring'); var size = require('object').length; var store = require('./store'); var url = require('url'); var user = require('./user'); var Facade = require('facade'); var Identify = Facade.Identify; var Group = Facade.Group; var Alias = Facade.Alias; var Track = Facade.Track; var Page = Facade.Page; /** * Expose `Analytics`. */ module.exports = Analytics; /** * Initialize a new `Analytics` instance. */ function Analytics () { this.Integrations = {}; this._integrations = {}; this._readied = false; this._timeout = 300; this._user = user; // BACKWARDS COMPATIBILITY bind.all(this); var self = this; this.on('initialize', function (settings, options) { if (options.initialPageview) self.page(); }); this.on('initialize', function () { self._parseQuery(); }); } /** * Event Emitter. */ Emitter(Analytics.prototype); /** * Use a `plugin`. * * @param {Function} plugin * @return {Analytics} */ Analytics.prototype.use = function (plugin) { plugin(this); return this; }; /** * Define a new `Integration`. * * @param {Function} Integration * @return {Analytics} */ Analytics.prototype.addIntegration = function (Integration) { var name = Integration.prototype.name; if (!name) throw new TypeError('attempted to add an invalid integration'); this.Integrations[name] = Integration; return this; }; /** * Initialize with the given integration `settings` and `options`. Aliased to * `init` for convenience. * * @param {Object} settings * @param {Object} options (optional) * @return {Analytics} */ Analytics.prototype.init = Analytics.prototype.initialize = function (settings, options) { settings = settings || {}; options = options || {}; this._options(options); this._readied = false; this._integrations = {}; // load user now that options are set user.load(); group.load(); // clean unknown integrations from settings var self = this; each(settings, function (name) { var Integration = self.Integrations[name]; if (!Integration) delete settings[name]; }); // make ready callback var ready = after(size(settings), function () { self._readied = true; self.emit('ready'); }); // initialize integrations, passing ready each(settings, function (name, opts) { var Integration = self.Integrations[name]; if (options.initialPageview && opts.initialPageview === false) { Integration.prototype.page = after(2, Integration.prototype.page); } var integration = new Integration(clone(opts)); integration.once('ready', ready); integration.initialize(); self._integrations[name] = integration; }); // backwards compat with angular plugin. // TODO: remove this.initialized = true; this.emit('initialize', settings, options); return this; }; /** * Identify a user by optional `id` and `traits`. * * @param {String} id (optional) * @param {Object} traits (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.identify = function (id, traits, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(traits)) fn = traits, options = null, traits = null; if (is.object(id)) options = traits, traits = id, id = user.id(); // clone traits before we manipulate so we don't do anything uncouth, and take // from `user` so that we carryover anonymous traits user.identify(id, traits); id = user.id(); traits = user.traits(); this._invoke('identify', new Identify({ options: options, traits: traits, userId: id })); // emit this.emit('identify', id, traits, options); this._callback(fn); return this; }; /** * Return the current user. * * @return {Object} */ Analytics.prototype.user = function () { return user; }; /** * Identify a group by optional `id` and `traits`. Or, if no arguments are * supplied, return the current group. * * @param {String} id (optional) * @param {Object} traits (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics or Object} */ Analytics.prototype.group = function (id, traits, options, fn) { if (0 === arguments.length) return group; if (is.fn(options)) fn = options, options = null; if (is.fn(traits)) fn = traits, options = null, traits = null; if (is.object(id)) options = traits, traits = id, id = group.id(); // grab from group again to make sure we're taking from the source group.identify(id, traits); id = group.id(); traits = group.traits(); this._invoke('group', new Group({ options: options, traits: traits, groupId: id })); this.emit('group', id, traits, options); this._callback(fn); return this; }; /** * Track an `event` that a user has triggered with optional `properties`. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.track = function (event, properties, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(properties)) fn = properties, options = null, properties = null; this._invoke('track', new Track({ properties: properties, options: options, event: event })); this.emit('track', event, properties, options); this._callback(fn); return this; }; /** * Helper method to track an outbound link that would normally navigate away * from the page before the analytics calls were sent. * * BACKWARDS COMPATIBILITY: aliased to `trackClick`. * * @param {Element or Array} links * @param {String or Function} event * @param {Object or Function} properties (optional) * @return {Analytics} */ Analytics.prototype.trackClick = Analytics.prototype.trackLink = function (links, event, properties) { if (!links) return this; if (is.element(links)) links = [links]; // always arrays, handles jquery var self = this; each(links, function (el) { on(el, 'click', function (e) { var ev = is.fn(event) ? event(el) : event; var props = is.fn(properties) ? properties(el) : properties; self.track(ev, props); if (el.href && el.target !== '_blank' && !isMeta(e)) { prevent(e); self._callback(function () { window.location.href = el.href; }); } }); }); return this; }; /** * Helper method to track an outbound form that would normally navigate away * from the page before the analytics calls were sent. * * BACKWARDS COMPATIBILITY: aliased to `trackSubmit`. * * @param {Element or Array} forms * @param {String or Function} event * @param {Object or Function} properties (optional) * @return {Analytics} */ Analytics.prototype.trackSubmit = Analytics.prototype.trackForm = function (forms, event, properties) { if (!forms) return this; if (is.element(forms)) forms = [forms]; // always arrays, handles jquery var self = this; each(forms, function (el) { function handler (e) { prevent(e); var ev = is.fn(event) ? event(el) : event; var props = is.fn(properties) ? properties(el) : properties; self.track(ev, props); self._callback(function () { el.submit(); }); } // support the events happening through jQuery or Zepto instead of through // the normal DOM API, since `el.submit` doesn't bubble up events... var $ = window.jQuery || window.Zepto; if ($) { $(el).submit(handler); } else { on(el, 'submit', handler); } }); return this; }; /** * Trigger a pageview, labeling the current page with an optional `category`, * `name` and `properties`. * * @param {String} category (optional) * @param {String} name (optional) * @param {Object or String} properties (or path) (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.page = function (category, name, properties, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(properties)) fn = properties, options = properties = null; if (is.fn(name)) fn = name, options = properties = name = null; if (is.object(category)) options = name, properties = category, name = category = null; if (is.object(name)) options = properties, properties = name, name = null; if (is.string(category) && !is.string(name)) name = category, category = null; var defs = { path: canonicalPath(), referrer: document.referrer, title: document.title, url: canonicalUrl(), search: location.search }; if (name) defs.name = name; if (category) defs.category = category; properties = clone(properties) || {}; defaults(properties, defs); this._invoke('page', new Page({ properties: properties, category: category, options: options, name: name })); this.emit('page', category, name, properties, options); this._callback(fn); return this; }; /** * BACKWARDS COMPATIBILITY: convert an old `pageview` to a `page` call. * * @param {String} url (optional) * @param {Object} options (optional) * @return {Analytics} * @api private */ Analytics.prototype.pageview = function (url, options) { var properties = {}; if (url) properties.path = url; this.page(properties); return this; }; /** * Merge two previously unassociated user identities. * * @param {String} to * @param {String} from (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.alias = function (to, from, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(from)) fn = from, options = null, from = null; if (is.object(from)) options = from, from = null; this._invoke('alias', new Alias({ options: options, from: from, to: to })); this.emit('alias', to, from, options); this._callback(fn); return this; }; /** * Register a `fn` to be fired when all the analytics services are ready. * * @param {Function} fn * @return {Analytics} */ Analytics.prototype.ready = function (fn) { if (!is.fn(fn)) return this; this._readied ? callback.async(fn) : this.once('ready', fn); return this; }; /** * Set the `timeout` (in milliseconds) used for callbacks. * * @param {Number} timeout */ Analytics.prototype.timeout = function (timeout) { this._timeout = timeout; }; /** * Enable or disable debug. * * @param {String or Boolean} str */ Analytics.prototype.debug = function(str){ if (0 == arguments.length || str) { debug.enable('analytics:' + (str || '*')); } else { debug.disable(); } }; /** * Apply options. * * @param {Object} options * @return {Analytics} * @api private */ Analytics.prototype._options = function (options) { options = options || {}; cookie.options(options.cookie); store.options(options.localStorage); user.options(options.user); group.options(options.group); return this; }; /** * Callback a `fn` after our defined timeout period. * * @param {Function} fn * @return {Analytics} * @api private */ Analytics.prototype._callback = function (fn) { callback.async(fn, this._timeout); return this; }; /** * Call `method` with `facade` on all enabled integrations. * * @param {String} method * @param {Facade} facade * @return {Analytics} * @api private */ Analytics.prototype._invoke = function (method, facade) { var options = facade.options(); each(this._integrations, function (name, integration) { if (!facade.enabled(name)) return; integration.invoke.call(integration, method, facade); }); return this; }; /** * Push `args`. * * @param {Array} args * @api private */ Analytics.prototype.push = function(args){ var method = args.shift(); if (!this[method]) return; this[method].apply(this, args); }; /** * Parse the query string for callable methods. * * @return {Analytics} * @api private */ Analytics.prototype._parseQuery = function () { // Identify and track any `ajs_uid` and `ajs_event` parameters in the URL. var q = querystring.parse(window.location.search); if (q.ajs_uid) this.identify(q.ajs_uid); if (q.ajs_event) this.track(q.ajs_event); return this; }; /** * Return the canonical path for the page. * * @return {String} */ function canonicalPath () { var canon = canonical(); if (!canon) return window.location.pathname; var parsed = url.parse(canon); return parsed.pathname; } /** * Return the canonical URL for the page, without the hash. * * @return {String} */ function canonicalUrl () { var canon = canonical(); if (canon) return canon; var url = window.location.href; var i = url.indexOf('#'); return -1 == i ? url : url.slice(0, i); } }); require.register("analytics/lib/cookie.js", function(exports, require, module){ var bind = require('bind'); var cookie = require('cookie'); var clone = require('clone'); var defaults = require('defaults'); var json = require('json'); var topDomain = require('top-domain'); /** * Initialize a new `Cookie` with `options`. * * @param {Object} options */ function Cookie (options) { this.options(options); } /** * Get or set the cookie options. * * @param {Object} options * @field {Number} maxage (1 year) * @field {String} domain * @field {String} path * @field {Boolean} secure */ Cookie.prototype.options = function (options) { if (arguments.length === 0) return this._options; options = options || {}; var domain = '.' + topDomain(window.location.href); // localhost cookies are special: http://curl.haxx.se/rfc/cookie_spec.html if (domain === '.localhost') domain = ''; defaults(options, { maxage: 31536000000, // default to a year path: '/', domain: domain }); this._options = options; }; /** * Set a `key` and `value` in our cookie. * * @param {String} key * @param {Object} value * @return {Boolean} saved */ Cookie.prototype.set = function (key, value) { try { value = json.stringify(value); cookie(key, value, clone(this._options)); return true; } catch (e) { return false; } }; /** * Get a value from our cookie by `key`. * * @param {String} key * @return {Object} value */ Cookie.prototype.get = function (key) { try { var value = cookie(key); value = value ? json.parse(value) : null; return value; } catch (e) { return null; } }; /** * Remove a value from our cookie by `key`. * * @param {String} key * @return {Boolean} removed */ Cookie.prototype.remove = function (key) { try { cookie(key, null, clone(this._options)); return true; } catch (e) { return false; } }; /** * Expose the cookie singleton. */ module.exports = bind.all(new Cookie()); /** * Expose the `Cookie` constructor. */ module.exports.Cookie = Cookie; }); require.register("analytics/lib/entity.js", function(exports, require, module){ var traverse = require('isodate-traverse'); var defaults = require('defaults'); var cookie = require('./cookie'); var store = require('./store'); var extend = require('extend'); var clone = require('clone'); /** * Expose `Entity` */ module.exports = Entity; /** * Initialize new `Entity` with `options`. * * @param {Object} options */ function Entity(options){ this.options(options); } /** * Get or set storage `options`. * * @param {Object} options * @property {Object} cookie * @property {Object} localStorage * @property {Boolean} persist (default: `true`) */ Entity.prototype.options = function (options) { if (arguments.length === 0) return this._options; options || (options = {}); defaults(options, this.defaults || {}); this._options = options; }; /** * Get or set the entity's `id`. * * @param {String} id */ Entity.prototype.id = function (id) { switch (arguments.length) { case 0: return this._getId(); case 1: return this._setId(id); } }; /** * Get the entity's id. * * @return {String} */ Entity.prototype._getId = function () { var ret = this._options.persist ? cookie.get(this._options.cookie.key) : this._id; return ret === undefined ? null : ret; }; /** * Set the entity's `id`. * * @param {String} id */ Entity.prototype._setId = function (id) { if (this._options.persist) { cookie.set(this._options.cookie.key, id); } else { this._id = id; } }; /** * Get or set the entity's `traits`. * * BACKWARDS COMPATIBILITY: aliased to `properties` * * @param {Object} traits */ Entity.prototype.properties = Entity.prototype.traits = function (traits) { switch (arguments.length) { case 0: return this._getTraits(); case 1: return this._setTraits(traits); } }; /** * Get the entity's traits. Always convert ISO date strings into real dates, * since they aren't parsed back from local storage. * * @return {Object} */ Entity.prototype._getTraits = function () { var ret = this._options.persist ? store.get(this._options.localStorage.key) : this._traits; return ret ? traverse(clone(ret)) : {}; }; /** * Set the entity's `traits`. * * @param {Object} traits */ Entity.prototype._setTraits = function (traits) { traits || (traits = {}); if (this._options.persist) { store.set(this._options.localStorage.key, traits); } else { this._traits = traits; } }; /** * Identify the entity with an `id` and `traits`. If we it's the same entity, * extend the existing `traits` instead of overwriting. * * @param {String} id * @param {Object} traits */ Entity.prototype.identify = function (id, traits) { traits || (traits = {}); var current = this.id(); if (current === null || current === id) traits = extend(this.traits(), traits); if (id) this.id(id); this.debug('identify %o, %o', id, traits); this.traits(traits); this.save(); }; /** * Save the entity to local storage and the cookie. * * @return {Boolean} */ Entity.prototype.save = function () { if (!this._options.persist) return false; cookie.set(this._options.cookie.key, this.id()); store.set(this._options.localStorage.key, this.traits()); return true; }; /** * Log the entity out, reseting `id` and `traits` to defaults. */ Entity.prototype.logout = function () { this.id(null); this.traits({}); cookie.remove(this._options.cookie.key); store.remove(this._options.localStorage.key); }; /** * Reset all entity state, logging out and returning options to defaults. */ Entity.prototype.reset = function () { this.logout(); this.options({}); }; /** * Load saved entity `id` or `traits` from storage. */ Entity.prototype.load = function () { this.id(cookie.get(this._options.cookie.key)); this.traits(store.get(this._options.localStorage.key)); }; }); require.register("analytics/lib/group.js", function(exports, require, module){ var debug = require('debug')('analytics:group'); var Entity = require('./entity'); var inherit = require('inherit'); var bind = require('bind'); /** * Group defaults */ Group.defaults = { persist: true, cookie: { key: 'ajs_group_id' }, localStorage: { key: 'ajs_group_properties' } }; /** * Initialize a new `Group` with `options`. * * @param {Object} options */ function Group (options) { this.defaults = Group.defaults; this.debug = debug; Entity.call(this, options); } /** * Inherit `Entity` */ inherit(Group, Entity); /** * Expose the group singleton. */ module.exports = bind.all(new Group()); /** * Expose the `Group` constructor. */ module.exports.Group = Group; }); require.register("analytics/lib/store.js", function(exports, require, module){ var bind = require('bind'); var defaults = require('defaults'); var store = require('store'); /** * Initialize a new `Store` with `options`. * * @param {Object} options */ function Store (options) { this.options(options); } /** * Set the `options` for the store. * * @param {Object} options * @field {Boolean} enabled (true) */ Store.prototype.options = function (options) { if (arguments.length === 0) return this._options; options = options || {}; defaults(options, { enabled : true }); this.enabled = options.enabled && store.enabled; this._options = options; }; /** * Set a `key` and `value` in local storage. * * @param {String} key * @param {Object} value */ Store.prototype.set = function (key, value) { if (!this.enabled) return false; return store.set(key, value); }; /** * Get a value from local storage by `key`. * * @param {String} key * @return {Object} */ Store.prototype.get = function (key) { if (!this.enabled) return null; return store.get(key); }; /** * Remove a value from local storage by `key`. * * @param {String} key */ Store.prototype.remove = function (key) { if (!this.enabled) return false; return store.remove(key); }; /** * Expose the store singleton. */ module.exports = bind.all(new Store()); /** * Expose the `Store` constructor. */ module.exports.Store = Store; }); require.register("analytics/lib/user.js", function(exports, require, module){ var debug = require('debug')('analytics:user'); var Entity = require('./entity'); var inherit = require('inherit'); var bind = require('bind'); var cookie = require('./cookie'); /** * User defaults */ User.defaults = { persist: true, cookie: { key: 'ajs_user_id', oldKey: 'ajs_user' }, localStorage: { key: 'ajs_user_traits' } }; /** * Initialize a new `User` with `options`. * * @param {Object} options */ function User (options) { this.defaults = User.defaults; this.debug = debug; Entity.call(this, options); } /** * Inherit `Entity` */ inherit(User, Entity); /** * Load saved user `id` or `traits` from storage. */ User.prototype.load = function () { if (this._loadOldCookie()) return; Entity.prototype.load.call(this); }; /** * BACKWARDS COMPATIBILITY: Load the old user from the cookie. * * @return {Boolean} * @api private */ User.prototype._loadOldCookie = function () { var user = cookie.get(this._options.cookie.oldKey); if (!user) return false; this.id(user.id); this.traits(user.traits); cookie.remove(this._options.cookie.oldKey); return true; }; /** * Expose the user singleton. */ module.exports = bind.all(new User()); /** * Expose the `User` constructor. */ module.exports.User = User; }); require.register("segmentio-analytics.js-integrations/lib/slugs.json", function(exports, require, module){ module.exports = [ "adroll", "adwords", "amplitude", "awesm", "awesomatic", "bing-ads", "bronto", "bugherd", "bugsnag", "chartbeat", "churnbee", "clicktale", "clicky", "comscore", "crazy-egg", "curebit", "customerio", "drip", "errorception", "evergage", "facebook-ads", "foxmetrics", "gauges", "get-satisfaction", "google-analytics", "google-tag-manager", "gosquared", "heap", "hittail", "hubspot", "improvely", "inspectlet", "intercom", "keen-io", "kissmetrics", "klaviyo", "leadlander", "livechat", "lucky-orange", "lytics", "mixpanel", "mojn", "mouseflow", "mousestats", "olark", "optimizely", "perfect-audience", "pingdom", "preact", "qualaroo", "quantcast", "rollbar", "saasquatch", "sentry", "snapengage", "spinnakr", "tapstream", "trakio", "twitter-ads", "usercycle", "userfox", "uservoice", "vero", "visual-website-optimizer", "webengage", "woopra", "yandex-metrica" ] }); require.alias("avetisk-defaults/index.js", "analytics/deps/defaults/index.js"); require.alias("avetisk-defaults/index.js", "defaults/index.js"); require.alias("component-clone/index.js", "analytics/deps/clone/index.js"); require.alias("component-clone/index.js", "clone/index.js"); require.alias("component-type/index.js", "component-clone/deps/type/index.js"); require.alias("component-cookie/index.js", "analytics/deps/cookie/index.js"); require.alias("component-cookie/index.js", "cookie/index.js"); require.alias("component-each/index.js", "analytics/deps/each/index.js"); require.alias("component-each/index.js", "each/index.js"); require.alias("component-type/index.js", "component-each/deps/type/index.js"); require.alias("component-emitter/index.js", "analytics/deps/emitter/index.js"); require.alias("component-emitter/index.js", "emitter/index.js"); require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js"); require.alias("component-event/index.js", "analytics/deps/event/index.js"); require.alias("component-event/index.js", "event/index.js"); require.alias("component-inherit/index.js", "analytics/deps/inherit/index.js"); require.alias("component-inherit/index.js", "inherit/index.js"); require.alias("component-object/index.js", "analytics/deps/object/index.js"); require.alias("component-object/index.js", "object/index.js"); require.alias("component-querystring/index.js", "analytics/deps/querystring/index.js"); require.alias("component-querystring/index.js", "querystring/index.js"); require.alias("component-trim/index.js", "component-querystring/deps/trim/index.js"); require.alias("component-url/index.js", "analytics/deps/url/index.js"); require.alias("component-url/index.js", "url/index.js"); require.alias("ianstormtaylor-bind/index.js", "analytics/deps/bind/index.js"); require.alias("ianstormtaylor-bind/index.js", "bind/index.js"); require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js"); require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js"); require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js"); require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js"); require.alias("ianstormtaylor-callback/index.js", "analytics/deps/callback/index.js"); require.alias("ianstormtaylor-callback/index.js", "callback/index.js"); require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js"); require.alias("ianstormtaylor-is/index.js", "analytics/deps/is/index.js"); require.alias("ianstormtaylor-is/index.js", "is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-after/index.js", "analytics/deps/after/index.js"); require.alias("segmentio-after/index.js", "after/index.js"); require.alias("segmentio-analytics.js-integration/lib/index.js", "analytics/deps/integration/lib/index.js"); require.alias("segmentio-analytics.js-integration/lib/protos.js", "analytics/deps/integration/lib/protos.js"); require.alias("segmentio-analytics.js-integration/lib/events.js", "analytics/deps/integration/lib/events.js"); require.alias("segmentio-analytics.js-integration/lib/statics.js", "analytics/deps/integration/lib/statics.js"); require.alias("segmentio-analytics.js-integration/lib/index.js", "analytics/deps/integration/index.js"); require.alias("segmentio-analytics.js-integration/lib/index.js", "integration/index.js"); require.alias("avetisk-defaults/index.js", "segmentio-analytics.js-integration/deps/defaults/index.js"); require.alias("component-clone/index.js", "segmentio-analytics.js-integration/deps/clone/index.js"); require.alias("component-type/index.js", "component-clone/deps/type/index.js"); require.alias("component-emitter/index.js", "segmentio-analytics.js-integration/deps/emitter/index.js"); require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js"); require.alias("ianstormtaylor-bind/index.js", "segmentio-analytics.js-integration/deps/bind/index.js"); require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js"); require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js"); require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js"); require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js"); require.alias("ianstormtaylor-callback/index.js", "segmentio-analytics.js-integration/deps/callback/index.js"); require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js"); require.alias("segmentio-after/index.js", "segmentio-analytics.js-integration/deps/after/index.js"); require.alias("timoxley-next-tick/index.js", "segmentio-analytics.js-integration/deps/next-tick/index.js"); require.alias("yields-slug/index.js", "segmentio-analytics.js-integration/deps/slug/index.js"); require.alias("visionmedia-debug/index.js", "segmentio-analytics.js-integration/deps/debug/index.js"); require.alias("visionmedia-debug/debug.js", "segmentio-analytics.js-integration/deps/debug/debug.js"); require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integration/index.js"); require.alias("segmentio-analytics.js-integrations/index.js", "analytics/deps/integrations/index.js"); require.alias("segmentio-analytics.js-integrations/lib/adroll.js", "analytics/deps/integrations/lib/adroll.js"); require.alias("segmentio-analytics.js-integrations/lib/adwords.js", "analytics/deps/integrations/lib/adwords.js"); require.alias("segmentio-analytics.js-integrations/lib/amplitude.js", "analytics/deps/integrations/lib/amplitude.js"); require.alias("segmentio-analytics.js-integrations/lib/awesm.js", "analytics/deps/integrations/lib/awesm.js"); require.alias("segmentio-analytics.js-integrations/lib/awesomatic.js", "analytics/deps/integrations/lib/awesomatic.js"); require.alias("segmentio-analytics.js-integrations/lib/bing-ads.js", "analytics/deps/integrations/lib/bing-ads.js"); require.alias("segmentio-analytics.js-integrations/lib/bronto.js", "analytics/deps/integrations/lib/bronto.js"); require.alias("segmentio-analytics.js-integrations/lib/bugherd.js", "analytics/deps/integrations/lib/bugherd.js"); require.alias("segmentio-analytics.js-integrations/lib/bugsnag.js", "analytics/deps/integrations/lib/bugsnag.js"); require.alias("segmentio-analytics.js-integrations/lib/chartbeat.js", "analytics/deps/integrations/lib/chartbeat.js"); require.alias("segmentio-analytics.js-integrations/lib/churnbee.js", "analytics/deps/integrations/lib/churnbee.js"); require.alias("segmentio-analytics.js-integrations/lib/clicktale.js", "analytics/deps/integrations/lib/clicktale.js"); require.alias("segmentio-analytics.js-integrations/lib/clicky.js", "analytics/deps/integrations/lib/clicky.js"); require.alias("segmentio-analytics.js-integrations/lib/comscore.js", "analytics/deps/integrations/lib/comscore.js"); require.alias("segmentio-analytics.js-integrations/lib/crazy-egg.js", "analytics/deps/integrations/lib/crazy-egg.js"); require.alias("segmentio-analytics.js-integrations/lib/curebit.js", "analytics/deps/integrations/lib/curebit.js"); require.alias("segmentio-analytics.js-integrations/lib/customerio.js", "analytics/deps/integrations/lib/customerio.js"); require.alias("segmentio-analytics.js-integrations/lib/drip.js", "analytics/deps/integrations/lib/drip.js"); require.alias("segmentio-analytics.js-integrations/lib/errorception.js", "analytics/deps/integrations/lib/errorception.js"); require.alias("segmentio-analytics.js-integrations/lib/evergage.js", "analytics/deps/integrations/lib/evergage.js"); require.alias("segmentio-analytics.js-integrations/lib/facebook-ads.js", "analytics/deps/integrations/lib/facebook-ads.js"); require.alias("segmentio-analytics.js-integrations/lib/foxmetrics.js", "analytics/deps/integrations/lib/foxmetrics.js"); require.alias("segmentio-analytics.js-integrations/lib/gauges.js", "analytics/deps/integrations/lib/gauges.js"); require.alias("segmentio-analytics.js-integrations/lib/get-satisfaction.js", "analytics/deps/integrations/lib/get-satisfaction.js"); require.alias("segmentio-analytics.js-integrations/lib/google-analytics.js", "analytics/deps/integrations/lib/google-analytics.js"); require.alias("segmentio-analytics.js-integrations/lib/google-tag-manager.js", "analytics/deps/integrations/lib/google-tag-manager.js"); require.alias("segmentio-analytics.js-integrations/lib/gosquared.js", "analytics/deps/integrations/lib/gosquared.js"); require.alias("segmentio-analytics.js-integrations/lib/heap.js", "analytics/deps/integrations/lib/heap.js"); require.alias("segmentio-analytics.js-integrations/lib/hittail.js", "analytics/deps/integrations/lib/hittail.js"); require.alias("segmentio-analytics.js-integrations/lib/hubspot.js", "analytics/deps/integrations/lib/hubspot.js"); require.alias("segmentio-analytics.js-integrations/lib/improvely.js", "analytics/deps/integrations/lib/improvely.js"); require.alias("segmentio-analytics.js-integrations/lib/inspectlet.js", "analytics/deps/integrations/lib/inspectlet.js"); require.alias("segmentio-analytics.js-integrations/lib/intercom.js", "analytics/deps/integrations/lib/intercom.js"); require.alias("segmentio-analytics.js-integrations/lib/keen-io.js", "analytics/deps/integrations/lib/keen-io.js"); require.alias("segmentio-analytics.js-integrations/lib/kissmetrics.js", "analytics/deps/integrations/lib/kissmetrics.js"); require.alias("segmentio-analytics.js-integrations/lib/klaviyo.js", "analytics/deps/integrations/lib/klaviyo.js"); require.alias("segmentio-analytics.js-integrations/lib/leadlander.js", "analytics/deps/integrations/lib/leadlander.js"); require.alias("segmentio-analytics.js-integrations/lib/livechat.js", "analytics/deps/integrations/lib/livechat.js"); require.alias("segmentio-analytics.js-integrations/lib/lucky-orange.js", "analytics/deps/integrations/lib/lucky-orange.js"); require.alias("segmentio-analytics.js-integrations/lib/lytics.js", "analytics/deps/integrations/lib/lytics.js"); require.alias("segmentio-analytics.js-integrations/lib/mixpanel.js", "analytics/deps/integrations/lib/mixpanel.js"); require.alias("segmentio-analytics.js-integrations/lib/mojn.js", "analytics/deps/integrations/lib/mojn.js"); require.alias("segmentio-analytics.js-integrations/lib/mouseflow.js", "analytics/deps/integrations/lib/mouseflow.js"); require.alias("segmentio-analytics.js-integrations/lib/mousestats.js", "analytics/deps/integrations/lib/mousestats.js"); require.alias("segmentio-analytics.js-integrations/lib/olark.js", "analytics/deps/integrations/lib/olark.js"); require.alias("segmentio-analytics.js-integrations/lib/optimizely.js", "analytics/deps/integrations/lib/optimizely.js"); require.alias("segmentio-analytics.js-integrations/lib/perfect-audience.js", "analytics/deps/integrations/lib/perfect-audience.js"); require.alias("segmentio-analytics.js-integrations/lib/pingdom.js", "analytics/deps/integrations/lib/pingdom.js"); require.alias("segmentio-analytics.js-integrations/lib/preact.js", "analytics/deps/integrations/lib/preact.js"); require.alias("segmentio-analytics.js-integrations/lib/qualaroo.js", "analytics/deps/integrations/lib/qualaroo.js"); require.alias("segmentio-analytics.js-integrations/lib/quantcast.js", "analytics/deps/integrations/lib/quantcast.js"); require.alias("segmentio-analytics.js-integrations/lib/rollbar.js", "analytics/deps/integrations/lib/rollbar.js"); require.alias("segmentio-analytics.js-integrations/lib/saasquatch.js", "analytics/deps/integrations/lib/saasquatch.js"); require.alias("segmentio-analytics.js-integrations/lib/sentry.js", "analytics/deps/integrations/lib/sentry.js"); require.alias("segmentio-analytics.js-integrations/lib/snapengage.js", "analytics/deps/integrations/lib/snapengage.js"); require.alias("segmentio-analytics.js-integrations/lib/spinnakr.js", "analytics/deps/integrations/lib/spinnakr.js"); require.alias("segmentio-analytics.js-integrations/lib/tapstream.js", "analytics/deps/integrations/lib/tapstream.js"); require.alias("segmentio-analytics.js-integrations/lib/trakio.js", "analytics/deps/integrations/lib/trakio.js"); require.alias("segmentio-analytics.js-integrations/lib/twitter-ads.js", "analytics/deps/integrations/lib/twitter-ads.js"); require.alias("segmentio-analytics.js-integrations/lib/usercycle.js", "analytics/deps/integrations/lib/usercycle.js"); require.alias("segmentio-analytics.js-integrations/lib/userfox.js", "analytics/deps/integrations/lib/userfox.js"); require.alias("segmentio-analytics.js-integrations/lib/uservoice.js", "analytics/deps/integrations/lib/uservoice.js"); require.alias("segmentio-analytics.js-integrations/lib/vero.js", "analytics/deps/integrations/lib/vero.js"); require.alias("segmentio-analytics.js-integrations/lib/visual-website-optimizer.js", "analytics/deps/integrations/lib/visual-website-optimizer.js"); require.alias("segmentio-analytics.js-integrations/lib/webengage.js", "analytics/deps/integrations/lib/webengage.js"); require.alias("segmentio-analytics.js-integrations/lib/woopra.js", "analytics/deps/integrations/lib/woopra.js"); require.alias("segmentio-analytics.js-integrations/lib/yandex-metrica.js", "analytics/deps/integrations/lib/yandex-metrica.js"); require.alias("segmentio-analytics.js-integrations/index.js", "integrations/index.js"); require.alias("component-clone/index.js", "segmentio-analytics.js-integrations/deps/clone/index.js"); require.alias("component-type/index.js", "component-clone/deps/type/index.js"); require.alias("component-domify/index.js", "segmentio-analytics.js-integrations/deps/domify/index.js"); require.alias("component-each/index.js", "segmentio-analytics.js-integrations/deps/each/index.js"); require.alias("component-type/index.js", "component-each/deps/type/index.js"); require.alias("component-once/index.js", "segmentio-analytics.js-integrations/deps/once/index.js"); require.alias("component-type/index.js", "segmentio-analytics.js-integrations/deps/type/index.js"); require.alias("component-url/index.js", "segmentio-analytics.js-integrations/deps/url/index.js"); require.alias("ianstormtaylor-callback/index.js", "segmentio-analytics.js-integrations/deps/callback/index.js"); require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js"); require.alias("ianstormtaylor-bind/index.js", "segmentio-analytics.js-integrations/deps/bind/index.js"); require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js"); require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js"); require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js"); require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js"); require.alias("ianstormtaylor-is/index.js", "segmentio-analytics.js-integrations/deps/is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-alias/index.js", "segmentio-analytics.js-integrations/deps/alias/index.js"); require.alias("component-clone/index.js", "segmentio-alias/deps/clone/index.js"); require.alias("component-type/index.js", "component-clone/deps/type/index.js"); require.alias("component-type/index.js", "segmentio-alias/deps/type/index.js"); require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integrations/deps/integration/lib/index.js"); require.alias("segmentio-analytics.js-integration/lib/protos.js", "segmentio-analytics.js-integrations/deps/integration/lib/protos.js"); require.alias("segmentio-analytics.js-integration/lib/events.js", "segmentio-analytics.js-integrations/deps/integration/lib/events.js"); require.alias("segmentio-analytics.js-integration/lib/statics.js", "segmentio-analytics.js-integrations/deps/integration/lib/statics.js"); require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integrations/deps/integration/index.js"); require.alias("avetisk-defaults/index.js", "segmentio-analytics.js-integration/deps/defaults/index.js"); require.alias("component-clone/index.js", "segmentio-analytics.js-integration/deps/clone/index.js"); require.alias("component-type/index.js", "component-clone/deps/type/index.js"); require.alias("component-emitter/index.js", "segmentio-analytics.js-integration/deps/emitter/index.js"); require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js"); require.alias("ianstormtaylor-bind/index.js", "segmentio-analytics.js-integration/deps/bind/index.js"); require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js"); require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js"); require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js"); require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js"); require.alias("ianstormtaylor-callback/index.js", "segmentio-analytics.js-integration/deps/callback/index.js"); require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js"); require.alias("segmentio-after/index.js", "segmentio-analytics.js-integration/deps/after/index.js"); require.alias("timoxley-next-tick/index.js", "segmentio-analytics.js-integration/deps/next-tick/index.js"); require.alias("yields-slug/index.js", "segmentio-analytics.js-integration/deps/slug/index.js"); require.alias("visionmedia-debug/index.js", "segmentio-analytics.js-integration/deps/debug/index.js"); require.alias("visionmedia-debug/debug.js", "segmentio-analytics.js-integration/deps/debug/debug.js"); require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integration/index.js"); require.alias("segmentio-canonical/index.js", "segmentio-analytics.js-integrations/deps/canonical/index.js"); require.alias("segmentio-convert-dates/index.js", "segmentio-analytics.js-integrations/deps/convert-dates/index.js"); require.alias("component-clone/index.js", "segmentio-convert-dates/deps/clone/index.js"); require.alias("component-type/index.js", "component-clone/deps/type/index.js"); require.alias("ianstormtaylor-is/index.js", "segmentio-convert-dates/deps/is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-extend/index.js", "segmentio-analytics.js-integrations/deps/extend/index.js"); require.alias("segmentio-facade/lib/index.js", "segmentio-analytics.js-integrations/deps/facade/lib/index.js"); require.alias("segmentio-facade/lib/alias.js", "segmentio-analytics.js-integrations/deps/facade/lib/alias.js"); require.alias("segmentio-facade/lib/facade.js", "segmentio-analytics.js-integrations/deps/facade/lib/facade.js"); require.alias("segmentio-facade/lib/group.js", "segmentio-analytics.js-integrations/deps/facade/lib/group.js"); require.alias("segmentio-facade/lib/page.js", "segmentio-analytics.js-integrations/deps/facade/lib/page.js"); require.alias("segmentio-facade/lib/identify.js", "segmentio-analytics.js-integrations/deps/facade/lib/identify.js"); require.alias("segmentio-facade/lib/is-enabled.js", "segmentio-analytics.js-integrations/deps/facade/lib/is-enabled.js"); require.alias("segmentio-facade/lib/track.js", "segmentio-analytics.js-integrations/deps/facade/lib/track.js"); require.alias("segmentio-facade/lib/index.js", "segmentio-analytics.js-integrations/deps/facade/index.js"); require.alias("camshaft-require-component/index.js", "segmentio-facade/deps/require-component/index.js"); require.alias("segmentio-isodate-traverse/index.js", "segmentio-facade/deps/isodate-traverse/index.js"); require.alias("component-each/index.js", "segmentio-isodate-traverse/deps/each/index.js"); require.alias("component-type/index.js", "component-each/deps/type/index.js"); require.alias("ianstormtaylor-is/index.js", "segmentio-isodate-traverse/deps/is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-isodate/index.js", "segmentio-isodate-traverse/deps/isodate/index.js"); require.alias("component-clone/index.js", "segmentio-facade/deps/clone/index.js"); require.alias("component-type/index.js", "component-clone/deps/type/index.js"); require.alias("component-inherit/index.js", "segmentio-facade/deps/inherit/index.js"); require.alias("component-trim/index.js", "segmentio-facade/deps/trim/index.js"); require.alias("segmentio-is-email/index.js", "segmentio-facade/deps/is-email/index.js"); require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/lib/index.js"); require.alias("segmentio-new-date/lib/milliseconds.js", "segmentio-facade/deps/new-date/lib/milliseconds.js"); require.alias("segmentio-new-date/lib/seconds.js", "segmentio-facade/deps/new-date/lib/seconds.js"); require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/index.js"); require.alias("ianstormtaylor-is/index.js", "segmentio-new-date/deps/is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-isodate/index.js", "segmentio-new-date/deps/isodate/index.js"); require.alias("segmentio-new-date/lib/index.js", "segmentio-new-date/index.js"); require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js"); require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js"); require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/lib/index.js"); require.alias("ianstormtaylor-case/lib/cases.js", "segmentio-obj-case/deps/case/lib/cases.js"); require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/index.js"); require.alias("ianstormtaylor-to-camel-case/index.js", "ianstormtaylor-case/deps/to-camel-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-camel-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-case/deps/to-capital-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-constant-case/index.js", "ianstormtaylor-case/deps/to-constant-case/index.js"); require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-to-constant-case/deps/to-snake-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-dot-case/index.js", "ianstormtaylor-case/deps/to-dot-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-dot-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-pascal-case/index.js", "ianstormtaylor-case/deps/to-pascal-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-pascal-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-sentence-case/index.js", "ianstormtaylor-case/deps/to-sentence-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-sentence-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-slug-case/index.js", "ianstormtaylor-case/deps/to-slug-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-slug-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-case/deps/to-snake-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-title-case/index.js", "ianstormtaylor-case/deps/to-title-case/index.js"); require.alias("component-escape-regexp/index.js", "ianstormtaylor-to-title-case/deps/escape-regexp/index.js"); require.alias("ianstormtaylor-map/index.js", "ianstormtaylor-to-title-case/deps/map/index.js"); require.alias("component-each/index.js", "ianstormtaylor-map/deps/each/index.js"); require.alias("component-type/index.js", "component-each/deps/type/index.js"); require.alias("ianstormtaylor-title-case-minors/index.js", "ianstormtaylor-to-title-case/deps/title-case-minors/index.js"); require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-to-title-case/deps/to-capital-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-case/lib/index.js", "ianstormtaylor-case/index.js"); require.alias("segmentio-obj-case/index.js", "segmentio-obj-case/index.js"); require.alias("segmentio-facade/lib/index.js", "segmentio-facade/index.js"); require.alias("segmentio-global-queue/index.js", "segmentio-analytics.js-integrations/deps/global-queue/index.js"); require.alias("segmentio-is-email/index.js", "segmentio-analytics.js-integrations/deps/is-email/index.js"); require.alias("segmentio-load-date/index.js", "segmentio-analytics.js-integrations/deps/load-date/index.js"); require.alias("segmentio-load-script/index.js", "segmentio-analytics.js-integrations/deps/load-script/index.js"); require.alias("component-type/index.js", "segmentio-load-script/deps/type/index.js"); require.alias("segmentio-on-body/index.js", "segmentio-analytics.js-integrations/deps/on-body/index.js"); require.alias("component-each/index.js", "segmentio-on-body/deps/each/index.js"); require.alias("component-type/index.js", "component-each/deps/type/index.js"); require.alias("segmentio-on-error/index.js", "segmentio-analytics.js-integrations/deps/on-error/index.js"); require.alias("segmentio-to-iso-string/index.js", "segmentio-analytics.js-integrations/deps/to-iso-string/index.js"); require.alias("segmentio-to-unix-timestamp/index.js", "segmentio-analytics.js-integrations/deps/to-unix-timestamp/index.js"); require.alias("segmentio-use-https/index.js", "segmentio-analytics.js-integrations/deps/use-https/index.js"); require.alias("timoxley-next-tick/index.js", "segmentio-analytics.js-integrations/deps/next-tick/index.js"); require.alias("yields-slug/index.js", "segmentio-analytics.js-integrations/deps/slug/index.js"); require.alias("visionmedia-batch/index.js", "segmentio-analytics.js-integrations/deps/batch/index.js"); require.alias("component-emitter/index.js", "visionmedia-batch/deps/emitter/index.js"); require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js"); require.alias("visionmedia-debug/index.js", "segmentio-analytics.js-integrations/deps/debug/index.js"); require.alias("visionmedia-debug/debug.js", "segmentio-analytics.js-integrations/deps/debug/debug.js"); require.alias("segmentio-load-pixel/index.js", "segmentio-analytics.js-integrations/deps/load-pixel/index.js"); require.alias("segmentio-load-pixel/index.js", "segmentio-analytics.js-integrations/deps/load-pixel/index.js"); require.alias("component-querystring/index.js", "segmentio-load-pixel/deps/querystring/index.js"); require.alias("component-trim/index.js", "component-querystring/deps/trim/index.js"); require.alias("segmentio-substitute/index.js", "segmentio-load-pixel/deps/substitute/index.js"); require.alias("segmentio-substitute/index.js", "segmentio-load-pixel/deps/substitute/index.js"); require.alias("segmentio-substitute/index.js", "segmentio-substitute/index.js"); require.alias("segmentio-load-pixel/index.js", "segmentio-load-pixel/index.js"); require.alias("segmentio-canonical/index.js", "analytics/deps/canonical/index.js"); require.alias("segmentio-canonical/index.js", "canonical/index.js"); require.alias("segmentio-extend/index.js", "analytics/deps/extend/index.js"); require.alias("segmentio-extend/index.js", "extend/index.js"); require.alias("segmentio-facade/lib/index.js", "analytics/deps/facade/lib/index.js"); require.alias("segmentio-facade/lib/alias.js", "analytics/deps/facade/lib/alias.js"); require.alias("segmentio-facade/lib/facade.js", "analytics/deps/facade/lib/facade.js"); require.alias("segmentio-facade/lib/group.js", "analytics/deps/facade/lib/group.js"); require.alias("segmentio-facade/lib/page.js", "analytics/deps/facade/lib/page.js"); require.alias("segmentio-facade/lib/identify.js", "analytics/deps/facade/lib/identify.js"); require.alias("segmentio-facade/lib/is-enabled.js", "analytics/deps/facade/lib/is-enabled.js"); require.alias("segmentio-facade/lib/track.js", "analytics/deps/facade/lib/track.js"); require.alias("segmentio-facade/lib/index.js", "analytics/deps/facade/index.js"); require.alias("segmentio-facade/lib/index.js", "facade/index.js"); require.alias("camshaft-require-component/index.js", "segmentio-facade/deps/require-component/index.js"); require.alias("segmentio-isodate-traverse/index.js", "segmentio-facade/deps/isodate-traverse/index.js"); require.alias("component-each/index.js", "segmentio-isodate-traverse/deps/each/index.js"); require.alias("component-type/index.js", "component-each/deps/type/index.js"); require.alias("ianstormtaylor-is/index.js", "segmentio-isodate-traverse/deps/is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-isodate/index.js", "segmentio-isodate-traverse/deps/isodate/index.js"); require.alias("component-clone/index.js", "segmentio-facade/deps/clone/index.js"); require.alias("component-type/index.js", "component-clone/deps/type/index.js"); require.alias("component-inherit/index.js", "segmentio-facade/deps/inherit/index.js"); require.alias("component-trim/index.js", "segmentio-facade/deps/trim/index.js"); require.alias("segmentio-is-email/index.js", "segmentio-facade/deps/is-email/index.js"); require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/lib/index.js"); require.alias("segmentio-new-date/lib/milliseconds.js", "segmentio-facade/deps/new-date/lib/milliseconds.js"); require.alias("segmentio-new-date/lib/seconds.js", "segmentio-facade/deps/new-date/lib/seconds.js"); require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/index.js"); require.alias("ianstormtaylor-is/index.js", "segmentio-new-date/deps/is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-isodate/index.js", "segmentio-new-date/deps/isodate/index.js"); require.alias("segmentio-new-date/lib/index.js", "segmentio-new-date/index.js"); require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js"); require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js"); require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/lib/index.js"); require.alias("ianstormtaylor-case/lib/cases.js", "segmentio-obj-case/deps/case/lib/cases.js"); require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/index.js"); require.alias("ianstormtaylor-to-camel-case/index.js", "ianstormtaylor-case/deps/to-camel-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-camel-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-case/deps/to-capital-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-constant-case/index.js", "ianstormtaylor-case/deps/to-constant-case/index.js"); require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-to-constant-case/deps/to-snake-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-dot-case/index.js", "ianstormtaylor-case/deps/to-dot-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-dot-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-pascal-case/index.js", "ianstormtaylor-case/deps/to-pascal-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-pascal-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-sentence-case/index.js", "ianstormtaylor-case/deps/to-sentence-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-sentence-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-slug-case/index.js", "ianstormtaylor-case/deps/to-slug-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-slug-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-case/deps/to-snake-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-title-case/index.js", "ianstormtaylor-case/deps/to-title-case/index.js"); require.alias("component-escape-regexp/index.js", "ianstormtaylor-to-title-case/deps/escape-regexp/index.js"); require.alias("ianstormtaylor-map/index.js", "ianstormtaylor-to-title-case/deps/map/index.js"); require.alias("component-each/index.js", "ianstormtaylor-map/deps/each/index.js"); require.alias("component-type/index.js", "component-each/deps/type/index.js"); require.alias("ianstormtaylor-title-case-minors/index.js", "ianstormtaylor-to-title-case/deps/title-case-minors/index.js"); require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-to-title-case/deps/to-capital-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-case/lib/index.js", "ianstormtaylor-case/index.js"); require.alias("segmentio-obj-case/index.js", "segmentio-obj-case/index.js"); require.alias("segmentio-facade/lib/index.js", "segmentio-facade/index.js"); require.alias("segmentio-is-email/index.js", "analytics/deps/is-email/index.js"); require.alias("segmentio-is-email/index.js", "is-email/index.js"); require.alias("segmentio-is-meta/index.js", "analytics/deps/is-meta/index.js"); require.alias("segmentio-is-meta/index.js", "is-meta/index.js"); require.alias("segmentio-isodate-traverse/index.js", "analytics/deps/isodate-traverse/index.js"); require.alias("segmentio-isodate-traverse/index.js", "isodate-traverse/index.js"); require.alias("component-each/index.js", "segmentio-isodate-traverse/deps/each/index.js"); require.alias("component-type/index.js", "component-each/deps/type/index.js"); require.alias("ianstormtaylor-is/index.js", "segmentio-isodate-traverse/deps/is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-isodate/index.js", "segmentio-isodate-traverse/deps/isodate/index.js"); require.alias("segmentio-json/index.js", "analytics/deps/json/index.js"); require.alias("segmentio-json/index.js", "json/index.js"); require.alias("component-json-fallback/index.js", "segmentio-json/deps/json-fallback/index.js"); require.alias("segmentio-new-date/lib/index.js", "analytics/deps/new-date/lib/index.js"); require.alias("segmentio-new-date/lib/milliseconds.js", "analytics/deps/new-date/lib/milliseconds.js"); require.alias("segmentio-new-date/lib/seconds.js", "analytics/deps/new-date/lib/seconds.js"); require.alias("segmentio-new-date/lib/index.js", "analytics/deps/new-date/index.js"); require.alias("segmentio-new-date/lib/index.js", "new-date/index.js"); require.alias("ianstormtaylor-is/index.js", "segmentio-new-date/deps/is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-isodate/index.js", "segmentio-new-date/deps/isodate/index.js"); require.alias("segmentio-new-date/lib/index.js", "segmentio-new-date/index.js"); require.alias("segmentio-store.js/store.js", "analytics/deps/store/store.js"); require.alias("segmentio-store.js/store.js", "analytics/deps/store/index.js"); require.alias("segmentio-store.js/store.js", "store/index.js"); require.alias("segmentio-store.js/store.js", "segmentio-store.js/index.js"); require.alias("segmentio-top-domain/index.js", "analytics/deps/top-domain/index.js"); require.alias("segmentio-top-domain/index.js", "analytics/deps/top-domain/index.js"); require.alias("segmentio-top-domain/index.js", "top-domain/index.js"); require.alias("component-url/index.js", "segmentio-top-domain/deps/url/index.js"); require.alias("segmentio-top-domain/index.js", "segmentio-top-domain/index.js"); require.alias("visionmedia-debug/index.js", "analytics/deps/debug/index.js"); require.alias("visionmedia-debug/debug.js", "analytics/deps/debug/debug.js"); require.alias("visionmedia-debug/index.js", "debug/index.js"); require.alias("yields-prevent/index.js", "analytics/deps/prevent/index.js"); require.alias("yields-prevent/index.js", "prevent/index.js"); require.alias("analytics/lib/index.js", "analytics/index.js");if (typeof exports == "object") { module.exports = require("analytics"); } else if (typeof define == "function" && define.amd) { define([], function(){ return require("analytics"); }); } else { this["analytics"] = require("analytics"); }})();
docs/app/Examples/elements/Step/Variations/StepExampleStackable.js
shengnian/shengnian-ui-react
import React from 'react' import { Icon, Step } from 'shengnian-ui-react' const StepExampleStackable = () => ( <Step.Group stackable='tablet'> <Step> <Icon name='plane' /> <Step.Content> <Step.Title>Shipping</Step.Title> <Step.Description>Choose your shipping options</Step.Description> </Step.Content> </Step> <Step active> <Icon name='dollar' /> <Step.Content> <Step.Title>Billing</Step.Title> <Step.Description>Enter billing information</Step.Description> </Step.Content> </Step> <Step disabled> <Icon name='info circle' /> <Step.Content> <Step.Title>Confirm Order</Step.Title> <Step.Description>Verify order details</Step.Description> </Step.Content> </Step> </Step.Group> ) export default StepExampleStackable
website/src/AppFrame.js
kkamperschroer/react-navigation
import React from 'react'; import Link from './Link'; import Footer from './Footer'; import { addNavigationHelpers, } from 'react-navigation'; const NavigationLinks = ({navigation, className, reverse}) => { let links = [ ...navigation.state.routes.map((route, i) => { if (route.routeName === 'Home' || route.routeName === 'NotFound') { return null; } return ( <Link to={route.routeName} className={i === navigation.state.index ? 'active':''} key={route.routeName}> {route.routeName} </Link> ); }), <a href="https://github.com/react-community/react-navigation" key="github"> GitHub </a>, ]; if (reverse) { links = links.reverse(); } return ( <div className={className}> {links} </div> ); } class AppFrame extends React.Component { state = {isMobileMenuOpen: false}; componentWillReceiveProps(props) { if (this.props.navigation.state !== props.navigation.state) { this.setState({isMobileMenuOpen: false}); window.scrollTo(0,0); } } render() { const {navigation, router} = this.props; const {isMobileMenuOpen} = this.state; const childNavigation = addNavigationHelpers({ ...navigation, state: navigation.state.routes[navigation.state.index], }); const {state} = navigation; const ScreenView = router.getComponentForRouteName(state.routes[state.index].routeName); const {routes, index} = state; const route = routes[index]; const hasChildNavigation = !!route.routes; return ( <div className={`main-app ${isMobileMenuOpen ? 'mobileMenuActive' : ''}`}> <nav className="pt-navbar" id="navbar"><div className="inner-navbar"> <Link className="pt-navbar-group pt-align-left project-title" to="Home"> <img src="/assets/react-nav-logo.svg" role="presentation" className="logo" /> <h1 className="pt-navbar-heading"> React Navigation </h1> </Link> <NavigationLinks navigation={navigation} className="navbuttons" /> {hasChildNavigation && ( <span className={`pt-icon-properties openMenuButton ${isMobileMenuOpen ? 'active' : ''}`} onClick={() => { this.setState(s => ({ isMobileMenuOpen: !s.isMobileMenuOpen})); window.scrollTo(0,0); }} /> )} </div></nav> <NavigationLinks navigation={navigation} className="mobile-navbuttons" reverse /> <ScreenView navigation={childNavigation} /> <Footer /> </div> ); } } export default AppFrame;
ajax/libs/jquery/1.11.1-rc1/jquery.min.js
dada0423/cdnjs
/*! jQuery v1.11.1-rc1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1-rc1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t="sizzle"+-new Date,u=a.document,v=0,w=0,x=fb(),y=fb(),z=fb(),A=function(a,b){return a===b&&(k=!0),0},B="undefined",C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=E.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;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+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+N+")|)|)"+L+"*\\]",P=":("+M+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+O.replace(3,8)+")*)|.*)\\)|)",Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(P),V=new RegExp("^"+N+"$"),W={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")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,ab=/'|\\/g,bb=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),cb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{H.apply(E=I.call(u.childNodes),u.childNodes),E[u.childNodes.length].nodeType}catch(db){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 eb(a,b,d,e){var f,g,i,j,k,n,q,r,v,w;if((b?b.ownerDocument||b:u)!==m&&l(b),b=b||m,d=d||[],!a||"string"!=typeof a)return d;if(1!==(j=b.nodeType)&&9!==j)return[];if(o&&!e){if(f=$.exec(a))if(i=f[1]){if(9===j){if(g=b.getElementById(i),!g||!g.parentNode)return d;if(g.id===i)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(i))&&s(b,g)&&g.id===i)return d.push(g),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((i=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(i)),d}if(c.qsa&&(!p||!p.test(a))){if(r=q=t,v=b,w=9===j&&a,1===j&&"object"!==b.nodeName.toLowerCase()){n=pb(a),(q=b.getAttribute("id"))?r=q.replace(ab,"\\$&"):b.setAttribute("id",r),r="[id='"+r+"'] ",k=n.length;while(k--)n[k]=r+qb(n[k]);v=_.test(a)&&nb(b.parentNode)||b,w=n.join(",")}if(w)try{return H.apply(d,v.querySelectorAll(w)),d}catch(x){}finally{q||b.removeAttribute("id")}}}return h(a.replace(Q,"$1"),b,d,e)}function fb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function gb(a){return a[t]=!0,a}function hb(a){var b=m.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ib(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function jb(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 kb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function mb(a){return gb(function(b){return b=+b,gb(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 nb(a){return a&&typeof a.getElementsByTagName!==B&&a}c=eb.support={},f=eb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},l=eb.setDocument=function(a){var b,e=a?a.ownerDocument||a:u,g=e.defaultView;return e!==m&&9===e.nodeType&&e.documentElement?(m=e,n=e.documentElement,o=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){l()},!1):g.attachEvent&&g.attachEvent("onunload",function(){l()})),c.attributes=hb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=hb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(e.getElementsByClassName)&&hb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=hb(function(a){return n.appendChild(a).id=t,!e.getElementsByName||!e.getElementsByName(t).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==B&&o){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(bb,cb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(bb,cb);return function(a){var c=typeof a.getAttributeNode!==B&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==B?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==B&&o?b.getElementsByClassName(a):void 0},q=[],p=[],(c.qsa=Z.test(e.querySelectorAll))&&(hb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&p.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||p.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll(":checked").length||p.push(":checked")}),hb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&p.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||p.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),p.push(",.*:")})),(c.matchesSelector=Z.test(r=n.webkitMatchesSelector||n.mozMatchesSelector||n.oMatchesSelector||n.msMatchesSelector))&&hb(function(a){c.disconnectedMatch=r.call(a,"div"),r.call(a,"[s!='']:x"),q.push("!=",P)}),p=p.length&&new RegExp(p.join("|")),q=q.length&&new RegExp(q.join("|")),b=Z.test(n.compareDocumentPosition),s=b||Z.test(n.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},A=b?function(a,b){if(a===b)return k=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===u&&s(u,a)?-1:b===e||b.ownerDocument===u&&s(u,b)?1:j?J.call(j,a)-J.call(j,b):0:4&d?-1:1)}:function(a,b){if(a===b)return k=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:j?J.call(j,a)-J.call(j,b):0;if(f===g)return jb(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?jb(h[d],i[d]):h[d]===u?-1:i[d]===u?1:0},e):m},eb.matches=function(a,b){return eb(a,null,null,b)},eb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==m&&l(a),b=b.replace(T,"='$1']"),!(!c.matchesSelector||!o||q&&q.test(b)||p&&p.test(b)))try{var d=r.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return eb(b,m,null,[a]).length>0},eb.contains=function(a,b){return(a.ownerDocument||a)!==m&&l(a),s(a,b)},eb.attr=function(a,b){(a.ownerDocument||a)!==m&&l(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!o):void 0;return void 0!==f?f:c.attributes||!o?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},eb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},eb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(k=!c.detectDuplicates,j=!c.sortStable&&a.slice(0),a.sort(A),k){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return j=null,a},e=eb.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=eb.selectors={cacheLength:50,createPseudo:gb,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(bb,cb),a[3]=(a[4]||a[5]||"").replace(bb,cb),"~="===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]||eb.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]&&eb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return W.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&U.test(c)&&(b=pb(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(bb,cb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=x[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&x(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==B&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=eb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[t]||(q[t]={}),j=k[a]||[],n=j[0]===v&&j[1],m=j[0]===v&&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]=[v,n,m];break}}else if(s&&(j=(b[t]||(b[t]={}))[a])&&j[0]===v)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[t]||(l[t]={}))[a]=[v,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()]||eb.error("unsupported pseudo: "+a);return e[t]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?gb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:gb(function(a){var b=[],c=[],d=g(a.replace(Q,"$1"));return d[t]?gb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:gb(function(a){return function(b){return eb(a,b).length>0}}),contains:gb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:gb(function(a){return V.test(a||"")||eb.error("unsupported lang: "+a),a=a.replace(bb,cb).toLowerCase(),function(b){var c;do if(c=o?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===n},focus:function(a){return a===m.activeElement&&(!m.hasFocus||m.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:mb(function(){return[0]}),last:mb(function(a,b){return[b-1]}),eq:mb(function(a,b,c){return[0>c?c+b:c]}),even:mb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:mb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:mb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:mb(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]=kb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=lb(b);function ob(){}ob.prototype=d.filters=d.pseudos,d.setFilters=new ob;function pb(a,b){var c,e,f,g,h,i,j,k=y[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=R.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?eb.error(a):y(a,i).slice(0)}function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=w++;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=[v,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[t]||(b[t]={}),(h=i[d])&&h[0]===v&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)eb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[t]&&(d=vb(d)),e&&!e[t]&&(e=vb(e,f)),gb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],j=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return J.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==i)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[t]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return vb(j>1&&sb(m),j>1&&qb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(Q,"$1"),c,e>j&&wb(a.slice(j,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,j,k){var l,n,o,p=0,q="0",r=f&&[],s=[],t=i,u=f||e&&d.find.TAG("*",k),w=v+=null==t?1:Math.random()||.1,x=u.length;for(k&&(i=g!==m&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){n=0;while(o=a[n++])if(o(l,g,h)){j.push(l);break}k&&(v=w)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(j));s=ub(s)}H.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&eb.uniqueSort(j)}return k&&(v=w,i=t),r};return c?gb(f):f}return g=eb.compile=function(a,b){var c,d=[],e=[],f=z[a+" "];if(!f){b||(b=pb(a)),c=b.length;while(c--)f=wb(b[c]),f[t]?d.push(f):e.push(f);f=z(a,xb(e,d)),f.selector=a}return f},h=eb.select=function(a,b,e,f){var h,i,j,k,l,m="function"==typeof a&&a,n=!f&&pb(a=m.selector||a);if(e=e||[],1===n.length){if(i=n[0]=n[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&o&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(bb,cb),b)||[])[0],!b)return e;m&&(b=b.parentNode),a=a.slice(i.shift().value.length)}h=W.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(bb,cb),_.test(i[0].type)&&nb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&qb(i),!a)return H.apply(e,f),e;break}}}return(m||g(a,n))(f,b,!o,e,_.test(a)&&nb(b.parentNode)||b),e},c.sortStable=t.split("").sort(A).join("")===t,c.detectDuplicates=!!k,l(),c.sortDetached=hb(function(a){return 1&a.compareDocumentPosition(m.createElement("div"))}),hb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ib("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&hb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ib("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),hb(function(a){return null==a.getAttribute("disabled")})||ib(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}),eb}(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--)d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d]));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px") },cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l=this,n={},o=a.style,p=a.nodeType&&U(a),q=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++,l.always(function(){l.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=m.css(a,"display"),"inline"===("none"===j?Fb(a.nodeName):j)&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?o.zoom=1:o.display="inline-block")),c.overflow&&(o.overflow="hidden",k.shrinkWrapBlocks()||l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}n[d]=q&&q[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(n))"inline"===("none"===j?Fb(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=m._data(a,"fxshow",{}),f&&(q.hidden=!p),p?m(a).show():l.done(function(){m(a).hide()}),l.done(function(){var b;m._removeData(a,"fxshow");for(b in n)m.style(a,b,n[b])});for(d in n)g=hc(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m}); //# sourceMappingURL=jquery.min.map
app/javascript/mastodon/features/notifications/components/notification.js
haleyashleypraesent/ProjectPrionosuchus
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import StatusContainer from '../../../containers/status_container'; import AccountContainer from '../../../containers/account_container'; import Avatar from '../../../components/avatar'; import { FormattedMessage } from 'react-intl'; import Permalink from '../../../components/permalink'; import emojify from '../../../emoji'; import escapeTextContentForBrowser from 'escape-html'; import ImmutablePureComponent from 'react-immutable-pure-component'; class Notification extends ImmutablePureComponent { static propTypes = { notification: ImmutablePropTypes.map.isRequired, }; renderFollow (account, link) { return ( <div className='notification notification-follow'> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <i className='fa fa-fw fa-user-plus' /> </div> <FormattedMessage id='notification.follow' defaultMessage='{name} followed you' values={{ name: link }} /> </div> <AccountContainer id={account.get('id')} withNote={false} /> </div> ); } renderMention (notification) { return <StatusContainer id={notification.get('status')} withDismiss />; } renderFavourite (notification, link) { return ( <div className='notification notification-favourite'> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <i className='fa fa-fw fa-star star-icon' /> </div> <FormattedMessage id='notification.favourite' defaultMessage='{name} favourited your status' values={{ name: link }} /> </div> <StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss /> </div> ); } renderReblog (notification, link) { return ( <div className='notification notification-reblog'> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <i className='fa fa-fw fa-retweet' /> </div> <FormattedMessage id='notification.reblog' defaultMessage='{name} boosted your status' values={{ name: link }} /> </div> <StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss /> </div> ); } render () { const { notification } = this.props; const account = notification.get('account'); const displayName = account.get('display_name').length > 0 ? account.get('display_name') : account.get('username'); const displayNameHTML = { __html: emojify(escapeTextContentForBrowser(displayName)) }; const link = <Permalink className='notification__display-name' href={account.get('url')} title={account.get('acct')} to={`/accounts/${account.get('id')}`} dangerouslySetInnerHTML={displayNameHTML} />; switch(notification.get('type')) { case 'follow': return this.renderFollow(account, link); case 'mention': return this.renderMention(notification); case 'favourite': return this.renderFavourite(notification, link); case 'reblog': return this.renderReblog(notification, link); } return null; } } export default Notification;
examples/src/components/Icons.js
tkloht/react-video-cover
import React from 'react'; import SVGButtonStyles from './SVGButton.module.css'; /* eslint-disable max-len */ /* source: https://github.com/gilbarbara/logos */ const GithubLogo = () => ( <svg width="32px" height="32px" viewBox="0 0 256 250" preserveAspectRatio="xMidYMid" className={SVGButtonStyles.SVGButton}> <g> <path d="M128.00106,0 C57.3172926,0 0,57.3066942 0,128.00106 C0,184.555281 36.6761997,232.535542 87.534937,249.460899 C93.9320223,250.645779 96.280588,246.684165 96.280588,243.303333 C96.280588,240.251045 96.1618878,230.167899 96.106777,219.472176 C60.4967585,227.215235 52.9826207,204.369712 52.9826207,204.369712 C47.1599584,189.574598 38.770408,185.640538 38.770408,185.640538 C27.1568785,177.696113 39.6458206,177.859325 39.6458206,177.859325 C52.4993419,178.762293 59.267365,191.04987 59.267365,191.04987 C70.6837675,210.618423 89.2115753,204.961093 96.5158685,201.690482 C97.6647155,193.417512 100.981959,187.77078 104.642583,184.574357 C76.211799,181.33766 46.324819,170.362144 46.324819,121.315702 C46.324819,107.340889 51.3250588,95.9223682 59.5132437,86.9583937 C58.1842268,83.7344152 53.8029229,70.715562 60.7532354,53.0843636 C60.7532354,53.0843636 71.5019501,49.6441813 95.9626412,66.2049595 C106.172967,63.368876 117.123047,61.9465949 128.00106,61.8978432 C138.879073,61.9465949 149.837632,63.368876 160.067033,66.2049595 C184.49805,49.6441813 195.231926,53.0843636 195.231926,53.0843636 C202.199197,70.715562 197.815773,83.7344152 196.486756,86.9583937 C204.694018,95.9223682 209.660343,107.340889 209.660343,121.315702 C209.660343,170.478725 179.716133,181.303747 151.213281,184.472614 C155.80443,188.444828 159.895342,196.234518 159.895342,208.176593 C159.895342,225.303317 159.746968,239.087361 159.746968,243.303333 C159.746968,246.709601 162.05102,250.70089 168.53925,249.443941 C219.370432,232.499507 256,184.536204 256,128.00106 C256,57.3066942 198.691187,0 128.00106,0 Z M47.9405593,182.340212 C47.6586465,182.976105 46.6581745,183.166873 45.7467277,182.730227 C44.8183235,182.312656 44.2968914,181.445722 44.5978808,180.80771 C44.8734344,180.152739 45.876026,179.97045 46.8023103,180.409216 C47.7328342,180.826786 48.2627451,181.702199 47.9405593,182.340212 Z M54.2367892,187.958254 C53.6263318,188.524199 52.4329723,188.261363 51.6232682,187.366874 C50.7860088,186.474504 50.6291553,185.281144 51.2480912,184.70672 C51.8776254,184.140775 53.0349512,184.405731 53.8743302,185.298101 C54.7115892,186.201069 54.8748019,187.38595 54.2367892,187.958254 Z M58.5562413,195.146347 C57.7719732,195.691096 56.4895886,195.180261 55.6968417,194.042013 C54.9125733,192.903764 54.9125733,191.538713 55.713799,190.991845 C56.5086651,190.444977 57.7719732,190.936735 58.5753181,192.066505 C59.3574669,193.22383 59.3574669,194.58888 58.5562413,195.146347 Z M65.8613592,203.471174 C65.1597571,204.244846 63.6654083,204.03712 62.5716717,202.981538 C61.4524999,201.94927 61.1409122,200.484596 61.8446341,199.710926 C62.5547146,198.935137 64.0575422,199.15346 65.1597571,200.200564 C66.2704506,201.230712 66.6095936,202.705984 65.8613592,203.471174 Z M75.3025151,206.281542 C74.9930474,207.284134 73.553809,207.739857 72.1039724,207.313809 C70.6562556,206.875043 69.7087748,205.700761 70.0012857,204.687571 C70.302275,203.678621 71.7478721,203.20382 73.2083069,203.659543 C74.6539041,204.09619 75.6035048,205.261994 75.3025151,206.281542 Z M86.046947,207.473627 C86.0829806,208.529209 84.8535871,209.404622 83.3316829,209.4237 C81.8013,209.457614 80.563428,208.603398 80.5464708,207.564772 C80.5464708,206.498591 81.7483088,205.631657 83.2786917,205.606221 C84.8005962,205.576546 86.046947,206.424403 86.046947,207.473627 Z M96.6021471,207.069023 C96.7844366,208.099171 95.7267341,209.156872 94.215428,209.438785 C92.7295577,209.710099 91.3539086,209.074206 91.1652603,208.052538 C90.9808515,206.996955 92.0576306,205.939253 93.5413813,205.66582 C95.054807,205.402984 96.4092596,206.021919 96.6021471,207.069023 Z" fill="#161614" /> </g> </svg> ); /** * source: https://github.com/google/material-design-icons * by google * licensed under CC BY 4.0 https://creativecommons.org/licenses/by/4.0/ */ const RefreshIcon = () => ( <svg width="36px" height="36px" viewBox="0 0 36 36" className={SVGButtonStyles.SVGButton}> <path d="M26.47 9.53C24.3 7.35 21.32 6 18 6 11.37 6 6 11.37 6 18s5.37 12 12 12c5.94 0 10.85-4.33 11.81-10h-3.04c-.91 4.01-4.49 7-8.77 7-4.97 0-9-4.03-9-9s4.03-9 9-9c2.49 0 4.71 1.03 6.34 2.66L20 16h10V6l-3.53 3.53z" /> </svg> ); export default { GithubLogo, RefreshIcon }; export { RefreshIcon, GithubLogo };
src/Parser/Druid/Guardian/Modules/Features/AntiFillerSpam.js
enragednuke/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import { formatPercentage } from 'common/format'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import Wrapper from 'common/Wrapper'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import EnemyInstances from 'Parser/Core/Modules/EnemyInstances'; import SpellUsable from 'Parser/Core/Modules/SpellUsable'; import GlobalCooldown from 'Parser/Core/Modules/GlobalCooldown'; import StatisticBox from 'Main/StatisticBox'; import Abilities from '../Abilities'; import ActiveTargets from './ActiveTargets'; const debug = false; // Determines whether a variable is a function or not, and returns its value function resolveValue(maybeFunction, ...args) { if (typeof maybeFunction === 'function') { return maybeFunction(...args); } return maybeFunction; } class AntiFillerSpam extends Analyzer { static dependencies = { combatants: Combatants, enemyInstances: EnemyInstances, activeTargets: ActiveTargets, spellUsable: SpellUsable, globalCooldown: GlobalCooldown, abilities: Abilities, }; abilityLastCasts = {}; _totalGCDSpells = 0; _totalFillerSpells = 0; _unnecessaryFillerSpells = 0; on_byPlayer_cast(event) { const spellId = event.ability.guid; const ability = this.abilities.getAbility(spellId); if (!ability || !ability.isOnGCD) { return; } this._totalGCDSpells += 1; const timestamp = event.timestamp; const spellLastCast = this.abilityLastCasts[spellId] || -Infinity; const targets = this.activeTargets.getActiveTargets(event.timestamp).map(enemyID => this.enemyInstances.enemies[enemyID]).filter(enemy => !!enemy); const combatant = this.combatants.selected; this.abilityLastCasts[spellId] = timestamp; let isFiller = false; if (ability.antiFillerSpam) { if (typeof ability.antiFillerSpam.isFiller === 'function') { isFiller = ability.antiFillerSpam.isFiller(event, combatant, targets, spellLastCast); } else { isFiller = ability.antiFillerSpam.isFiller; } } if (!isFiller) { return; } debug && console.group(`[FILLER SPELL] - ${spellId} ${SPELLS[spellId].name}`); this._totalFillerSpells += 1; const availableSpells = []; // Only abilities on the GCD matter since the goal is to make sure every GCD is used as efficiently as possible this.globalCooldown.abilitiesOnGlobalCooldown .map(spellId => this.abilities.getAbility(spellId)) .filter(ability => ability !== null) .forEach(gcdSpell => { const gcdSpellId = gcdSpell.primarySpell.id; if (ability.primarySpell.id === gcdSpellId) { return; } const lastCast = this.abilityLastCasts[gcdSpellId] || -Infinity; const isFillerEval = gcdSpell.antiFillerSpam && (typeof gcdSpell.antiFillerSpam.isFiller === 'function' ? gcdSpell.antiFillerSpam.isFiller(event, combatant, targets, lastCast) : gcdSpell.antiFillerSpam.isFiller); if (isFillerEval || gcdSpell.category === Abilities.SPELL_CATEGORIES.UTILITY) { return; } const isOffCooldown = this.spellUsable.isAvailable(gcdSpellId); const args = [event, combatant, targets, lastCast]; const meetsCondition = (gcdSpell.antiFillerSpam.condition !== undefined) ? resolveValue(gcdSpell.antiFillerSpam.condition, ...args) : true; if (!meetsCondition) { return; } if (!isOffCooldown) { return; } debug && console.warn(` [Available non-filler] - ${gcdSpellId} ${SPELLS[gcdSpellId].name} - offCD: ${isOffCooldown} - canBeCast: ${meetsCondition} `); availableSpells.push(gcdSpellId); }); if (availableSpells.length > 0) { this._unnecessaryFillerSpells += 1; } debug && console.groupEnd(); } get fillerSpamPercentage() { return this._unnecessaryFillerSpells / this._totalGCDSpells; } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.SWIPE_BEAR.id} />} value={`${formatPercentage(this.fillerSpamPercentage)}%`} label="Unnecessary Fillers" tooltip={`You cast <strong>${this._unnecessaryFillerSpells}</strong> unnecessary filler spells out of <strong>${this._totalGCDSpells}</strong> total GCDs. Filler spells (Swipe, Moonfire without a GG proc, or Moonfire outside of pandemic if talented into Incarnation) do far less damage than your main rotational spells, and should be minimized whenever possible.`} /> ); } suggestions(when) { when(this.fillerSpamPercentage).isGreaterThan(0.1) .addSuggestion((suggest, actual, recommended) => { return suggest( <Wrapper> You are casting too many unnecessary filler spells. Try to plan your casts two or three GCDs ahead of time to anticipate your main rotational spells coming off cooldown, and to give yourself time to react to <SpellLink id={SPELLS.GORE_BEAR.id} /> and <SpellLink id={SPELLS.GALACTIC_GUARDIAN_TALENT.id} /> procs. </Wrapper> ) .icon(SPELLS.SWIPE_BEAR.icon) .actual(`${formatPercentage(actual)}% unnecessary filler spells cast`) .recommended(`${formatPercentage(recommended, 0)}% or less is recommended`) .regular(recommended + 0.05).major(recommended + 0.1); }); } } export default AntiFillerSpam;
app/index.js
lynks-p2p/lynks-client
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Router, hashHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import routes from './routes'; import configureStore from './store/configureStore'; import './app.global.css'; const store = configureStore(); const history = syncHistoryWithStore(hashHistory, store); render( <Provider store={store}> <Router history={history} routes={routes} /> </Provider>, document.getElementById('root') );
src/components/Player/components/Modal/components/TraktInfo.js
jaruba/PowderPlayer
import React from 'react'; import { shell } from 'electron'; import ModalActions from '../actions'; import PlayerStore from '../../../store'; import traktUtil from '../../../utils/trakt'; import player from '../../../utils/player'; import MetaInspector from 'node-metainspector'; import { BrowserWindow } from 'remote'; export default React.createClass({ getInitialState() { var itemDesc = player.itemDesc(); return { parsedTitle: '', parsedRating: '', trakt: itemDesc.setting.trakt, parsed: itemDesc.setting.parsed, image: itemDesc.setting.image } }, componentDidMount() { this.refs.dialog.open(); }, componentDidUpdate() { this.refs.dialog.open(); }, update() { var setting = player.itemDesc().setting; this.setState({ parsedTitle: setting.parsed.name.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()})+(setting.trakt.season ? "\u00a0\u00a0-\u00a0\u00a0S"+('0' + setting.trakt.season).slice(-2) + ' E' + ('0' + setting.trakt.number).slice(-2) : setting.trakt.year ? '\u00a0\u00a0-\u00a0\u00a0'+setting.trakt.year : ''), parsedRating: (Math.round(setting.trakt.rating * 100) / 100)+' / 10 (' + setting.trakt.votes + ')', trakt: setting.trakt, parsed: setting.parsed, image: setting.image ? setting.image.replace('https://assets.fanart.tv', 'http://assets.fanart.tv') : '' }); }, componentWillMount() { this.update(); }, handleCodeAdd() { var inputvalue = this.refs.codeInput.value; if (inputvalue.length) { ModalActions.close(); try { traktUtil.exchangePin(inputvalue); player.notifier.info('Login Successful'); } catch(e) { player.notifier.info('Error: '+e.message); } } else { this.refs['codeInput'].focus(); player.notifier.info('Error: Trakt Code is Required'); } }, getCode(event) { traktUtil.openTraktAuth(); }, openImdb(event) { shell.openExternal('http://www.imdb.com/title/'+this.state.parsed.imdb+'/'); ModalActions.close(); }, openTrailer(event) { // ModalActions.close(); var client = new MetaInspector('http://m.imdb.com/title/'+this.state.parsed.imdb, { timeout: 5000 }); var parsed = this.state.parsed; client.on("fetch", function(){ // var trailer_url = ('http://m.imdb.com'+client.iframes[0]).replace(/m\.imdb/i, 'www.imdb').replace(/mobile/i, 'embed').replace('autoplay=false','autoplay=true'); if (client && client.links && client.links.relative && client.links.relative.length) { var foundId = client.links.relative.some(function(el) { if (el.startsWith('/video/imdb/')) { var videoId = el.replace('/video/imdb/', '') videoId = videoId.substr(0, videoId.indexOf('?')) var trailer_url = 'http://www.imdb.com/title/' + parsed.imdb + '/videoplayer/' + videoId + '?ref_=m_tt_ov_vi' var win = new BrowserWindow({ width: 854, height: 510, show: false, 'standard-window': true, 'auto-hide-menu-bar': true, resizable: false, title: parsed.name.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()})+' Trailer - IMDB', center: true }); win.on('closed', function() { win = null; }); win.loadUrl(trailer_url); win.webContents.on('did-finish-load', () => { win.show(); win.focus(); // should do this in a preload script // $('.sidebar-close-button').click() // $('.close-button').hide() if (player.wcjs.playing) player.wcjs.togglePause(); }); return true } }) if (!foundId) player.notifier.info('Trailer Not Found', '', 4000); } else player.notifier.info('Trailer Not Found', '', 4000); }); client.on("error", function(err){ player.notifier.info('Trailer Error: '+err, '', 4000); // console.log(err); }); client.fetch(); }, openSearch(event) { ModalActions.open({ title: 'Trakt Search', type: 'TraktSearch', theme: 'DarkRawTheme' }); }, render() { if (this.state.parsed && this.state.parsed.tag && this.state.parsed.tag.length) { var tags = this.state.parsed.tag; } else tags = []; return ( <paper-dialog ref="dialog" style={{width: '900px', textAlign: 'left', borderRadius: '3px', maxWidth: '90%', backgroundColor: '#303030', padding: '20px', overflowX: 'auto'}} opened={false} className="trakt-info-dialog" with-backdrop > <img className="trakt-info-img" src={this.state.image} style={{float: 'left', maxWidth: '52%', padding: '0', margin: '0'}} /> <div className={'trakt-info-desc' + (!this.state.image ? ' trakt-long-desc' : '')} style={{ fontSize: '15px', color: 'white', float: 'left', display: 'inline-block', padding: '0', margin: '0', marginLeft: '3%', maxWidth: '45%' }}> <div style={{ marginBottom: '7px' }}>{this.state.parsedTitle}</div> <div style={{ marginBottom: '7px' }}>{this.state.parsedRating}</div> <div style={{ marginBottom: '7px', display: this.state.trakt.season ? 'block' : 'none' }}>{this.state.trakt.title}</div> <div style={{ marginBottom: '7px', textAlign: 'justify', display: this.state.trakt.overview ? 'block' : 'none' }}>{this.state.trakt.overview}</div> <div style={{ display: true ? 'none' : tags.length ? 'block' : 'none' }}>{tags.join(', ')}</div> </div> <div style={{clear:'both', height: '10px'}} /> <paper-button raised onClick={this.openImdb} style={{ marginBottom: '0', display: this.state.parsed.imdb ? 'block' : 'none' }} className='playerButtons' > IMDB </paper-button> <paper-button raised onClick={this.openTrailer} style={{ marginBottom: '0', display: this.state.parsed.imdb ? 'block' : 'none' }} className='playerButtons' > Trailer </paper-button> <paper-button raised onClick={ModalActions.close} style={{ marginBottom: '0', marginRight: '0', float: 'right' }} className='playerButtons-primary' > Back </paper-button> <paper-button raised onClick={this.openSearch} style={{ marginBottom: '0', float: 'right' }} className='playerButtons trakt-not-correct' > Not Correct? </paper-button> </paper-dialog> ); } });
stories/components/profile/index.js
hollomancer/operationcode_frontend
import React from 'react'; import { storiesOf } from '@storybook/react'; import Profile from 'scenes/home/profile/profile'; // import blocJpg from '../../asset/bloc.jpg'; storiesOf('scenes/home/profile', module) .add('Not Verified', () => <Profile />) .add('Verified', () => <Profile verified />);
src/components/BibleText.js
jcuenod/react-lafwebpy-client
import React from 'react' import ReactHint from 'react-hint' import EventPropagator from 'events/EventPropagator' import VerseView from 'components/BibleText/VerseView' import ClauseAtomView from 'components/BibleText/ClauseAtomView' class BibleText extends React.Component { constructor(props) { super(props) var settings = JSON.parse(localStorage.getItem("qbibleSettings")) || {} this.state = { data: [], active_wid: -1, display_setting: settings } } componentDidMount() { EventPropagator.registerListener([{ eventType: "navigation_request", callback: (payload) => { var request = {} request["reference"] = payload.reference request["reference"]["book"] = request["reference"]["book"].replace(/\ /g, "_") // Find out if highlighting is on var settings = {} EventPropagator.fireEvent({'eventType': 'get_settings', 'payload': { 'callback': (stobj) => { settings = stobj } }}) request.display_by = settings.display_by var highlightobj = {} if (settings.highlight_terms) { // If highlighting is on, then get the queries to highlight and create the terms var rawQueries = [] EventPropagator.fireEvent({'eventType': 'get_terms', 'payload': {'callback': (sterms) => { rawQueries = sterms }}}) var counter = 0 rawQueries.forEach((q) => { delete q["uid"] highlightobj['highlight' + counter++] = q }) request["highlights"] = highlightobj } $.post(window.root_url + "/api/book_chapter", JSON.stringify(request), (result) => { this.setState({data: result}) var newRef = result.reference newRef["book"] = newRef["book"].replace(/\_/g, " ") EventPropagator.fireEvent({ eventType: "navigation_complete", payload: { reference: newRef } }) ga('send', { hitType: 'event', eventCategory: 'bibletext', eventAction: 'navigation' }) }) } }, { eventType: "word_clicked", callback: (payload) => { this.setState({"active_wid": payload.wid}) ga('send', { hitType: 'event', eventCategory: 'bibletext', eventAction: 'word-clicked' }) } }, { eventType: "update_settings", callback: (payload) => { if (["font_size", "font_family"].includes(payload.setting_type)) { var newState = this.state.display_setting newState[payload.setting_type] = payload.value this.setState({"display_setting": newState}) } } }]) } render() { var d = this.state.data var fontsizes = { "small": "130%", "medium": "200%", "large": "270%" } var biblestyles = {} if (this.state.display_setting.hasOwnProperty("font_size")) biblestyles["fontSize"] = fontsizes[this.state.display_setting.font_size] if (this.state.display_setting.hasOwnProperty("font_family")) biblestyles["fontFamily"] = this.state.display_setting.font_family var toDisplay if (d.display_by == "verse") { toDisplay = d.chapter_data.map((verse, i) => ( <VerseView key={i} data={verse} active_wid={this.state.active_wid}></VerseView> )) } else if (d.display_by == "clause") { toDisplay = <div className="clause_atom_holder"> {d.chapter_data.map((clause, i) => ( <ClauseAtomView key={i} data={clause} active_wid={this.state.active_wid}></ClauseAtomView> ))} <ReactHint /> </div> } else { console.log(d) toDisplay = "" } return ( <div className="bible_text_container"> <div className="bible_text" style={biblestyles}> {toDisplay} </div> </div> ) } } export default BibleText
node_modules/react-svg-pan-zoom/node_modules/core-js/modules/es6.promise.js
SpatialMap/SpatialMapDev
'use strict'; var $ = require('./$') , LIBRARY = require('./$.library') , global = require('./$.global') , ctx = require('./$.ctx') , classof = require('./$.classof') , $export = require('./$.export') , isObject = require('./$.is-object') , anObject = require('./$.an-object') , aFunction = require('./$.a-function') , strictNew = require('./$.strict-new') , forOf = require('./$.for-of') , setProto = require('./$.set-proto').set , same = require('./$.same-value') , SPECIES = require('./$.wks')('species') , speciesConstructor = require('./$.species-constructor') , asap = require('./$.microtask') , PROMISE = 'Promise' , process = global.process , isNode = classof(process) == 'process' , P = global[PROMISE] , empty = function(){ /* empty */ } , Wrapper; var testResolve = function(sub){ var test = new P(empty), promise; if(sub)test.constructor = function(exec){ exec(empty, empty); }; (promise = P.resolve(test))['catch'](empty); return promise === test; }; var USE_NATIVE = function(){ var works = false; function P2(x){ var self = new P(x); setProto(self, P2.prototype); return self; } try { works = P && P.resolve && testResolve(); setProto(P2, P); P2.prototype = $.create(P.prototype, {constructor: {value: P2}}); // actual Firefox has broken subclass support, test that if(!(P2.resolve(5).then(function(){}) instanceof P2)){ works = false; } // actual V8 bug, https://code.google.com/p/v8/issues/detail?id=4162 if(works && require('./$.descriptors')){ var thenableThenGotten = false; P.resolve($.setDesc({}, 'then', { get: function(){ thenableThenGotten = true; } })); works = thenableThenGotten; } } catch(e){ works = false; } return works; }(); // helpers var sameConstructor = function(a, b){ // library wrapper special case if(LIBRARY && a === P && b === Wrapper)return true; return same(a, b); }; var getConstructor = function(C){ var S = anObject(C)[SPECIES]; return S != undefined ? S : C; }; var isThenable = function(it){ var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var PromiseCapability = function(C){ var resolve, reject; this.promise = new C(function($$resolve, $$reject){ if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction(resolve), this.reject = aFunction(reject) }; var perform = function(exec){ try { exec(); } catch(e){ return {error: e}; } }; var notify = function(record, isReject){ if(record.n)return; record.n = true; var chain = record.c; asap(function(){ var value = record.v , ok = record.s == 1 , i = 0; var run = function(reaction){ var handler = ok ? reaction.ok : reaction.fail , resolve = reaction.resolve , reject = reaction.reject , result, then; try { if(handler){ if(!ok)record.h = true; result = handler === true ? value : handler(value); if(result === reaction.promise){ reject(TypeError('Promise-chain cycle')); } else if(then = isThenable(result)){ then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch(e){ reject(e); } }; while(chain.length > i)run(chain[i++]); // variable length - can't use forEach chain.length = 0; record.n = false; if(isReject)setTimeout(function(){ var promise = record.p , handler, console; if(isUnhandled(promise)){ if(isNode){ process.emit('unhandledRejection', value, promise); } else if(handler = global.onunhandledrejection){ handler({promise: promise, reason: value}); } else if((console = global.console) && console.error){ console.error('Unhandled promise rejection', value); } } record.a = undefined; }, 1); }); }; var isUnhandled = function(promise){ var record = promise._d , chain = record.a || record.c , i = 0 , reaction; if(record.h)return false; while(chain.length > i){ reaction = chain[i++]; if(reaction.fail || !isUnhandled(reaction.promise))return false; } return true; }; var $reject = function(value){ var record = this; if(record.d)return; record.d = true; record = record.r || record; // unwrap record.v = value; record.s = 2; record.a = record.c.slice(); notify(record, true); }; var $resolve = function(value){ var record = this , then; if(record.d)return; record.d = true; record = record.r || record; // unwrap try { if(record.p === value)throw TypeError("Promise can't be resolved itself"); if(then = isThenable(value)){ asap(function(){ var wrapper = {r: record, d: false}; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch(e){ $reject.call(wrapper, e); } }); } else { record.v = value; record.s = 1; notify(record, false); } } catch(e){ $reject.call({r: record, d: false}, e); // wrap } }; // constructor polyfill if(!USE_NATIVE){ // 25.4.3.1 Promise(executor) P = function Promise(executor){ aFunction(executor); var record = this._d = { p: strictNew(this, P, PROMISE), // <- promise c: [], // <- awaiting reactions a: undefined, // <- checked in isUnhandled reactions s: 0, // <- state d: false, // <- done v: undefined, // <- value h: false, // <- handled rejection n: false // <- notify }; try { executor(ctx($resolve, record, 1), ctx($reject, record, 1)); } catch(err){ $reject.call(record, err); } }; require('./$.redefine-all')(P.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var reaction = new PromiseCapability(speciesConstructor(this, P)) , promise = reaction.promise , record = this._d; reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; record.c.push(reaction); if(record.a)record.a.push(reaction); if(record.s)notify(record, false); return promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: P}); require('./$.set-to-string-tag')(P, PROMISE); require('./$.set-species')(PROMISE); Wrapper = require('./$.core')[PROMISE]; // statics $export($export.S + $export.F * !USE_NATIVE, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ var capability = new PromiseCapability(this) , $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (!USE_NATIVE || testResolve(true)), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x){ // instanceof instead of internal slot check because we should fix it without replacement native Promise core if(x instanceof P && sameConstructor(x.constructor, this))return x; var capability = new PromiseCapability(this) , $$resolve = capability.resolve; $$resolve(x); return capability.promise; } }); $export($export.S + $export.F * !(USE_NATIVE && require('./$.iter-detect')(function(iter){ P.all(iter)['catch'](function(){}); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = getConstructor(this) , capability = new PromiseCapability(C) , resolve = capability.resolve , reject = capability.reject , values = []; var abrupt = perform(function(){ forOf(iterable, false, values.push, values); var remaining = values.length , results = Array(remaining); if(remaining)$.each.call(values, function(promise, index){ var alreadyCalled = false; C.resolve(promise).then(function(value){ if(alreadyCalled)return; alreadyCalled = true; results[index] = value; --remaining || resolve(results); }, reject); }); else resolve(results); }); if(abrupt)reject(abrupt.error); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = getConstructor(this) , capability = new PromiseCapability(C) , reject = capability.reject; var abrupt = perform(function(){ forOf(iterable, false, function(promise){ C.resolve(promise).then(capability.resolve, reject); }); }); if(abrupt)reject(abrupt.error); return capability.promise; } });
src/client/components/TurnIndicator/TurnIndicator.js
eliasmeire/hz-pictionary
import React from 'react'; import './TurnIndicator.scss'; const TurnIndicator = ({ user, drawingPlayer }) => ( <div className="turn-indicator"> { drawingPlayer.id === user.id ? 'Your turn!' : `${drawingPlayer.name}'s turn` } </div> ); export default TurnIndicator;
src/server/render.js
HackArdennes2017/Project06
import { renderToString, renderToStaticMarkup } from 'react-dom/server' import { StaticRouter } from 'react-router' import { matchPath } from 'react-router-dom' import React from 'react' import routes from 'routes' import createStore from 'store' import { fetchItems } from 'action/items' import Html from 'components/Html' import App from 'components/App' export default stats => async (req, res) => { try { const store = createStore() await store.dispatch(fetchItems()) const context = {} const promises = [] routes.some(route => { const match = matchPath(req.url, route) if (match && route.load) { promises.push(route.load(store)) } return match }) await Promise.all(promises) const root = App(store, StaticRouter, { location: req.url, context }) const page = ( <Html stats={stats} state={store.getState()} content={renderToString(root)} /> ) res.end(`<!doctype html>${renderToStaticMarkup(page)}`) } catch (err) { res.status(500).send(err.stack) } }
gulpfile.js
worminer/React.js-Financial-News
let gulp = require('gulp'); let gutil = require('gulp-util'); let gulpif = require('gulp-if'); let autoprefixer = require('gulp-autoprefixer'); let cssmin = require('gulp-cssmin'); let less = require('gulp-less'); let concat = require('gulp-concat'); let plumber = require('gulp-plumber'); let buffer = require('vinyl-buffer'); let source = require('vinyl-source-stream'); let babelify = require('babelify'); let browserify = require('browserify'); let watchify = require('watchify'); let uglify = require('gulp-uglify'); let sourcemaps = require('gulp-sourcemaps'); let production = process.env.NODE_ENV === 'production'; let dependencies = [ 'react', 'react-dom', 'react-router', 'underscore' ]; /* |-------------------------------------------------------------------------- | Combine all JS libraries into a single file for fewer HTTP requests. |-------------------------------------------------------------------------- */ gulp.task('vendor', function () { return gulp.src([ 'bower_components/jquery/dist/jquery.js', 'bower_components/bootstrap/dist/scripts/bootstrap.js', 'bower_components/magnific-popup/dist/jquery.magnific-popup.js', 'bower_components/ShowMessage/ShowMessage.js', 'bower_components/bootstrap-star-rating/star-rating.min.js' ]).pipe(concat('vendor.js')) .pipe(gulpif(production, uglify({mangle: false}))) .pipe(gulp.dest('public/scripts')); }); /* |-------------------------------------------------------------------------- | Compile third-party dependencies separately for faster performance. |-------------------------------------------------------------------------- */ gulp.task('browserify-vendor', function () { return browserify() .require(dependencies) .bundle() .pipe(source('vendor.bundle.js')) .pipe(buffer()) .pipe(gulpif(production, uglify({mangle: false}))) .pipe(gulp.dest('public/scripts')); }); /* |-------------------------------------------------------------------------- | Compile only project files, excluding all third-party dependencies. |-------------------------------------------------------------------------- */ gulp.task('browserify', ['browserify-vendor'], function () { return browserify({entries: 'source/client/main.js', debug: true}) .external(dependencies) .transform(babelify, {presets: ['es2015', 'react']}) .bundle() .pipe(source('bundle.js')) .pipe(buffer()) .pipe(sourcemaps.init({loadMaps: true})) .pipe(gulpif(production, uglify({mangle: false}))) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('public/scripts')); }); /* |-------------------------------------------------------------------------- | Same as browserify task, but will also watch for changes and re-compile. |-------------------------------------------------------------------------- */ gulp.task('browserify-watch', ['browserify-vendor'], function () { let bundler = watchify(browserify({entries: 'source/client/main.js', debug: true}, watchify.args)); bundler.external(dependencies); bundler.transform(babelify, {presets: ['es2015', 'react']}); bundler.on('update', rebundle); return rebundle(); function rebundle() { let start = Date.now(); return bundler.bundle() .on('error', function (err) { gutil.log(gutil.colors.red(err.toString())); }) .on('end', function () { gutil.log(gutil.colors.green('Finished rebundling in', (Date.now() - start) + 'ms.')); }) .pipe(source('bundle.js')) .pipe(buffer()) .pipe(sourcemaps.init({loadMaps: true})) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('public/scripts/')); } }); /* |-------------------------------------------------------------------------- | Compile LESS styles. |-------------------------------------------------------------------------- */ gulp.task('styles', function () { return gulp.src('source/client/styles/main.less') .pipe(plumber()) .pipe(less()) .pipe(autoprefixer()) .pipe(gulpif(production, cssmin())) .pipe(gulp.dest('public/styles')); }); gulp.task('watch', function () { gulp.watch('source/client/styles/**/*.less', ['styles']); }); gulp.task('default', ['styles', 'vendor', 'browserify-watch', 'watch']); gulp.task('build', ['styles', 'vendor', 'browserify']);
ui/browser.js
davidbarratt/help
import React from 'react'; import Router from 'react-router/BrowserRouter'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import App from './components/app.js'; import help from './reducers/index.js'; import CustomerNormalizer from './normalizers/customer.js'; let initialState; let element = document.getElementById('state'); if (element) { try { initialState = JSON.parse(element.innerText); let normalizer = new CustomerNormalizer(); initialState.customer.list = initialState.customer.list.map((item) => { return normalizer.normalize(item); }); initialState.customer.draft = normalizer.normalize(initialState.customer.draft); } catch (e) { console.log(e); } } let store = createStore(help, initialState, applyMiddleware(thunk)); render( <Provider store={store}> <Router> <App /> </Router> </Provider>, document.getElementsByTagName('help-app')[0] );
src/svg-icons/action/settings-voice.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsVoice = (props) => ( <SvgIcon {...props}> <path d="M7 24h2v-2H7v2zm5-11c1.66 0 2.99-1.34 2.99-3L15 4c0-1.66-1.34-3-3-3S9 2.34 9 4v6c0 1.66 1.34 3 3 3zm-1 11h2v-2h-2v2zm4 0h2v-2h-2v2zm4-14h-1.7c0 3-2.54 5.1-5.3 5.1S6.7 13 6.7 10H5c0 3.41 2.72 6.23 6 6.72V20h2v-3.28c3.28-.49 6-3.31 6-6.72z"/> </SvgIcon> ); ActionSettingsVoice = pure(ActionSettingsVoice); ActionSettingsVoice.displayName = 'ActionSettingsVoice'; ActionSettingsVoice.muiName = 'SvgIcon'; export default ActionSettingsVoice;
src/renderers/dom/client/syntheticEvents/__tests__/SyntheticEvent-test.js
wjb12/react
/** * 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. * * @emails react-core */ 'use strict'; var SyntheticEvent; describe('SyntheticEvent', function() { var createEvent; beforeEach(function() { SyntheticEvent = require('SyntheticEvent'); createEvent = function(nativeEvent) { var target = require('getEventTarget')(nativeEvent); return SyntheticEvent.getPooled({}, '', nativeEvent, target); }; }); it('should normalize `target` from the nativeEvent', function() { var target = document.createElement('div'); var syntheticEvent = createEvent({srcElement: target}); expect(syntheticEvent.target).toBe(target); expect(syntheticEvent.type).toBe(undefined); }); it('should be able to `preventDefault`', function() { var nativeEvent = {}; var syntheticEvent = createEvent(nativeEvent); expect(syntheticEvent.isDefaultPrevented()).toBe(false); syntheticEvent.preventDefault(); expect(syntheticEvent.isDefaultPrevented()).toBe(true); expect(syntheticEvent.defaultPrevented).toBe(true); expect(nativeEvent.returnValue).toBe(false); }); it('should be prevented if nativeEvent is prevented', function() { expect( createEvent({defaultPrevented: true}).isDefaultPrevented() ).toBe(true); expect(createEvent({returnValue: false}).isDefaultPrevented()).toBe(true); }); it('should be able to `stopPropagation`', function() { var nativeEvent = {}; var syntheticEvent = createEvent(nativeEvent); expect(syntheticEvent.isPropagationStopped()).toBe(false); syntheticEvent.stopPropagation(); expect(syntheticEvent.isPropagationStopped()).toBe(true); expect(nativeEvent.cancelBubble).toBe(true); }); it('should be able to `persist`', function() { var syntheticEvent = createEvent({}); expect(syntheticEvent.isPersistent()).toBe(false); syntheticEvent.persist(); expect(syntheticEvent.isPersistent()).toBe(true); }); });
react-redux-tutorial/redux-examples/counter/test/components/Counter.spec.js
react-scott/react-learn
import expect from 'expect' import React from 'react' import TestUtils from 'react-addons-test-utils' import Counter from '../../components/Counter' function setup() { const actions = { increment: expect.createSpy(), incrementIfOdd: expect.createSpy(), incrementAsync: expect.createSpy(), decrement: expect.createSpy() } const component = TestUtils.renderIntoDocument(<Counter counter={1} {...actions} />) return { component: component, actions: actions, buttons: TestUtils.scryRenderedDOMComponentsWithTag(component, 'button'), p: TestUtils.findRenderedDOMComponentWithTag(component, 'p') } } describe('Counter component', () => { it('should display count', () => { const { p } = setup() expect(p.textContent).toMatch(/^Clicked: 1 times/) }) it('first button should call increment', () => { const { buttons, actions } = setup() TestUtils.Simulate.click(buttons[0]) expect(actions.increment).toHaveBeenCalled() }) it('second button should call decrement', () => { const { buttons, actions } = setup() TestUtils.Simulate.click(buttons[1]) expect(actions.decrement).toHaveBeenCalled() }) it('third button should call incrementIfOdd', () => { const { buttons, actions } = setup() TestUtils.Simulate.click(buttons[2]) expect(actions.incrementIfOdd).toHaveBeenCalled() }) it('fourth button should call incrementAsync', () => { const { buttons, actions } = setup() TestUtils.Simulate.click(buttons[3]) expect(actions.incrementAsync).toHaveBeenCalled() }) })
CoreCRM/ClientApp/src/components/Layout/Menu.js
holmescn/CoreCRM
import React from 'react'; import PropTypes from 'prop-types'; import { Menu, Icon } from 'antd'; import { Link } from 'dva/router'; const Menus = ({ siderFold, darkTheme, location, handleClickNavMenu, navOpenKeys, changeOpenKeys, menu }) => { const selectedKeys = []; const getMenus = (menuTree) => { function recursive(item, parentRoute) { if (item.children) { return ( <Menu.SubMenu key={item.id} title={<span> {item.icon && <Icon type={item.icon} />} {item.name} </span>} > {item.children.map(child => recursive(child, item.route))} </Menu.SubMenu> ); } else { const re = new RegExp(`^${location.pathname}`); if (re.test(item.route)) { selectedKeys.push(JSON.stringify(item.id)); } return ( <Menu.Item key={item.id} > <Link to={parentRoute ? parentRoute + item.route : item.route}> {item.icon && <Icon type={item.icon} />} {item.name} </Link> </Menu.Item> ); } } return recursive(menuTree); }; const menuItems = getMenus(menu); const menuProps = Object.assign({ selectedKeys, mode: (siderFold ? 'vertical' : 'inline'), theme: (darkTheme ? 'dark' : 'light'), }, siderFold ? {} : { openKeys: navOpenKeys, onOpenChange: changeOpenKeys, }); return ( <Menu {...menuProps} onClick={handleClickNavMenu} > {menuItems} </Menu> ); }; Menus.propTypes = { menu: PropTypes.object, siderFold: PropTypes.bool, darkTheme: PropTypes.bool, location: PropTypes.object, handleClickNavMenu: PropTypes.func, navOpenKeys: PropTypes.array, changeOpenKeys: PropTypes.func, }; export default Menus;
app/javascript/plugins/email_pension/EmailRepresentativeView.js
SumOfUs/Champaign
import React, { Component } from 'react'; import { isEmpty, find, template, merge, each, pick } from 'lodash'; import Input from '../../components/SweetInput/SweetInput'; import Button from '../../components/Button/Button'; import FormGroup from '../../components/Form/FormGroup'; import EmailEditor from '../../components/EmailEditor/EmailEditor'; import SelectTarget from './SelectTarget'; import SelectCountry from '../../components/SelectCountry/SelectCountry'; import { FormattedMessage, injectIntl } from 'react-intl'; import './EmailPensionView.scss'; class EmailRepresentativeView extends Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.defaultTemplateVars = { targets_names: this.props.intl.formatMessage({ id: 'email_tool.template_defaults.target_full_name', }), constituency: this.props.intl.formatMessage({ id: 'email_tool.template_defaults.constituency_name', }), name: this.props.intl.formatMessage({ id: 'email_tool.template_defaults.name', }), }; this.state = { errors: {}, targets: [], name: '', email: '', subject: '', country: '', target_name: '', target_email: '', ...props, }; } validateForm() { const errors = {}; const fields = ['country', 'subject', 'name', 'email', 'targets']; fields.forEach(field => { if (isEmpty(this.state[field])) { const location = `email_tool.form.errors.${field}`; const message = <FormattedMessage id={location} />; errors[field] = message; } }); this.setState({ errors: errors }); return isEmpty(errors); } templateVars() { let vars = pick(this.state, ['name', 'email', 'constituency']); if (this.state.targets) { vars.targets_names = this.state.targets .map( target => `${target.title} ${target.first_name} ${target.last_name}` ) .join(', '); } each(this.defaultTemplateVars, (val, key) => { if (vars[key] === undefined || vars[key] === '') { vars[key] = val; } }); return vars; } onEmailEditorUpdate = ({ subject, body }) => { this.setState(state => ({ ...state, body, subject })); }; errorNotice = () => { if (!isEmpty(this.state.errors)) { return ( <span className="error-msg left-align"> <FormattedMessage id="email_tool.form.errors.message" /> </span> ); } }; onSubmission = e => { e.preventDefault(); const valid = this.validateForm(); if (!valid) return; const payload = { body: this.state.body, country: this.state.country, subject: this.state.subject, from_name: this.state.name, from_email: this.state.email, postcode: this.state.postcode.trim(), plugin_id: this.props.pluginId, }; merge(payload, this.props.formValues); this.setState({ isSubmitting: true }); // FIXME Handle errors $.post(`/api/pages/${this.props.pageId}/pension_emails`, payload).fail( e => { console.log('Unable to send email', e); } ); }; handleTargetSelection(data) { this.setState({ constituency: data.targets[0].constituency, targets: data.targets, postcode: data.postcode, }); } handleChange(data) { this.setState(data); } render() { return ( <div className="email-target"> <div className="email-target-form"> <form onSubmit={e => e.preventDefault()} className="action-form form--big" > <FormGroup> <SelectCountry value={this.state.country} name="country" label={ <FormattedMessage id="email_tool.form.select_country" defaultMessage="Select country (default)" /> } className="form-control" errorMessage={this.state.errors.country} onChange={value => { this.handleChange({ country: value }); }} /> </FormGroup> <SelectTarget handler={this.handleTargetSelection.bind(this)} endpoint={this.props.targetEndpoint} error={this.state.errors.targets} /> <div className="email-target-action"> <h3> <FormattedMessage id="email_tool.section.compose" defaultMessage="Compose Your Email" /> </h3> <FormGroup> <Input name="name" label={ <FormattedMessage id="email_tool.form.your_name" defaultMessage="Your name (default)" /> } value={this.state.name} errorMessage={this.state.errors.name} onChange={value => { this.handleChange({ name: value }); }} /> </FormGroup> <FormGroup> <Input name="email" type="email" label={ <FormattedMessage id="email_tool.form.your_email" defaultMessage="Your email (default)" /> } value={this.state.email} errorMessage={this.state.errors.email} onChange={value => { this.handleChange({ email: value }); }} /> </FormGroup> <EmailEditor errors={this.state.errors} body={this.props.emailBody} header={this.props.emailHeader} footer={this.props.emailFooter} subject={this.props.emailSubject} templateVars={this.templateVars()} onUpdate={this.onEmailEditorUpdate} /> </div> <div className="form__group"> <Button onClick={this.onSubmission} disabled={this.state.isSubmitting} type="button" className="button action-form__submit-button" > <FormattedMessage id="email_tool.form.send_email" defaultMessage="Send email (default)" /> </Button> {this.errorNotice()} </div> </form> </div> </div> ); } } export default injectIntl(EmailRepresentativeView);
examples/cropper/jquery.js
fengshao0907/webuploader
/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license */(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&&gt(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) }b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
node_modules/react-icons/io/bug.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const IoBug = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m26.8 9.9c-0.5 1.3-1.3 2.4-2.2 3.4-1.9 1.9-4.4 2.9-7.1 2.9s-5.2-1-7.1-2.9c-0.9-1-1.7-2.1-2.2-3.4 2.3-3 5.6-4.9 9.3-4.9s7 1.9 9.3 4.9z m-19.4 1.3c1.7 3.5 5.3 6 9.5 6.2v17.6c-3.1-0.2-6-1.7-8.1-4.2-0.6 0.5-0.8 0.7-1.1 1.2 0.7 0.7 0.6 1.7 0 2.4-0.7 0.8-1.9 0.8-2.7 0.1s-0.9-1.8-0.2-2.6l0.3-0.3 0.1 0c0.3-1.1 1.1-2 2.1-2.8-1.1-2.1-2-4.5-2.2-7.1-0.6 0-1 0.2-1.4 0.3 0 1-0.8 1.8-1.8 1.8s-1.9-0.9-1.9-1.9 0.9-1.9 1.9-1.9h0.2c0.3-0.2 0.6-0.4 0.9-0.5 0.6-0.1 1.1-0.3 2-0.3 0.1-1.8 0.5-3.5 1-5.1-0.5-0.3-0.8-0.5-1.2-0.8-0.4-0.4-0.8-1-1.1-1.5 0 0-0.2-0.1-0.3-0.2-0.9-0.4-1.1-1.6-0.7-2.5s1.7-1.2 2.6-0.7c0.9 0.4 1.2 1.5 0.8 2.4 0.1 0.2 0.2 0.5 0.3 0.6 0.2 0.2 0.4 0.2 0.6 0.4 0.2-0.2 0.3-0.4 0.4-0.6z m25.7 8.8c1 0 1.9 0.9 1.9 1.9s-0.9 1.9-1.9 1.9-1.8-0.8-1.8-1.8c-0.4-0.1-0.8-0.3-1.4-0.3-0.2 2.6-1.1 5-2.2 7 1.1 0.9 1.8 1.8 2.1 2.9 0 0 0 0 0.1 0l0.3 0.3c0.7 0.8 0.6 1.9-0.2 2.6s-2 0.7-2.7-0.1c-0.6-0.7-0.7-1.7 0-2.4-0.3-0.5-0.5-0.7-1.1-1.2-2.1 2.5-5 4-8.1 4.2v-17.6c4.2-0.2 7.8-2.7 9.5-6.2 0.1 0.2 0.2 0.4 0.4 0.6 0.2-0.2 0.4-0.2 0.6-0.4 0.1-0.1 0.1-0.4 0.3-0.6-0.4-0.9-0.1-2 0.8-2.4 0.9-0.5 2.1-0.3 2.6 0.7s0.2 2.1-0.7 2.5c-0.1 0.1-0.3 0.2-0.4 0.2-0.2 0.5-0.6 1.1-1 1.5-0.4 0.3-0.7 0.5-1.2 0.8 0.5 1.6 0.9 3.3 1 5.1 0.9 0 1.4 0.2 1.9 0.3 0.4 0.1 0.7 0.3 1 0.5h0.2z"/></g> </Icon> ) export default IoBug
app/javascript/mastodon/features/compose/components/action_bar.js
unarist/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import DropdownMenuContainer from '../../../containers/dropdown_menu_container'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ edit_profile: { id: 'account.edit_profile', defaultMessage: 'Edit profile' }, pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned toots' }, preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' }, follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' }, favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' }, lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' }, blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' }, domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Hidden domains' }, mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' }, filters: { id: 'navigation_bar.filters', defaultMessage: 'Muted words' }, }); @injectIntl export default class ActionBar extends React.PureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, intl: PropTypes.object.isRequired, }; render () { const { intl } = this.props; let menu = []; menu.push({ text: intl.formatMessage(messages.edit_profile), href: '/settings/profile' }); menu.push({ text: intl.formatMessage(messages.preferences), href: '/settings/preferences' }); menu.push({ text: intl.formatMessage(messages.pins), to: '/pinned' }); menu.push(null); menu.push({ text: intl.formatMessage(messages.follow_requests), to: '/follow_requests' }); menu.push({ text: intl.formatMessage(messages.favourites), to: '/favourites' }); menu.push({ text: intl.formatMessage(messages.lists), to: '/lists' }); menu.push(null); menu.push({ text: intl.formatMessage(messages.mutes), to: '/mutes' }); menu.push({ text: intl.formatMessage(messages.blocks), to: '/blocks' }); menu.push({ text: intl.formatMessage(messages.domain_blocks), to: '/domain_blocks' }); menu.push({ text: intl.formatMessage(messages.filters), href: '/filters' }); return ( <div className='compose__action-bar'> <div className='compose__action-bar-dropdown'> <DropdownMenuContainer items={menu} icon='ellipsis-v' size={24} direction='right' /> </div> </div> ); } }
packages/material-ui-icons/src/LocationCity.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M15 11V5l-3-3-3 3v2H3v14h18V11h-6zm-8 8H5v-2h2v2zm0-4H5v-2h2v2zm0-4H5V9h2v2zm6 8h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V9h2v2zm0-4h-2V5h2v2zm6 12h-2v-2h2v2zm0-4h-2v-2h2v2z" /></g> , 'LocationCity');
modules/experimental/AsyncProps.js
tikotzky/react-router
import React from 'react'; function shallowEqual(a, b) { var ka = 0; var kb = 0; for (let key in a) { if (a.hasOwnProperty(key) && a[key] !== b[key]) return false; ka++; } for (let key in b) if (b.hasOwnProperty(key)) kb++; return ka === kb; } var AsyncProps = React.createClass({ statics: { createElement (Component, state) { return Component.loadProps ? <AsyncProps Component={Component} routing={state}/> : <Component {...state}/>; } }, getInitialState() { return { propsAreLoading: false, propsAreLoadingLong: false, asyncProps: null, previousRoutingState: null }; }, componentDidMount() { this.load(this.props); }, componentWillReceiveProps(nextProps) { var needToLoad = !shallowEqual( nextProps.routing.routeParams, this.props.routing.routeParams ); if (needToLoad) { var routerTransitioned = nextProps.routing.location !== this.props.routing.location; var keepPreviousRoutingState = this.state.propsAreLoadingLong && routerTransitioned; if (keepPreviousRoutingState) { this.load(nextProps); } else { this.setState({ previousRoutingState: this.props.routing }, () => this.load(nextProps)); } } }, /* * Could make this method much better, right now AsyncProps doesn't render its * children until it fetches data, causing a "waterfall" effect, when instead * it could look at the branch of components from it down to the end and load * up the props for all of them in parallel, waterfall will do for now... */ load(props) { var lastLoadTime = this._lastLoadTime = Date.now(); var { params } = props.routing; var { Component } = this.props; this.setState({ propsAreLoading: true }, () => { var longLoadTimer = setTimeout(() => { this.setState({ propsAreLoadingLong: true }); }, 300); // TODO: handle `error`s Component.loadProps(params, (error, asyncProps) => { clearTimeout(longLoadTimer); // if the router transitions between now and when the callback runs we will // ignore it to prevent setting state w/ the wrong data (earlier calls to // load that call back later than later calls to load) if (this._lastLoadTime !== lastLoadTime || !this.isMounted()) return; this.setState({ propsAreLoading: false, propsAreLoadingLong: false, asyncProps: asyncProps, previousRoutingState: null }); }); }); }, render() { var { Component } = this.props; var { asyncProps, propsAreLoading, propsAreLoadingLong } = this.state; var routing = this.state.previousRoutingState || this.props.routing; if (this.state.asyncProps === null) return Component.Loader ? <Component.Loader {...routing}/> : null; return <Component onPropsDidChange={() => this.load(this.props) } propsAreLoading={propsAreLoading} propsAreLoadingLong={propsAreLoadingLong} {...routing} {...asyncProps} />; } }); export default AsyncProps;
examples/src/components/Contributors.js
VanCoding/react-select
import React from 'react'; import Select from 'react-select'; const CONTRIBUTORS = require('../data/contributors'); const MAX_CONTRIBUTORS = 6; const ASYNC_DELAY = 500; const Contributors = React.createClass({ displayName: 'Contributors', propTypes: { label: React.PropTypes.string, }, getInitialState () { return { multi: true, value: [CONTRIBUTORS[0]], }; }, onChange (value) { this.setState({ value: value, }); }, switchToMulti () { this.setState({ multi: true, value: [this.state.value], }); }, switchToSingle () { this.setState({ multi: false, value: this.state.value[0], }); }, getContributors (input, callback) { input = input.toLowerCase(); var options = CONTRIBUTORS.filter(i => { return i.github.substr(0, input.length) === input; }); var data = { options: options.slice(0, MAX_CONTRIBUTORS), complete: options.length <= MAX_CONTRIBUTORS, }; setTimeout(function() { callback(null, data); }, ASYNC_DELAY); }, gotoContributor (value, event) { window.open('https://github.com/' + value.github); }, render () { return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select.Async multi={this.state.multi} value={this.state.value} onChange={this.onChange} onValueClick={this.gotoContributor} valueKey="github" labelKey="name" loadOptions={this.getContributors} /> <div className="checkbox-list"> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={this.state.multi} onChange={this.switchToMulti}/> <span className="checkbox-label">Multiselect</span> </label> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={!this.state.multi} onChange={this.switchToSingle}/> <span className="checkbox-label">Single Value</span> </label> </div> <div className="hint">This example implements custom label and value properties, async options and opens the github profiles in a new window when values are clicked</div> </div> ); } }); module.exports = Contributors;
src/components/body/Body.js
TechyFatih/Nuzlog
import React from 'react'; import { Grid, Col, Row } from 'react-bootstrap'; import { connect } from 'react-redux'; import './Body.css'; import Journal from './journal/Journal'; import Menu from './menu/Menu'; class Body extends React.Component { render() { return ( <div id='main'> {!this.props.gameOpen && <div id='cover' />} <Grid fluid> <Row> <Col lg={6} md={5}> <Journal /> </Col> <Col lg={6} md={7}> <Menu /> </Col> </Row> </Grid> </div> ); } } const mapStateToProps = state => { return { gameOpen: state.gameOpen }; }; export default connect(mapStateToProps)(Body);
docs/src/pages/premium-themes/onepirate/SignUp.js
allanalexandre/material-ui
import withRoot from './modules/withRoot'; // --- Post bootstrap ----- import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import Grid from '@material-ui/core/Grid'; import Link from '@material-ui/core/Link'; import { Field, Form, FormSpy } from 'react-final-form'; import Typography from './modules/components/Typography'; import AppFooter from './modules/views/AppFooter'; import AppAppBar from './modules/views/AppAppBar'; import AppForm from './modules/views/AppForm'; import { email, required } from './modules/form/validation'; import RFTextField from './modules/form/RFTextField'; import FormButton from './modules/form/FormButton'; import FormFeedback from './modules/form/FormFeedback'; import compose from 'docs/src/modules/utils/compose'; const styles = theme => ({ form: { marginTop: theme.spacing(6), }, button: { marginTop: theme.spacing(3), marginBottom: theme.spacing(2), }, feedback: { marginTop: theme.spacing(2), }, }); class SignUp extends React.Component { state = { sent: false, }; validate = values => { const errors = required(['firstName', 'lastName', 'email', 'password'], values, this.props); if (!errors.email) { const emailError = email(values.email, values, this.props); if (emailError) { errors.email = email(values.email, values, this.props); } } return errors; }; handleSubmit = () => {}; render() { const { classes } = this.props; const { sent } = this.state; return ( <React.Fragment> <AppAppBar /> <AppForm> <React.Fragment> <Typography variant="h3" gutterBottom marked="center" align="center"> Sign Up </Typography> <Typography variant="body2" align="center"> <Link href="/premium-themes/onepirate/sign-in/" underline="always"> Already have an account? </Link> </Typography> </React.Fragment> <Form onSubmit={this.handleSubmit} subscription={{ submitting: true }} validate={this.validate} > {({ handleSubmit, submitting }) => ( <form onSubmit={handleSubmit} className={classes.form} noValidate> <Grid container spacing={2}> <Grid item xs={12} sm={6}> <Field autoFocus component={RFTextField} autoComplete="fname" fullWidth label="First name" name="firstName" required /> </Grid> <Grid item xs={12} sm={6}> <Field component={RFTextField} autoComplete="lname" fullWidth label="Last name" name="lastName" required /> </Grid> </Grid> <Field autoComplete="email" component={RFTextField} disabled={submitting || sent} fullWidth label="Email" margin="normal" name="email" required /> <Field fullWidth component={RFTextField} disabled={submitting || sent} required name="password" autoComplete="current-password" label="Password" type="password" margin="normal" /> <FormSpy subscription={{ submitError: true }}> {({ submitError }) => submitError ? ( <FormFeedback className={classes.feedback} error> {submitError} </FormFeedback> ) : null } </FormSpy> <FormButton className={classes.button} disabled={submitting || sent} color="secondary" fullWidth > {submitting || sent ? 'In progress…' : 'Sign Up'} </FormButton> </form> )} </Form> </AppForm> <AppFooter /> </React.Fragment> ); } } SignUp.propTypes = { classes: PropTypes.object.isRequired, }; export default compose( withRoot, withStyles(styles), )(SignUp);
CompositeUi/src/views/component/UserCard.js
kreta/kreta
/* * This file is part of the Kreta package. * * (c) Beñat Espiña <[email protected]> * (c) Gorka Laucirica <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import React from 'react'; import CardExtended from './CardExtended'; import UserThumbnail from './UserThumbnail'; class UserCard extends React.Component { static propTypes = { user: React.PropTypes.object.isRequired, }; username() { const {user} = this.props; return `@${user.user_name}`; } subtitle() { return this.title() === this.username() ? null : this.username(); } title() { const {user} = this.props; if (user.first_name && user.last_name) { return `${user.first_name} ${user.last_name}`; } return this.username(); } render() { const {user, actions} = this.props; return ( <CardExtended subtitle={this.subtitle()} thumbnail={<UserThumbnail user={user} />} title={this.title()} > {actions} </CardExtended> ); } } export default UserCard;
src/components/generics/navbar.js
bombe-software/demos
import React, { Component } from 'react'; import { Link } from "react-router-dom"; import { connect } from "react-redux"; class Navbar extends Component { constructor(props) { super(props); this.state = { isToggleOn: false, isUserSelected: false }; this.handleClick = this.handleClick.bind(this); this.renderNavEnd = this.renderNavEnd.bind(this); } handleClick() { this.setState(prevState => ({ isToggleOn: !prevState.isToggleOn })); } handleClickUser(){ this.setState(prevState => ({ isUserSelected: !prevState.isUserSelected })); } renderNavEnd(){ if(JSON.stringify(this.props.user) == '{}'){ return( <div> <div className="navbar-item"> <Link to="/login" className="navbar-item is-light" onClick={this.handleClick}> Iniciar sesión </Link> <Link to="/signup" className="navbar-item" onClick={this.handleClick}> Registro </Link > </div> </div> ); }else{ return( <div> <div className="navbar-item"> <div className="field is-grouped"> <div className="navbar-item is-light has-dropdown is-hoverable" onClick={this.handleClick}> <a className="navbar-item">@{this.props.user.nombre_usuario}</a> <div className="navbar-dropdown is-right"> <Link to="/config_cuenta" className="navbar-item">Configuración de la cuenta</Link> <a className="navbar-item" href="/">Cerrar sesión</a> </div> </div> <div className="navbar-item"> <img src={"../../assets/img/"+this.props.user.avatar+".png"} height="28" width="28"/> </div> </div> </div> </div> ); } } renderModerador(){ if(JSON.stringify(this.props.user) != '{}'){ if(this.props.user.id_tipo_usuario == '2'){ return( <Link to="/moderador" className="navbar-item"> Moderador </Link> ); } } } /** * Es una forma de capturar cualquier error en la clase * y que este no crashe el programa, ayuda con la depuracion * de errores * @method componentDidCatch * @const info Es más informacion acerca del error * @const error Es el titulo del error */ componentDidCatch(error, info) { console.log("Error: " + error); console.log("Info: " + info); } render() { return ( //Logo de la navbar <div> <nav className="navbar is-transparent"> <div className="navbar-brand"> <Link className="navbar-item" to="/"> <img src="../../assets/img/demos_logo_21.png" alt="Demos" width="112" height="28"/> </Link> <div className={this.state.isToggleOn ? 'navbar-burger burger is-active' : 'navbar-burger burger'} data-target="nav-demos-menu" onClick={this.handleClick}> <span></span> <span></span> <span></span> </div> </div> <div id="nav-demos-menu" className={this.state.isToggleOn ? 'navbar-menu is-active' : 'navbar-menu'}> <div className="navbar-start"> <div className="navbar-item"> <Link to="/elecciones" className="navbar-item" onClick={this.handleClick}> Elecciones </Link> <Link to="/politicos" className="navbar-item" onClick={this.handleClick}> Politicos </Link> <Link to="/acerca-de" className="navbar-item" onClick={this.handleClick}> Ayuda </Link> <Link to="/soporte" className="navbar-item" onClick={this.handleClick}> Soporte </Link> {this.renderModerador()} </div> </div> <div className="navbar-end"> {this.renderNavEnd()} </div> </div> </nav> </div> ); } } function mapStateToProps(state) { return { user: state.user }; } export default connect(mapStateToProps, null )(Navbar);
node_modules/react-bootstrap/es/SafeAnchor.js
Technaesthetic/ua-tools
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 React from 'react'; import elementType from 'react-prop-types/lib/elementType'; var propTypes = { href: React.PropTypes.string, onClick: React.PropTypes.func, disabled: React.PropTypes.bool, role: React.PropTypes.string, tabIndex: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * this is sort of silly but needed for Button */ componentClass: elementType }; var defaultProps = { componentClass: 'a' }; function isTrivialHref(href) { return !href || href.trim() === '#'; } /** * There are situations due to browser quirks or Bootstrap CSS where * an anchor tag is needed, when semantically a button tag is the * better choice. SafeAnchor ensures that when an anchor is used like a * button its accessible. It also emulates input `disabled` behavior for * links, which is usually desirable for Buttons, NavItems, MenuItems, etc. */ var SafeAnchor = function (_React$Component) { _inherits(SafeAnchor, _React$Component); function SafeAnchor(props, context) { _classCallCheck(this, SafeAnchor); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } SafeAnchor.prototype.handleClick = function handleClick(event) { var _props = this.props, disabled = _props.disabled, href = _props.href, onClick = _props.onClick; if (disabled || isTrivialHref(href)) { event.preventDefault(); } if (disabled) { event.stopPropagation(); return; } if (onClick) { onClick(event); } }; SafeAnchor.prototype.render = function render() { var _props2 = this.props, Component = _props2.componentClass, disabled = _props2.disabled, props = _objectWithoutProperties(_props2, ['componentClass', 'disabled']); if (isTrivialHref(props.href)) { props.role = props.role || 'button'; // we want to make sure there is a href attribute on the node // otherwise, the cursor incorrectly styled (except with role='button') props.href = props.href || '#'; } if (disabled) { props.tabIndex = -1; props.style = _extends({ pointerEvents: 'none' }, props.style); } return React.createElement(Component, _extends({}, props, { onClick: this.handleClick })); }; return SafeAnchor; }(React.Component); SafeAnchor.propTypes = propTypes; SafeAnchor.defaultProps = defaultProps; export default SafeAnchor;
frontend/src/NuevoMedico/MedicoFormView.js
GAumala/Facturacion
import React from 'react'; import ActionStore from 'material-ui/svg-icons/action/store'; import Person from 'material-ui/svg-icons/social/person'; import Phone from 'material-ui/svg-icons/communication/phone'; import Email from 'material-ui/svg-icons/communication/email'; import MonetizationOn from 'material-ui/svg-icons/editor/monetization-on'; import IconTextFieldRow from '../lib/formTable/IconTextFieldRow'; export default class MedicoFormView extends React.Component { render() { const { errors, inputs, updateData } = this.props; const telf1Input = { hintText: 'Teléfono 1', icon: Phone, value: inputs.telefono1 || '', errorText: errors.telefono1, onChange: event => { updateData('telefono1', event.target.value); } }; const medicoInput = { hintText: 'Medico', icon: Person, value: inputs.nombre || '', errorText: errors.nombre, onChange: event => { updateData('nombre', event.target.value); } }; const telf2Input = { hintText: 'Teléfono 2', icon: Phone, value: inputs.telefono2 || '', errorText: errors.telefono2, onChange: event => { updateData('telefono2', event.target.value); } }; const direccionInput = { hintText: 'Dirección', icon: ActionStore, value: inputs.direccion || '', errorText: errors.direccion, onChange: event => { updateData('direccion', event.target.value); } }; const emailInput = { hintText: 'E-mail', icon: Email, value: inputs.email || '', errorText: errors.email, onChange: event => { updateData('email', event.target.value); } }; const comisionInput = { hintText: 'Comision', icon: MonetizationOn, value: inputs.comision || '', errorText: errors.comision, onChange: event => { updateData('comision', event.target.value); } }; return ( <table> <tbody> <IconTextFieldRow leftInput={medicoInput} rightInput={direccionInput} /> <IconTextFieldRow leftInput={comisionInput} rightInput={emailInput} /> <IconTextFieldRow leftInput={telf1Input} rightInput={telf2Input} /> </tbody> </table> ); } }
src/index.js
benwiley4000/react-gif-player
import React from 'react'; import PropTypes from 'prop-types'; import lifecyclesPoylfill from 'react-lifecycles-compat'; import GifPlayer from './GifPlayer'; const preload = (src, callback) => { var img = new Image(); if (typeof callback === 'function') { img.onload = () => callback(img); img.setAttribute('crossOrigin', 'anonymous'); } img.src = src; }; const firstGifFrameUrl = img => { const canvas = document.createElement('canvas'); if (typeof canvas.getContext !== 'function') { return null; } canvas.width = img.width; canvas.height = img.height; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); return canvas.toDataURL(); } class GifPlayerContainer extends React.Component { static getDerivedStateFromProps (nextProps, prevState) { const prevGif = prevState.providedGif; const nextGif = nextProps.gif; const prevStill = prevState.providedStill; const nextStill = nextProps.still; if (prevGif === nextGif && prevStill === nextStill) { return null; } return { playing: nextGif && nextProps.autoplay && prevGif !== nextGif ? true : prevState.playing, providedGif: nextGif, providedStill: nextStill, actualGif: nextGif, actualStill: nextStill || prevGif !== nextGif ? nextStill : prevState.actualStill }; } constructor (props) { super(props); this.state = { playing: Boolean(props.autoplay), providedGif: props.gif, providedStill: props.still, actualGif: props.gif, actualStill: props.still }; this.updateId = -1; } componentDidMount () { if (typeof this.props.pauseRef === 'function') { this.props.pauseRef(() => this.setState({ playing: false })); } this.updateImages(); } componentDidUpdate (prevProps, prevState) { this.updateImages(prevState); const { onTogglePlay } = this.props; if (prevState.playing !== this.state.playing && typeof onTogglePlay === 'function') { onTogglePlay(this.state.playing); } } updateImages (prevState = {}) { const { providedGif, providedStill } = this.state; if ( providedGif && !providedStill && providedGif !== prevState.providedGif ) { const updateId = ++this.updateId; preload(providedGif, img => { if (this.updateId === updateId) { const actualStill = firstGifFrameUrl(img); if (actualStill) { this.setState({ actualStill }); } } }); } } toggle () { this.setState({ playing: !this.state.playing }); } render () { // extract these props but pass down the rest const { autoplay, pauseRef, onTogglePlay, ...rest } = this.props; const { actualGif, actualStill, playing } = this.state; return ( <GifPlayer {...rest} gif={actualGif} still={actualStill} playing={playing} toggle={() => this.toggle()} /> ); } } lifecyclesPoylfill(GifPlayerContainer); GifPlayerContainer.propTypes = { gif: PropTypes.string, still: PropTypes.string, autoplay: PropTypes.bool, pauseRef: PropTypes.func, onTogglePlay: PropTypes.func }; export default GifPlayerContainer;
ajax/libs/react-quill/0.0.1/react-quill.min.js
tholu/cdnjs
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("quilljs")):"function"==typeof define&&define.amd?define(["react","quilljs"],t):"object"==typeof exports?exports.ReactQuill=t(require("react"),require("quilljs")):e.ReactQuill=t(e.React,e.Quill)}(this,function(e,t){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){e.exports=r(4),e.exports.Mixin=r(2),e.exports.Toolbar=r(3)},function(t){t.exports=e},function(e,t,r){"use strict";var n=r(1),o=r(5),i=(n.PropTypes,{createEditor:function(e,t){var r=new o(e,t);return this.hookEditor(r),r},hookEditor:function(e){var t=this;e.on("text-change",function(r,n){t.onEditorChange&&t.onEditorChange(e.getHTML(),r,n)})},updateEditor:function(){throw new Error("Not implemented")},destroyEditor:function(e){e.removeAllListeners()},setEditorContents:function(e,t){var r=e.getSelection();e.setHTML(t),e.setSelection(r)}});e.exports=i},function(e,t,r){"use strict";var n=r(1),o=n.PropTypes,i=[{label:"Formats",type:"group",items:[{label:"Size",type:"size",items:[{label:"Normal",value:""},{label:"Smaller",value:"0.8em"},{label:"Larger",value:"1.4em"},{label:"Huge",value:"2em"}]},{label:"Alignment",type:"align",items:[{label:"Center",value:"center"},{label:"Left",value:"left"},{label:"Right",value:"right"},{label:"Justify",value:"justify"}]}]},{label:"Text",type:"group",items:[{type:"bold",label:"Bold"},{type:"italic",label:"Italic"},{type:"strike",label:"Strike"},{type:"underline",label:"Underline"},{type:"link",label:"Link"}]},{label:"Blocks",type:"group",items:[{type:"bullet",label:"Bullet"},{type:"list",label:"List"}]}],l=n.createClass({displayName:"Quill Toolbar",propTypes:{id:o.string,className:o.string,items:o.array},getDefaultProps:function(){return{items:i}},renderGroup:function(e){return n.DOM.span({key:e.label,className:"ql-format-group"},e.items.map(this.renderItem))},renderChoiceItem:function(e){return n.DOM.option({key:e.label||e.value,value:e.value},e.label)},renderChoices:function(e){return n.DOM.select({key:e.label,className:"ql-"+e.type},e.items.map(this.renderChoiceItem))},renderAction:function(e){return n.DOM.span({key:e.label||e.value,className:"ql-format-button ql-"+e.type,title:e.label})},renderItem:function(e){var t={group:this.renderGroup,align:this.renderChoices,size:this.renderChoices,action:this.renderAction},r=t[e.type]||t.action;return r(e)},getClassName:function(){return"quill-toolbar "+(this.props.className||"")},render:function(){return n.DOM.div({className:this.getClassName()},this.props.items.map(this.renderItem))}});e.exports=l},function(e,t,r){"use strict";var n=r(1),o=r(3),i=r(2),l=n.PropTypes,s=n.createClass({displayName:"Quill",mixins:[i],propTypes:{id:l.string,className:l.string,value:l.string,defaultValue:l.string,readOnly:l.bool,toolbar:l.object,formats:l.array,styles:l.object,theme:l.string,pollInterval:l.number,onChange:l.func},getDefaultProps:function(){return{className:"",modules:{}}},getInitialState:function(){return{}},componentWillReceiveProps:function(e){"value"in e&&e.value!==this.props.value&&this.setEditorContents(this.state.editor,e.value)},componentDidMount:function(){var e=this.createEditor(this.getEditorElement(),this.getEditorConfig());this.setState({editor:e})},componentWillUnmount:function(){this.destroyEditor(this.state.editor)},shouldComponentUpdate:function(){return!1},componentWillUpdate:function(){this.componentWillUnmount()},componentDidUpdate:function(){this.componentDidMount()},getEditorConfig:function(){var e={readOnly:this.props.readOnly,theme:this.props.theme,formats:this.props.formats,styles:this.props.styles,modules:this.props.modules,pollInterval:this.props.pollInterval};return e.modules.toolbar||(e.modules=JSON.parse(JSON.stringify(e.modules)),e.modules.toolbar={container:this.refs.toolbar.getDOMNode()}),e},getEditorElement:function(){return this.refs.editor.getDOMNode()},getEditorContents:function(){return this.props.value||this.props.defaultValue},getClassName:function(){return["quill",this.props.className].join(" ")},renderContents:function(){return n.Children.count(this.props.children)>0?n.Children.only(this.props.children):[o({items:this.props.toolbar,ref:"toolbar"}),n.DOM.div({className:"quill-contents",ref:"editor",dangerouslySetInnerHTML:{__html:this.getEditorContents()}})]},render:function(){return n.DOM.div({className:this.getClassName(),onChange:this.preventDefault},this.renderContents())},onEditorChange:function(e){e!==this.state.value&&this.props.onChange&&this.props.onChange(e)},preventDefault:function(e){e.preventDefault(),e.stopPropagation()}});e.exports=s},function(e){e.exports=t}])});
src/svg-icons/av/fast-rewind.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvFastRewind = (props) => ( <SvgIcon {...props}> <path d="M11 18V6l-8.5 6 8.5 6zm.5-6l8.5 6V6l-8.5 6z"/> </SvgIcon> ); AvFastRewind = pure(AvFastRewind); AvFastRewind.displayName = 'AvFastRewind'; AvFastRewind.muiName = 'SvgIcon'; export default AvFastRewind;
web/src/components/FacebookLogout.js
fmiglianico/HaveYouMet
import React, { Component } from 'react'; import store from '../stores/Store'; import FacebookActionCreators from '../actions/FacebookActionCreator'; class FacebookLogout extends Component { render() { return ( <a href="#" onClick={this.didClickFacebookLogoutButton}>Log Out</a> ); } didClickFacebookLogoutButton() { store.dispatch(FacebookActionCreators.logout()); } } export default FacebookLogout;
trim-interview-26092019/src/components/navBar.js
balaSpyrus/wave11
import React from 'react'; import { Link } from 'react-router-dom'; class NavBar extends React.Component { constructor(props) { super(props); this.state = { }; } render() { return ( <nav className="navbar navbar-expand-lg navbar-light bg-light"> <Link to='/'>App</Link> <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse" id="navbarText"> <ul className="navbar-nav mr-auto"> </ul> <span className="navbar-text"> <Link to='/createUser'>Create User</Link> </span> </div> </nav> ); } } export default NavBar;
src/containers/Manifesto.js
pjkarlik/ReactUI
import React from 'react'; const Manifesto = () => { const content = ( <span> <h2>Interface Research and Design</h2> <p> Sed quis mattis turpis. Ut vitae finibus sem. Donec scelerisque nec nisi non malesuada. Praesent mattis lacus quis diam imperdiet rhoncus. Ut porta efficitur magna, quis pretium magna. Nam venenatis convallis finibus. Nunc non mi tincidunt, luctus purus tempus. <br/><br/> Vitae dignissim ante est vel erat. Maecenas auctor dolor vitae egestas aliquam. <br/><br/> Morbi sed arcu vitae ligula porta gravida. Integer vel ex neque. Etiam quis elementum magna. Duis nec tincidunt enim. </p> </span> ); return content; }; Manifesto.displayName = 'Manifesto'; export default Manifesto;
app/javascript/mastodon/components/__tests__/avatar-test.js
res-ac/mstdn.res.ac
import React from 'react'; import renderer from 'react-test-renderer'; import { fromJS } from 'immutable'; import Avatar from '../avatar'; describe('<Avatar />', () => { const account = fromJS({ username: 'alice', acct: 'alice', display_name: 'Alice', avatar: '/animated/alice.gif', avatar_static: '/static/alice.jpg', }); const size = 100; describe('Autoplay', () => { it('renders a animated avatar', () => { const component = renderer.create(<Avatar account={account} animate size={size} />); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); }); describe('Still', () => { it('renders a still avatar', () => { const component = renderer.create(<Avatar account={account} size={size} />); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); }); // TODO add autoplay test if possible });
node_modules/react-router/lib/IndexRoute.js
FrancoCotter/ReactWeatherApp
'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _routerWarning = require('./routerWarning'); var _routerWarning2 = _interopRequireDefault(_routerWarning); var _invariant = require('invariant'); var _invariant2 = _interopRequireDefault(_invariant); var _RouteUtils = require('./RouteUtils'); var _PropTypes = require('./PropTypes'); var func = _react2['default'].PropTypes.func; /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ var IndexRoute = _react2['default'].createClass({ displayName: 'IndexRoute', statics: { createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = _RouteUtils.createRouteFromReactElement(element); } else { process.env.NODE_ENV !== 'production' ? _routerWarning2['default'](false, 'An <IndexRoute> does not make sense at the root of your route config') : undefined; } } }, propTypes: { path: _PropTypes.falsy, component: _PropTypes.component, components: _PropTypes.components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? _invariant2['default'](false, '<IndexRoute> elements are for router configuration only and should not be rendered') : _invariant2['default'](false) : undefined; } }); exports['default'] = IndexRoute; module.exports = exports['default'];
src/index.js
eldavojohn/myRetail-practice-app
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import configureStore from './stores/ConfigureProductStore' import ProductContainer from './product/ProductContainer' import '../public/index.css' import 'babel-polyfill' const store = configureStore() ReactDOM.render( <Provider store={store}> <ProductContainer /> </Provider>, document.getElementById('root') )
public/js/jquery/1.5.2/jquery.min.js
intxx0/messages
/*! * jQuery JavaScript Library v1.5.2 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu Mar 31 15:28:23 2011 -0400 */ (function(a,b){function ci(a){return d.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cf(a){if(!b_[a]){var b=d("<"+a+">").appendTo("body"),c=b.css("display");b.remove();if(c==="none"||c==="")c="block";b_[a]=c}return b_[a]}function ce(a,b){var c={};d.each(cd.concat.apply([],cd.slice(0,b)),function(){c[this]=a});return c}function b$(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function bZ(){try{return new a.XMLHttpRequest}catch(b){}}function bY(){d(a).unload(function(){for(var a in bW)bW[a](0,1)})}function bS(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var e=a.dataTypes,f={},g,h,i=e.length,j,k=e[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h==="string"&&(f[h.toLowerCase()]=a.converters[h]);l=k,k=e[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=f[m]||f["* "+k];if(!n){p=b;for(o in f){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=f[j[1]+" "+k];if(p){o=f[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&d.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function bR(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function bQ(a,b,c,e){if(d.isArray(b)&&b.length)d.each(b,function(b,f){c||bs.test(a)?e(a,f):bQ(a+"["+(typeof f==="object"||d.isArray(f)?b:"")+"]",f,c,e)});else if(c||b==null||typeof b!=="object")e(a,b);else if(d.isArray(b)||d.isEmptyObject(b))e(a,"");else for(var f in b)bQ(a+"["+f+"]",b[f],c,e)}function bP(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bJ,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l==="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bP(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bP(a,c,d,e,"*",g));return l}function bO(a){return function(b,c){typeof b!=="string"&&(c=b,b="*");if(d.isFunction(c)){var e=b.toLowerCase().split(bD),f=0,g=e.length,h,i,j;for(;f<g;f++)h=e[f],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bq(a,b,c){var e=b==="width"?bk:bl,f=b==="width"?a.offsetWidth:a.offsetHeight;if(c==="border")return f;d.each(e,function(){c||(f-=parseFloat(d.css(a,"padding"+this))||0),c==="margin"?f+=parseFloat(d.css(a,"margin"+this))||0:f-=parseFloat(d.css(a,"border"+this+"Width"))||0});return f}function bc(a,b){b.src?d.ajax({url:b.src,async:!1,dataType:"script"}):d.globalEval(b.text||b.textContent||b.innerHTML||""),b.parentNode&&b.parentNode.removeChild(b)}function bb(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function ba(a,b){if(b.nodeType===1){var c=b.nodeName.toLowerCase();b.clearAttributes(),b.mergeAttributes(a);if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(d.expando)}}function _(a,b){if(b.nodeType===1&&d.hasData(a)){var c=d.expando,e=d.data(a),f=d.data(b,e);if(e=e[c]){var g=e.events;f=f[c]=d.extend({},e);if(g){delete f.handle,f.events={};for(var h in g)for(var i=0,j=g[h].length;i<j;i++)d.event.add(b,h+(g[h][i].namespace?".":"")+g[h][i].namespace,g[h][i],g[h][i].data)}}}}function $(a,b){return d.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function Q(a,b,c){if(d.isFunction(b))return d.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return d.grep(a,function(a,d){return a===b===c});if(typeof b==="string"){var e=d.grep(a,function(a){return a.nodeType===1});if(L.test(b))return d.filter(b,e,!c);b=d.filter(b,e)}return d.grep(a,function(a,e){return d.inArray(a,b)>=0===c})}function P(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function H(a,b){return(a&&a!=="*"?a+".":"")+b.replace(t,"`").replace(u,"&")}function G(a){var b,c,e,f,g,h,i,j,k,l,m,n,o,p=[],q=[],s=d._data(this,"events");if(a.liveFired!==this&&s&&s.live&&!a.target.disabled&&(!a.button||a.type!=="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var t=s.live.slice(0);for(i=0;i<t.length;i++)g=t[i],g.origType.replace(r,"")===a.type?q.push(g.selector):t.splice(i--,1);f=d(a.target).closest(q,a.currentTarget);for(j=0,k=f.length;j<k;j++){m=f[j];for(i=0;i<t.length;i++){g=t[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,e=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,e=d(a.relatedTarget).closest(g.selector)[0];(!e||e!==h)&&p.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=p.length;j<k;j++){f=p[j];if(c&&f.level>c)break;a.currentTarget=f.elem,a.data=f.handleObj.data,a.handleObj=f.handleObj,o=f.handleObj.origHandler.apply(f.elem,arguments);if(o===!1||a.isPropagationStopped()){c=f.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}function E(a,c,e){var f=d.extend({},e[0]);f.type=a,f.originalEvent={},f.liveFired=b,d.event.handle.call(c,f),f.isDefaultPrevented()&&e[0].preventDefault()}function y(){return!0}function x(){return!1}function i(a){for(var b in a)if(b!=="toJSON")return!1;return!0}function h(a,c,e){if(e===b&&a.nodeType===1){e=a.getAttribute("data-"+c);if(typeof e==="string"){try{e=e==="true"?!0:e==="false"?!1:e==="null"?null:d.isNaN(e)?g.test(e)?d.parseJSON(e):e:parseFloat(e)}catch(f){}d.data(a,c,e)}else e=b}return e}var c=a.document,d=function(){function G(){if(!d.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(G,1);return}d.ready()}}var d=function(a,b){return new d.fn.init(a,b,g)},e=a.jQuery,f=a.$,g,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,i=/\S/,j=/^\s+/,k=/\s+$/,l=/\d/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=navigator.userAgent,w,x,y,z=Object.prototype.toString,A=Object.prototype.hasOwnProperty,B=Array.prototype.push,C=Array.prototype.slice,D=String.prototype.trim,E=Array.prototype.indexOf,F={};d.fn=d.prototype={constructor:d,init:function(a,e,f){var g,i,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!e&&c.body){this.context=c,this[0]=c.body,this.selector="body",this.length=1;return this}if(typeof a==="string"){g=h.exec(a);if(!g||!g[1]&&e)return!e||e.jquery?(e||f).find(a):this.constructor(e).find(a);if(g[1]){e=e instanceof d?e[0]:e,k=e?e.ownerDocument||e:c,j=m.exec(a),j?d.isPlainObject(e)?(a=[c.createElement(j[1])],d.fn.attr.call(a,e,!0)):a=[k.createElement(j[1])]:(j=d.buildFragment([g[1]],[k]),a=(j.cacheable?d.clone(j.fragment):j.fragment).childNodes);return d.merge(this,a)}i=c.getElementById(g[2]);if(i&&i.parentNode){if(i.id!==g[2])return f.find(a);this.length=1,this[0]=i}this.context=c,this.selector=a;return this}if(d.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return d.makeArray(a,this)},selector:"",jquery:"1.5.2",length:0,size:function(){return this.length},toArray:function(){return C.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var e=this.constructor();d.isArray(a)?B.apply(e,a):d.merge(e,a),e.prevObject=this,e.context=this.context,b==="find"?e.selector=this.selector+(this.selector?" ":"")+c:b&&(e.selector=this.selector+"."+b+"("+c+")");return e},each:function(a,b){return d.each(this,a,b)},ready:function(a){d.bindReady(),x.done(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(C.apply(this,arguments),"slice",C.call(arguments).join(","))},map:function(a){return this.pushStack(d.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:B,sort:[].sort,splice:[].splice},d.fn.init.prototype=d.fn,d.extend=d.fn.extend=function(){var a,c,e,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i==="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!=="object"&&!d.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){e=i[c],f=a[c];if(i===f)continue;l&&f&&(d.isPlainObject(f)||(g=d.isArray(f)))?(g?(g=!1,h=e&&d.isArray(e)?e:[]):h=e&&d.isPlainObject(e)?e:{},i[c]=d.extend(l,h,f)):f!==b&&(i[c]=f)}return i},d.extend({noConflict:function(b){a.$=f,b&&(a.jQuery=e);return d},isReady:!1,readyWait:1,ready:function(a){a===!0&&d.readyWait--;if(!d.readyWait||a!==!0&&!d.isReady){if(!c.body)return setTimeout(d.ready,1);d.isReady=!0;if(a!==!0&&--d.readyWait>0)return;x.resolveWith(c,[d]),d.fn.trigger&&d(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!x){x=d._Deferred();if(c.readyState==="complete")return setTimeout(d.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",y,!1),a.addEventListener("load",d.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",y),a.attachEvent("onload",d.ready);var b=!1;try{b=a.frameElement==null}catch(e){}c.documentElement.doScroll&&b&&G()}}},isFunction:function(a){return d.type(a)==="function"},isArray:Array.isArray||function(a){return d.type(a)==="array"},isWindow:function(a){return a&&typeof a==="object"&&"setInterval"in a},isNaN:function(a){return a==null||!l.test(a)||isNaN(a)},type:function(a){return a==null?String(a):F[z.call(a)]||"object"},isPlainObject:function(a){if(!a||d.type(a)!=="object"||a.nodeType||d.isWindow(a))return!1;if(a.constructor&&!A.call(a,"constructor")&&!A.call(a.constructor.prototype,"isPrototypeOf"))return!1;var c;for(c in a){}return c===b||A.call(a,c)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!=="string"||!b)return null;b=d.trim(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return a.JSON&&a.JSON.parse?a.JSON.parse(b):(new Function("return "+b))();d.error("Invalid JSON: "+b)},parseXML:function(b,c,e){a.DOMParser?(e=new DOMParser,c=e.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b)),e=c.documentElement,(!e||!e.nodeName||e.nodeName==="parsererror")&&d.error("Invalid XML: "+b);return c},noop:function(){},globalEval:function(a){if(a&&i.test(a)){var b=c.head||c.getElementsByTagName("head")[0]||c.documentElement,e=c.createElement("script");d.support.scriptEval()?e.appendChild(c.createTextNode(a)):e.text=a,b.insertBefore(e,b.firstChild),b.removeChild(e)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,e){var f,g=0,h=a.length,i=h===b||d.isFunction(a);if(e){if(i){for(f in a)if(c.apply(a[f],e)===!1)break}else for(;g<h;)if(c.apply(a[g++],e)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(var j=a[0];g<h&&c.call(j,g,j)!==!1;j=a[++g]){}return a},trim:D?function(a){return a==null?"":D.call(a)}:function(a){return a==null?"":(a+"").replace(j,"").replace(k,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var e=d.type(a);a.length==null||e==="string"||e==="function"||e==="regexp"||d.isWindow(a)?B.call(c,a):d.merge(c,a)}return c},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var c=0,d=b.length;c<d;c++)if(b[c]===a)return c;return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length==="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,b,c){var d=[],e;for(var f=0,g=a.length;f<g;f++)e=b(a[f],f,c),e!=null&&(d[d.length]=e);return d.concat.apply([],d)},guid:1,proxy:function(a,c,e){arguments.length===2&&(typeof c==="string"?(e=a,a=e[c],c=b):c&&!d.isFunction(c)&&(e=c,c=b)),!c&&a&&(c=function(){return a.apply(e||this,arguments)}),a&&(c.guid=a.guid=a.guid||c.guid||d.guid++);return c},access:function(a,c,e,f,g,h){var i=a.length;if(typeof c==="object"){for(var j in c)d.access(a,j,c[j],f,g,e);return a}if(e!==b){f=!h&&f&&d.isFunction(e);for(var k=0;k<i;k++)g(a[k],c,f?e.call(a[k],k,g(a[k],c)):e,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}d.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.subclass=this.subclass,a.fn.init=function b(b,c){c&&c instanceof d&&!(c instanceof a)&&(c=a(c));return d.fn.init.call(this,b,c,e)},a.fn.init.prototype=a.fn;var e=a(c);return a},browser:{}}),d.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){F["[object "+b+"]"]=b.toLowerCase()}),w=d.uaMatch(v),w.browser&&(d.browser[w.browser]=!0,d.browser.version=w.version),d.browser.webkit&&(d.browser.safari=!0),E&&(d.inArray=function(a,b){return E.call(b,a)}),i.test(" ")&&(j=/^[\s\xA0]+/,k=/[\s\xA0]+$/),g=d(c),c.addEventListener?y=function(){c.removeEventListener("DOMContentLoaded",y,!1),d.ready()}:c.attachEvent&&(y=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",y),d.ready())});return d}(),e="then done fail isResolved isRejected promise".split(" "),f=[].slice;d.extend({_Deferred:function(){var a=[],b,c,e,f={done:function(){if(!e){var c=arguments,g,h,i,j,k;b&&(k=b,b=0);for(g=0,h=c.length;g<h;g++)i=c[g],j=d.type(i),j==="array"?f.done.apply(f,i):j==="function"&&a.push(i);k&&f.resolveWith(k[0],k[1])}return this},resolveWith:function(d,f){if(!e&&!b&&!c){f=f||[],c=1;try{while(a[0])a.shift().apply(d,f)}finally{b=[d,f],c=0}}return this},resolve:function(){f.resolveWith(this,arguments);return this},isResolved:function(){return c||b},cancel:function(){e=1,a=[];return this}};return f},Deferred:function(a){var b=d._Deferred(),c=d._Deferred(),f;d.extend(b,{then:function(a,c){b.done(a).fail(c);return this},fail:c.done,rejectWith:c.resolveWith,reject:c.resolve,isRejected:c.isResolved,promise:function(a){if(a==null){if(f)return f;f=a={}}var c=e.length;while(c--)a[e[c]]=b[e[c]];return a}}),b.done(c.cancel).fail(b.cancel),delete b.cancel,a&&a.call(b,b);return b},when:function(a){function i(a){return function(c){b[a]=arguments.length>1?f.call(arguments,0):c,--g||h.resolveWith(h,f.call(b,0))}}var b=arguments,c=0,e=b.length,g=e,h=e<=1&&a&&d.isFunction(a.promise)?a:d.Deferred();if(e>1){for(;c<e;c++)b[c]&&d.isFunction(b[c].promise)?b[c].promise().then(i(c),h.reject):--g;g||h.resolveWith(h,b)}else h!==a&&h.resolveWith(h,e?[a]:[]);return h.promise()}}),function(){d.support={};var b=c.createElement("div");b.style.display="none",b.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var e=b.getElementsByTagName("*"),f=b.getElementsByTagName("a")[0],g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=b.getElementsByTagName("input")[0];if(e&&e.length&&f){d.support={leadingWhitespace:b.firstChild.nodeType===3,tbody:!b.getElementsByTagName("tbody").length,htmlSerialize:!!b.getElementsByTagName("link").length,style:/red/.test(f.getAttribute("style")),hrefNormalized:f.getAttribute("href")==="/a",opacity:/^0.55$/.test(f.style.opacity),cssFloat:!!f.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,deleteExpando:!0,optDisabled:!1,checkClone:!1,noCloneEvent:!0,noCloneChecked:!0,boxModel:null,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableHiddenOffsets:!0,reliableMarginRight:!0},i.checked=!0,d.support.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,d.support.optDisabled=!h.disabled;var j=null;d.support.scriptEval=function(){if(j===null){var b=c.documentElement,e=c.createElement("script"),f="script"+d.now();try{e.appendChild(c.createTextNode("window."+f+"=1;"))}catch(g){}b.insertBefore(e,b.firstChild),a[f]?(j=!0,delete a[f]):j=!1,b.removeChild(e)}return j};try{delete b.test}catch(k){d.support.deleteExpando=!1}!b.addEventListener&&b.attachEvent&&b.fireEvent&&(b.attachEvent("onclick",function l(){d.support.noCloneEvent=!1,b.detachEvent("onclick",l)}),b.cloneNode(!0).fireEvent("onclick")),b=c.createElement("div"),b.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";var m=c.createDocumentFragment();m.appendChild(b.firstChild),d.support.checkClone=m.cloneNode(!0).cloneNode(!0).lastChild.checked,d(function(){var a=c.createElement("div"),b=c.getElementsByTagName("body")[0];if(b){a.style.width=a.style.paddingLeft="1px",b.appendChild(a),d.boxModel=d.support.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,d.support.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",d.support.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";var e=a.getElementsByTagName("td");d.support.reliableHiddenOffsets=e[0].offsetHeight===0,e[0].style.display="",e[1].style.display="none",d.support.reliableHiddenOffsets=d.support.reliableHiddenOffsets&&e[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(a.style.width="1px",a.style.marginRight="0",d.support.reliableMarginRight=(parseInt(c.defaultView.getComputedStyle(a,null).marginRight,10)||0)===0),b.removeChild(a).style.display="none",a=e=null}});var n=function(a){var b=c.createElement("div");a="on"+a;if(!b.attachEvent)return!0;var d=a in b;d||(b.setAttribute(a,"return;"),d=typeof b[a]==="function");return d};d.support.submitBubbles=n("submit"),d.support.changeBubbles=n("change"),b=e=f=null}}();var g=/^(?:\{.*\}|\[.*\])$/;d.extend({cache:{},uuid:0,expando:"jQuery"+(d.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?d.cache[a[d.expando]]:a[d.expando];return!!a&&!i(a)},data:function(a,c,e,f){if(d.acceptData(a)){var g=d.expando,h=typeof c==="string",i,j=a.nodeType,k=j?d.cache:a,l=j?a[d.expando]:a[d.expando]&&d.expando;if((!l||f&&l&&!k[l][g])&&h&&e===b)return;l||(j?a[d.expando]=l=++d.uuid:l=d.expando),k[l]||(k[l]={},j||(k[l].toJSON=d.noop));if(typeof c==="object"||typeof c==="function")f?k[l][g]=d.extend(k[l][g],c):k[l]=d.extend(k[l],c);i=k[l],f&&(i[g]||(i[g]={}),i=i[g]),e!==b&&(i[c]=e);if(c==="events"&&!i[c])return i[g]&&i[g].events;return h?i[c]:i}},removeData:function(b,c,e){if(d.acceptData(b)){var f=d.expando,g=b.nodeType,h=g?d.cache:b,j=g?b[d.expando]:d.expando;if(!h[j])return;if(c){var k=e?h[j][f]:h[j];if(k){delete k[c];if(!i(k))return}}if(e){delete h[j][f];if(!i(h[j]))return}var l=h[j][f];d.support.deleteExpando||h!=a?delete h[j]:h[j]=null,l?(h[j]={},g||(h[j].toJSON=d.noop),h[j][f]=l):g&&(d.support.deleteExpando?delete b[d.expando]:b.removeAttribute?b.removeAttribute(d.expando):b[d.expando]=null)}},_data:function(a,b,c){return d.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=d.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),d.fn.extend({data:function(a,c){var e=null;if(typeof a==="undefined"){if(this.length){e=d.data(this[0]);if(this[0].nodeType===1){var f=this[0].attributes,g;for(var i=0,j=f.length;i<j;i++)g=f[i].name,g.indexOf("data-")===0&&(g=g.substr(5),h(this[0],g,e[g]))}}return e}if(typeof a==="object")return this.each(function(){d.data(this,a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(c===b){e=this.triggerHandler("getData"+k[1]+"!",[k[0]]),e===b&&this.length&&(e=d.data(this[0],a),e=h(this[0],a,e));return e===b&&k[1]?this.data(k[0]):e}return this.each(function(){var b=d(this),e=[k[0],c];b.triggerHandler("setData"+k[1]+"!",e),d.data(this,a,c),b.triggerHandler("changeData"+k[1]+"!",e)})},removeData:function(a){return this.each(function(){d.removeData(this,a)})}}),d.extend({queue:function(a,b,c){if(a){b=(b||"fx")+"queue";var e=d._data(a,b);if(!c)return e||[];!e||d.isArray(c)?e=d._data(a,b,d.makeArray(c)):e.push(c);return e}},dequeue:function(a,b){b=b||"fx";var c=d.queue(a,b),e=c.shift();e==="inprogress"&&(e=c.shift()),e&&(b==="fx"&&c.unshift("inprogress"),e.call(a,function(){d.dequeue(a,b)})),c.length||d.removeData(a,b+"queue",!0)}}),d.fn.extend({queue:function(a,c){typeof a!=="string"&&(c=a,a="fx");if(c===b)return d.queue(this[0],a);return this.each(function(b){var e=d.queue(this,a,c);a==="fx"&&e[0]!=="inprogress"&&d.dequeue(this,a)})},dequeue:function(a){return this.each(function(){d.dequeue(this,a)})},delay:function(a,b){a=d.fx?d.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(){var c=this;setTimeout(function(){d.dequeue(c,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var j=/[\n\t\r]/g,k=/\s+/,l=/\r/g,m=/^(?:href|src|style)$/,n=/^(?:button|input)$/i,o=/^(?:button|input|object|select|textarea)$/i,p=/^a(?:rea)?$/i,q=/^(?:radio|checkbox)$/i;d.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"},d.fn.extend({attr:function(a,b){return d.access(this,a,b,!0,d.attr)},removeAttr:function(a,b){return this.each(function(){d.attr(this,a,""),this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.addClass(a.call(this,b,c.attr("class")))});if(a&&typeof a==="string"){var b=(a||"").split(k);for(var c=0,e=this.length;c<e;c++){var f=this[c];if(f.nodeType===1)if(f.className){var g=" "+f.className+" ",h=f.className;for(var i=0,j=b.length;i<j;i++)g.indexOf(" "+b[i]+" ")<0&&(h+=" "+b[i]);f.className=d.trim(h)}else f.className=a}}return this},removeClass:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.removeClass(a.call(this,b,c.attr("class")))});if(a&&typeof a==="string"||a===b){var c=(a||"").split(k);for(var e=0,f=this.length;e<f;e++){var g=this[e];if(g.nodeType===1&&g.className)if(a){var h=(" "+g.className+" ").replace(j," ");for(var i=0,l=c.length;i<l;i++)h=h.replace(" "+c[i]+" "," ");g.className=d.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,e=typeof b==="boolean";if(d.isFunction(a))return this.each(function(c){var e=d(this);e.toggleClass(a.call(this,c,e.attr("class"),b),b)});return this.each(function(){if(c==="string"){var f,g=0,h=d(this),i=b,j=a.split(k);while(f=j[g++])i=e?i:!h.hasClass(f),h[i?"addClass":"removeClass"](f)}else if(c==="undefined"||c==="boolean")this.className&&d._data(this,"__className__",this.className),this.className=this.className||a===!1?"":d._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ";for(var c=0,d=this.length;c<d;c++)if((" "+this[c].className+" ").replace(j," ").indexOf(b)>-1)return!0;return!1},val:function(a){if(!arguments.length){var c=this[0];if(c){if(d.nodeName(c,"option")){var e=c.attributes.value;return!e||e.specified?c.value:c.text}if(d.nodeName(c,"select")){var f=c.selectedIndex,g=[],h=c.options,i=c.type==="select-one";if(f<0)return null;for(var j=i?f:0,k=i?f+1:h.length;j<k;j++){var m=h[j];if(m.selected&&(d.support.optDisabled?!m.disabled:m.getAttribute("disabled")===null)&&(!m.parentNode.disabled||!d.nodeName(m.parentNode,"optgroup"))){a=d(m).val();if(i)return a;g.push(a)}}if(i&&!g.length&&h.length)return d(h[f]).val();return g}if(q.test(c.type)&&!d.support.checkOn)return c.getAttribute("value")===null?"on":c.value;return(c.value||"").replace(l,"")}return b}var n=d.isFunction(a);return this.each(function(b){var c=d(this),e=a;if(this.nodeType===1){n&&(e=a.call(this,b,c.val())),e==null?e="":typeof e==="number"?e+="":d.isArray(e)&&(e=d.map(e,function(a){return a==null?"":a+""}));if(d.isArray(e)&&q.test(this.type))this.checked=d.inArray(c.val(),e)>=0;else if(d.nodeName(this,"select")){var f=d.makeArray(e);d("option",this).each(function(){this.selected=d.inArray(d(this).val(),f)>=0}),f.length||(this.selectedIndex=-1)}else this.value=e}})}}),d.extend({attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,e,f){if(!a||a.nodeType===3||a.nodeType===8||a.nodeType===2)return b;if(f&&c in d.attrFn)return d(a)[c](e);var g=a.nodeType!==1||!d.isXMLDoc(a),h=e!==b;c=g&&d.props[c]||c;if(a.nodeType===1){var i=m.test(c);if(c==="selected"&&!d.support.optSelected){var j=a.parentNode;j&&(j.selectedIndex,j.parentNode&&j.parentNode.selectedIndex)}if((c in a||a[c]!==b)&&g&&!i){h&&(c==="type"&&n.test(a.nodeName)&&a.parentNode&&d.error("type property can't be changed"),e===null?a.nodeType===1&&a.removeAttribute(c):a[c]=e);if(d.nodeName(a,"form")&&a.getAttributeNode(c))return a.getAttributeNode(c).nodeValue;if(c==="tabIndex"){var k=a.getAttributeNode("tabIndex");return k&&k.specified?k.value:o.test(a.nodeName)||p.test(a.nodeName)&&a.href?0:b}return a[c]}if(!d.support.style&&g&&c==="style"){h&&(a.style.cssText=""+e);return a.style.cssText}h&&a.setAttribute(c,""+e);if(!a.attributes[c]&&(a.hasAttribute&&!a.hasAttribute(c)))return b;var l=!d.support.hrefNormalized&&g&&i?a.getAttribute(c,2):a.getAttribute(c);return l===null?b:l}h&&(a[c]=e);return a[c]}});var r=/\.(.*)$/,s=/^(?:textarea|input|select)$/i,t=/\./g,u=/ /g,v=/[^\w\s.|`]/g,w=function(a){return a.replace(v,"\\$&")};d.event={add:function(c,e,f,g){if(c.nodeType!==3&&c.nodeType!==8){try{d.isWindow(c)&&(c!==a&&!c.frameElement)&&(c=a)}catch(h){}if(f===!1)f=x;else if(!f)return;var i,j;f.handler&&(i=f,f=i.handler),f.guid||(f.guid=d.guid++);var k=d._data(c);if(!k)return;var l=k.events,m=k.handle;l||(k.events=l={}),m||(k.handle=m=function(a){return typeof d!=="undefined"&&d.event.triggered!==a.type?d.event.handle.apply(m.elem,arguments):b}),m.elem=c,e=e.split(" ");var n,o=0,p;while(n=e[o++]){j=i?d.extend({},i):{handler:f,data:g},n.indexOf(".")>-1?(p=n.split("."),n=p.shift(),j.namespace=p.slice(0).sort().join(".")):(p=[],j.namespace=""),j.type=n,j.guid||(j.guid=f.guid);var q=l[n],r=d.event.special[n]||{};if(!q){q=l[n]=[];if(!r.setup||r.setup.call(c,g,p,m)===!1)c.addEventListener?c.addEventListener(n,m,!1):c.attachEvent&&c.attachEvent("on"+n,m)}r.add&&(r.add.call(c,j),j.handler.guid||(j.handler.guid=f.guid)),q.push(j),d.event.global[n]=!0}c=null}},global:{},remove:function(a,c,e,f){if(a.nodeType!==3&&a.nodeType!==8){e===!1&&(e=x);var g,h,i,j,k=0,l,m,n,o,p,q,r,s=d.hasData(a)&&d._data(a),t=s&&s.events;if(!s||!t)return;c&&c.type&&(e=c.handler,c=c.type);if(!c||typeof c==="string"&&c.charAt(0)==="."){c=c||"";for(h in t)d.event.remove(a,h+c);return}c=c.split(" ");while(h=c[k++]){r=h,q=null,l=h.indexOf(".")<0,m=[],l||(m=h.split("."),h=m.shift(),n=new RegExp("(^|\\.)"+d.map(m.slice(0).sort(),w).join("\\.(?:.*\\.)?")+"(\\.|$)")),p=t[h];if(!p)continue;if(!e){for(j=0;j<p.length;j++){q=p[j];if(l||n.test(q.namespace))d.event.remove(a,r,q.handler,j),p.splice(j--,1)}continue}o=d.event.special[h]||{};for(j=f||0;j<p.length;j++){q=p[j];if(e.guid===q.guid){if(l||n.test(q.namespace))f==null&&p.splice(j--,1),o.remove&&o.remove.call(a,q);if(f!=null)break}}if(p.length===0||f!=null&&p.length===1)(!o.teardown||o.teardown.call(a,m)===!1)&&d.removeEvent(a,h,s.handle),g=null,delete t[h]}if(d.isEmptyObject(t)){var u=s.handle;u&&(u.elem=null),delete s.events,delete s.handle,d.isEmptyObject(s)&&d.removeData(a,b,!0)}}},trigger:function(a,c,e){var f=a.type||a,g=arguments[3];if(!g){a=typeof a==="object"?a[d.expando]?a:d.extend(d.Event(f),a):d.Event(f),f.indexOf("!")>=0&&(a.type=f=f.slice(0,-1),a.exclusive=!0),e||(a.stopPropagation(),d.event.global[f]&&d.each(d.cache,function(){var b=d.expando,e=this[b];e&&e.events&&e.events[f]&&d.event.trigger(a,c,e.handle.elem)}));if(!e||e.nodeType===3||e.nodeType===8)return b;a.result=b,a.target=e,c=d.makeArray(c),c.unshift(a)}a.currentTarget=e;var h=d._data(e,"handle");h&&h.apply(e,c);var i=e.parentNode||e.ownerDocument;try{e&&e.nodeName&&d.noData[e.nodeName.toLowerCase()]||e["on"+f]&&e["on"+f].apply(e,c)===!1&&(a.result=!1,a.preventDefault())}catch(j){}if(!a.isPropagationStopped()&&i)d.event.trigger(a,c,i,!0);else if(!a.isDefaultPrevented()){var k,l=a.target,m=f.replace(r,""),n=d.nodeName(l,"a")&&m==="click",o=d.event.special[m]||{};if((!o._default||o._default.call(e,a)===!1)&&!n&&!(l&&l.nodeName&&d.noData[l.nodeName.toLowerCase()])){try{l[m]&&(k=l["on"+m],k&&(l["on"+m]=null),d.event.triggered=a.type,l[m]())}catch(p){}k&&(l["on"+m]=k),d.event.triggered=b}}},handle:function(c){var e,f,g,h,i,j=[],k=d.makeArray(arguments);c=k[0]=d.event.fix(c||a.event),c.currentTarget=this,e=c.type.indexOf(".")<0&&!c.exclusive,e||(g=c.type.split("."),c.type=g.shift(),j=g.slice(0).sort(),h=new RegExp("(^|\\.)"+j.join("\\.(?:.*\\.)?")+"(\\.|$)")),c.namespace=c.namespace||j.join("."),i=d._data(this,"events"),f=(i||{})[c.type];if(i&&f){f=f.slice(0);for(var l=0,m=f.length;l<m;l++){var n=f[l];if(e||h.test(n.namespace)){c.handler=n.handler,c.data=n.data,c.handleObj=n;var o=n.handler.apply(this,k);o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()));if(c.isImmediatePropagationStopped())break}}}return c.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[d.expando])return a;var e=a;a=d.Event(e);for(var f=this.props.length,g;f;)g=this.props[--f],a[g]=e[g];a.target||(a.target=a.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),!a.relatedTarget&&a.fromElement&&(a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement);if(a.pageX==null&&a.clientX!=null){var h=c.documentElement,i=c.body;a.pageX=a.clientX+(h&&h.scrollLeft||i&&i.scrollLeft||0)-(h&&h.clientLeft||i&&i.clientLeft||0),a.pageY=a.clientY+(h&&h.scrollTop||i&&i.scrollTop||0)-(h&&h.clientTop||i&&i.clientTop||0)}a.which==null&&(a.charCode!=null||a.keyCode!=null)&&(a.which=a.charCode!=null?a.charCode:a.keyCode),!a.metaKey&&a.ctrlKey&&(a.metaKey=a.ctrlKey),!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:d.proxy,special:{ready:{setup:d.bindReady,teardown:d.noop},live:{add:function(a){d.event.add(this,H(a.origType,a.selector),d.extend({},a,{handler:G,guid:a.handler.guid}))},remove:function(a){d.event.remove(this,H(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,c){d.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}}},d.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},d.Event=function(a){if(!this.preventDefault)return new d.Event(a);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?y:x):this.type=a,this.timeStamp=d.now(),this[d.expando]=!0},d.Event.prototype={preventDefault:function(){this.isDefaultPrevented=y;var a=this.originalEvent;a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=y;var a=this.originalEvent;a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=y,this.stopPropagation()},isDefaultPrevented:x,isPropagationStopped:x,isImmediatePropagationStopped:x};var z=function(a){var b=a.relatedTarget;try{if(b&&b!==c&&!b.parentNode)return;while(b&&b!==this)b=b.parentNode;b!==this&&(a.type=a.data,d.event.handle.apply(this,arguments))}catch(e){}},A=function(a){a.type=a.data,d.event.handle.apply(this,arguments)};d.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){d.event.special[a]={setup:function(c){d.event.add(this,b,c&&c.selector?A:z,a)},teardown:function(a){d.event.remove(this,b,a&&a.selector?A:z)}}}),d.support.submitBubbles||(d.event.special.submit={setup:function(a,b){if(this.nodeName&&this.nodeName.toLowerCase()!=="form")d.event.add(this,"click.specialSubmit",function(a){var b=a.target,c=b.type;(c==="submit"||c==="image")&&d(b).closest("form").length&&E("submit",this,arguments)}),d.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=b.type;(c==="text"||c==="password")&&d(b).closest("form").length&&a.keyCode===13&&E("submit",this,arguments)});else return!1},teardown:function(a){d.event.remove(this,".specialSubmit")}});if(!d.support.changeBubbles){var B,C=function(a){var b=a.type,c=a.value;b==="radio"||b==="checkbox"?c=a.checked:b==="select-multiple"?c=a.selectedIndex>-1?d.map(a.options,function(a){return a.selected}).join("-"):"":a.nodeName.toLowerCase()==="select"&&(c=a.selectedIndex);return c},D=function D(a){var c=a.target,e,f;if(s.test(c.nodeName)&&!c.readOnly){e=d._data(c,"_change_data"),f=C(c),(a.type!=="focusout"||c.type!=="radio")&&d._data(c,"_change_data",f);if(e===b||f===e)return;if(e!=null||f)a.type="change",a.liveFired=b,d.event.trigger(a,arguments[1],c)}};d.event.special.change={filters:{focusout:D,beforedeactivate:D,click:function(a){var b=a.target,c=b.type;(c==="radio"||c==="checkbox"||b.nodeName.toLowerCase()==="select")&&D.call(this,a)},keydown:function(a){var b=a.target,c=b.type;(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(c==="checkbox"||c==="radio")||c==="select-multiple")&&D.call(this,a)},beforeactivate:function(a){var b=a.target;d._data(b,"_change_data",C(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in B)d.event.add(this,c+".specialChange",B[c]);return s.test(this.nodeName)},teardown:function(a){d.event.remove(this,".specialChange");return s.test(this.nodeName)}},B=d.event.special.change.filters,B.focus=B.beforeactivate}c.addEventListener&&d.each({focus:"focusin",blur:"focusout"},function(a,b){function f(a){var c=d.event.fix(a);c.type=b,c.originalEvent={},d.event.trigger(c,null,c.target),c.isDefaultPrevented()&&a.preventDefault()}var e=0;d.event.special[b]={setup:function(){e++===0&&c.addEventListener(a,f,!0)},teardown:function(){--e===0&&c.removeEventListener(a,f,!0)}}}),d.each(["bind","one"],function(a,c){d.fn[c]=function(a,e,f){if(typeof a==="object"){for(var g in a)this[c](g,e,a[g],f);return this}if(d.isFunction(e)||e===!1)f=e,e=b;var h=c==="one"?d.proxy(f,function(a){d(this).unbind(a,h);return f.apply(this,arguments)}):f;if(a==="unload"&&c!=="one")this.one(a,e,f);else for(var i=0,j=this.length;i<j;i++)d.event.add(this[i],a,h,e);return this}}),d.fn.extend({unbind:function(a,b){if(typeof a!=="object"||a.preventDefault)for(var e=0,f=this.length;e<f;e++)d.event.remove(this[e],a,b);else for(var c in a)this.unbind(c,a[c]);return this},delegate:function(a,b,c,d){return this.live(b,c,d,a)},undelegate:function(a,b,c){return arguments.length===0?this.unbind("live"):this.die(b,null,c,a)},trigger:function(a,b){return this.each(function(){d.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var c=d.Event(a);c.preventDefault(),c.stopPropagation(),d.event.trigger(c,b,this[0]);return c.result}},toggle:function(a){var b=arguments,c=1;while(c<b.length)d.proxy(a,b[c++]);return this.click(d.proxy(a,function(e){var f=(d._data(this,"lastToggle"+a.guid)||0)%c;d._data(this,"lastToggle"+a.guid,f+1),e.preventDefault();return b[f].apply(this,arguments)||!1}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var F={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};d.each(["live","die"],function(a,c){d.fn[c]=function(a,e,f,g){var h,i=0,j,k,l,m=g||this.selector,n=g?this:d(this.context);if(typeof a==="object"&&!a.preventDefault){for(var o in a)n[c](o,e,a[o],m);return this}d.isFunction(e)&&(f=e,e=b),a=(a||"").split(" ");while((h=a[i++])!=null){j=r.exec(h),k="",j&&(k=j[0],h=h.replace(r,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,h==="focus"||h==="blur"?(a.push(F[h]+k),h=h+k):h=(F[h]||h)+k;if(c==="live")for(var p=0,q=n.length;p<q;p++)d.event.add(n[p],"live."+H(h,m),{data:e,selector:m,handler:f,origType:h,origHandler:f,preType:l});else n.unbind("live."+H(h,m),f)}return this}}),d.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){d.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},d.attrFn&&(d.attrFn[b]=!0)}),function(){function u(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}if(i.nodeType===1){f||(i.sizcache=c,i.sizset=g);if(typeof b!=="string"){if(i===b){j=!0;break}}else if(k.filter(b,[i]).length>0){j=i;break}}i=i[a]}d[g]=j}}}function t(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}i.nodeType===1&&!f&&(i.sizcache=c,i.sizset=g);if(i.nodeName.toLowerCase()===b){j=i;break}i=i[a]}d[g]=j}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,g=!1,h=!0,i=/\\/g,j=/\W/;[0,0].sort(function(){h=!1;return 0});var k=function(b,d,e,g){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!=="string")return e;var i,j,n,o,q,r,s,t,u=!0,w=k.isXML(d),x=[],y=b;do{a.exec(""),i=a.exec(y);if(i){y=i[3],x.push(i[1]);if(i[2]){o=i[3];break}}}while(i);if(x.length>1&&m.exec(b))if(x.length===2&&l.relative[x[0]])j=v(x[0]+x[1],d);else{j=l.relative[x[0]]?[d]:k(x.shift(),d);while(x.length)b=x.shift(),l.relative[b]&&(b+=x.shift()),j=v(b,j)}else{!g&&x.length>1&&d.nodeType===9&&!w&&l.match.ID.test(x[0])&&!l.match.ID.test(x[x.length-1])&&(q=k.find(x.shift(),d,w),d=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]);if(d){q=g?{expr:x.pop(),set:p(g)}:k.find(x.pop(),x.length===1&&(x[0]==="~"||x[0]==="+")&&d.parentNode?d.parentNode:d,w),j=q.expr?k.filter(q.expr,q.set):q.set,x.length>0?n=p(j):u=!1;while(x.length)r=x.pop(),s=r,l.relative[r]?s=x.pop():r="",s==null&&(s=d),l.relative[r](n,s,w)}else n=x=[]}n||(n=j),n||k.error(r||b);if(f.call(n)==="[object Array]")if(u)if(d&&d.nodeType===1)for(t=0;n[t]!=null;t++)n[t]&&(n[t]===!0||n[t].nodeType===1&&k.contains(d,n[t]))&&e.push(j[t]);else for(t=0;n[t]!=null;t++)n[t]&&n[t].nodeType===1&&e.push(j[t]);else e.push.apply(e,n);else p(n,e);o&&(k(o,h,e,g),k.uniqueSort(e));return e};k.uniqueSort=function(a){if(r){g=h,a.sort(r);if(g)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},k.matches=function(a,b){return k(a,null,null,b)},k.matchesSelector=function(a,b){return k(b,null,null,[a]).length>0},k.find=function(a,b,c){var d;if(!a)return[];for(var e=0,f=l.order.length;e<f;e++){var g,h=l.order[e];if(g=l.leftMatch[h].exec(a)){var j=g[1];g.splice(1,1);if(j.substr(j.length-1)!=="\\"){g[1]=(g[1]||"").replace(i,""),d=l.find[h](g,b,c);if(d!=null){a=a.replace(l.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!=="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},k.filter=function(a,c,d,e){var f,g,h=a,i=[],j=c,m=c&&c[0]&&k.isXML(c[0]);while(a&&c.length){for(var n in l.filter)if((f=l.leftMatch[n].exec(a))!=null&&f[2]){var o,p,q=l.filter[n],r=f[1];g=!1,f.splice(1,1);if(r.substr(r.length-1)==="\\")continue;j===i&&(i=[]);if(l.preFilter[n]){f=l.preFilter[n](f,j,d,i,e,m);if(f){if(f===!0)continue}else g=o=!0}if(f)for(var s=0;(p=j[s])!=null;s++)if(p){o=q(p,f,s,j);var t=e^!!o;d&&o!=null?t?g=!0:j[s]=!1:t&&(i.push(p),g=!0)}if(o!==b){d||(j=i),a=a.replace(l.match[n],"");if(!g)return[];break}}if(a===h)if(g==null)k.error(a);else break;h=a}return j},k.error=function(a){throw"Syntax error, unrecognized expression: "+a};var l=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|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b==="string",d=c&&!j.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1){}a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&k.filter(b,a,!0)},">":function(a,b){var c,d=typeof b==="string",e=0,f=a.length;if(d&&!j.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&k.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=u;typeof b==="string"&&!j.test(b)&&(b=b.toLowerCase(),d=b,g=t),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=u;typeof b==="string"&&!j.test(b)&&(b=b.toLowerCase(),d=b,g=t),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!=="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!=="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!=="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(i,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(i,"")},TAG:function(a,b){return a[1].replace(i,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||k.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&k.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(i,"");!f&&l.attrMap[g]&&(a[1]=l.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(i,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=k(b[3],null,null,c);else{var g=k.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(l.match.POS.test(b[0])||l.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!k(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return"text"===c&&(b===c||b===null)},radio:function(a){return"radio"===a.type},checkbox:function(a){return"checkbox"===a.type},file:function(a){return"file"===a.type},password:function(a){return"password"===a.type},submit:function(a){return"submit"===a.type},image:function(a){return"image"===a.type},reset:function(a){return"reset"===a.type},button:function(a){return"button"===a.type||a.nodeName.toLowerCase()==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=l.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||k.getText([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}k.error(e)},CHILD:function(a,b){var c=b[1],d=a;switch(c){case"only":case"first":while(d=d.previousSibling)if(d.nodeType===1)return!1;if(c==="first")return!0;d=a;case"last":while(d=d.nextSibling)if(d.nodeType===1)return!1;return!0;case"nth":var e=b[2],f=b[3];if(e===1&&f===0)return!0;var g=b[0],h=a.parentNode;if(h&&(h.sizcache!==g||!a.nodeIndex)){var i=0;for(d=h.firstChild;d;d=d.nextSibling)d.nodeType===1&&(d.nodeIndex=++i);h.sizcache=g}var j=a.nodeIndex-f;return e===0?j===0:j%e===0&&j/e>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=l.attrHandle[c]?l.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=l.setFilters[e];if(f)return f(a,c,b,d)}}},m=l.match.POS,n=function(a,b){return"\\"+(b-0+1)};for(var o in l.match)l.match[o]=new RegExp(l.match[o].source+/(?![^\[]*\])(?![^\(]*\))/.source),l.leftMatch[o]=new RegExp(/(^(?:.|\r|\n)*?)/.source+l.match[o].source.replace(/\\(\d+)/g,n));var p=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(q){p=function(a,b){var c=0,d=b||[];if(f.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length==="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var r,s;c.documentElement.compareDocumentPosition?r=function(a,b){if(a===b){g=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(r=function(a,b){var c,d,e=[],f=[],h=a.parentNode,i=b.parentNode,j=h;if(a===b){g=!0;return 0}if(h===i)return s(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return s(e[k],f[k]);return k===c?s(a,f[k],-1):s(e[k],b,1)},s=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),k.getText=function(a){var b="",c;for(var d=0;a[d];d++)c=a[d],c.nodeType===3||c.nodeType===4?b+=c.nodeValue:c.nodeType!==8&&(b+=k.getText(c.childNodes));return b},function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(l.find.ID=function(a,c,d){if(typeof c.getElementById!=="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!=="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},l.filter.ID=function(a,b){var c=typeof a.getAttributeNode!=="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(l.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!=="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(l.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=k,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){k=function(b,e,f,g){e=e||c;if(!g&&!k.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return p(e.getElementsByTagName(b),f);if(h[2]&&l.find.CLASS&&e.getElementsByClassName)return p(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return p([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return p([],f);if(i.id===h[3])return p([i],f)}try{return p(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var m=e,n=e.getAttribute("id"),o=n||d,q=e.parentNode,r=/^\s*[+~]/.test(b);n?o=o.replace(/'/g,"\\$&"):e.setAttribute("id",o),r&&q&&(e=e.parentNode);try{if(!r||q)return p(e.querySelectorAll("[id='"+o+"'] "+b),f)}catch(s){}finally{n||m.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)k[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}k.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(a))try{if(e||!l.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return k(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;l.order.splice(1,0,"CLASS"),l.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!=="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?k.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?k.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:k.contains=function(){return!1},k.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var v=function(a,b){var c,d=[],e="",f=b.nodeType?[b]:b;while(c=l.match.PSEUDO.exec(a))e+=c[0],a=a.replace(l.match.PSEUDO,"");a=l.relative[a]?a+"*":a;for(var g=0,h=f.length;g<h;g++)k(a,f[g],d);return k.filter(e,d)};d.find=k,d.expr=k.selectors,d.expr[":"]=d.expr.filters,d.unique=k.uniqueSort,d.text=k.getText,d.isXMLDoc=k.isXML,d.contains=k.contains}();var I=/Until$/,J=/^(?:parents|prevUntil|prevAll)/,K=/,/,L=/^.[^:#\[\.,]*$/,M=Array.prototype.slice,N=d.expr.match.POS,O={children:!0,contents:!0,next:!0,prev:!0};d.fn.extend({find:function(a){var b=this.pushStack("","find",a),c=0;for(var e=0,f=this.length;e<f;e++){c=b.length,d.find(a,this[e],b);if(e>0)for(var g=c;g<b.length;g++)for(var h=0;h<c;h++)if(b[h]===b[g]){b.splice(g--,1);break}}return b},has:function(a){var b=d(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(d.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(Q(this,a,!1),"not",a)},filter:function(a){return this.pushStack(Q(this,a,!0),"filter",a)},is:function(a){return!!a&&d.filter(a,this).length>0},closest:function(a,b){var c=[],e,f,g=this[0];if(d.isArray(a)){var h,i,j={},k=1;if(g&&a.length){for(e=0,f=a.length;e<f;e++)i=a[e],j[i]||(j[i]=d.expr.match.POS.test(i)?d(i,b||this.context):i);while(g&&g.ownerDocument&&g!==b){for(i in j)h=j[i],(h.jquery?h.index(g)>-1:d(g).is(h))&&c.push({selector:i,elem:g,level:k});g=g.parentNode,k++}}return c}var l=N.test(a)?d(a,b||this.context):null;for(e=0,f=this.length;e<f;e++){g=this[e];while(g){if(l?l.index(g)>-1:d.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b)break}}c=c.length>1?d.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a||typeof a==="string")return d.inArray(this[0],a?d(a):this.parent().children());return d.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a==="string"?d(a,b):d.makeArray(a),e=d.merge(this.get(),c);return this.pushStack(P(c[0])||P(e[0])?e:d.unique(e))},andSelf:function(){return this.add(this.prevObject)}}),d.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return d.dir(a,"parentNode")},parentsUntil:function(a,b,c){return d.dir(a,"parentNode",c)},next:function(a){return d.nth(a,2,"nextSibling")},prev:function(a){return d.nth(a,2,"previousSibling")},nextAll:function(a){return d.dir(a,"nextSibling")},prevAll:function(a){return d.dir(a,"previousSibling")},nextUntil:function(a,b,c){return d.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return d.dir(a,"previousSibling",c)},siblings:function(a){return d.sibling(a.parentNode.firstChild,a)},children:function(a){return d.sibling(a.firstChild)},contents:function(a){return d.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:d.makeArray(a.childNodes)}},function(a,b){d.fn[a]=function(c,e){var f=d.map(this,b,c),g=M.call(arguments);I.test(a)||(e=c),e&&typeof e==="string"&&(f=d.filter(e,f)),f=this.length>1&&!O[a]?d.unique(f):f,(this.length>1||K.test(e))&&J.test(a)&&(f=f.reverse());return this.pushStack(f,a,g.join(","))}}),d.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?d.find.matchesSelector(b[0],a)?[b[0]]:[]:d.find.matches(a,b)},dir:function(a,c,e){var f=[],g=a[c];while(g&&g.nodeType!==9&&(e===b||g.nodeType!==1||!d(g).is(e)))g.nodeType===1&&f.push(g),g=g[c];return f},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var R=/ jQuery\d+="(?:\d+|null)"/g,S=/^\s+/,T=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,U=/<([\w:]+)/,V=/<tbody/i,W=/<|&#?\w+;/,X=/<(?:script|object|embed|option|style)/i,Y=/checked\s*(?:[^=]|=\s*.checked.)/i,Z={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,"",""]};Z.optgroup=Z.option,Z.tbody=Z.tfoot=Z.colgroup=Z.caption=Z.thead,Z.th=Z.td,d.support.htmlSerialize||(Z._default=[1,"div<div>","</div>"]),d.fn.extend({text:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.text(a.call(this,b,c.text()))});if(typeof a!=="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return d.text(this)},wrapAll:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapAll(a.call(this,b))});if(this[0]){var b=d(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapInner(a.call(this,b))});return this.each(function(){var b=d(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){d(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){d.nodeName(this,"body")||d(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=d(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,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,d(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,e;(e=this[c])!=null;c++)if(!a||d.filter(a,[e]).length)!b&&e.nodeType===1&&(d.cleanData(e.getElementsByTagName("*")),d.cleanData([e])),e.parentNode&&e.parentNode.removeChild(e);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&d.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return d.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(R,""):null;if(typeof a!=="string"||X.test(a)||!d.support.leadingWhitespace&&S.test(a)||Z[(U.exec(a)||["",""])[1].toLowerCase()])d.isFunction(a)?this.each(function(b){var c=d(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);else{a=a.replace(T,"<$1></$2>");try{for(var c=0,e=this.length;c<e;c++)this[c].nodeType===1&&(d.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(f){this.empty().append(a)}}return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(d.isFunction(a))return this.each(function(b){var c=d(this),e=c.html();c.replaceWith(a.call(this,b,e))});typeof a!=="string"&&(a=d(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;d(this).remove(),b?d(b).before(a):d(c).append(a)})}return this.length?this.pushStack(d(d.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,e){var f,g,h,i,j=a[0],k=[];if(!d.support.checkClone&&arguments.length===3&&typeof j==="string"&&Y.test(j))return this.each(function(){d(this).domManip(a,c,e,!0)});if(d.isFunction(j))return this.each(function(f){var g=d(this);a[0]=j.call(this,f,c?g.html():b),g.domManip(a,c,e)});if(this[0]){i=j&&j.parentNode,d.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?f={fragment:i}:f=d.buildFragment(a,this,k),h=f.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&d.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)e.call(c?$(this[l],g):this[l],f.cacheable||m>1&&l<n?d.clone(h,!0,!0):h)}k.length&&d.each(k,bc)}return this}}),d.buildFragment=function(a,b,e){var f,g,h,i=b&&b[0]?b[0].ownerDocument||b[0]:c;a.length===1&&typeof a[0]==="string"&&a[0].length<512&&i===c&&a[0].charAt(0)==="<"&&!X.test(a[0])&&(d.support.checkClone||!Y.test(a[0]))&&(g=!0,h=d.fragments[a[0]],h&&(h!==1&&(f=h))),f||(f=i.createDocumentFragment(),d.clean(a,i,f,e)),g&&(d.fragments[a[0]]=h?f:1);return{fragment:f,cacheable:g}},d.fragments={},d.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){d.fn[a]=function(c){var e=[],f=d(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&f.length===1){f[b](this[0]);return this}for(var h=0,i=f.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();d(f[h])[b](j),e=e.concat(j)}return this.pushStack(e,a,f.selector)}}),d.extend({clone:function(a,b,c){var e=a.cloneNode(!0),f,g,h;if((!d.support.noCloneEvent||!d.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!d.isXMLDoc(a)){ba(a,e),f=bb(a),g=bb(e);for(h=0;f[h];++h)ba(f[h],g[h])}if(b){_(a,e);if(c){f=bb(a),g=bb(e);for(h=0;f[h];++h)_(f[h],g[h])}}return e},clean:function(a,b,e,f){b=b||c,typeof b.createElement==="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var g=[];for(var h=0,i;(i=a[h])!=null;h++){typeof i==="number"&&(i+="");if(!i)continue;if(typeof i!=="string"||W.test(i)){if(typeof i==="string"){i=i.replace(T,"<$1></$2>");var j=(U.exec(i)||["",""])[1].toLowerCase(),k=Z[j]||Z._default,l=k[0],m=b.createElement("div");m.innerHTML=k[1]+i+k[2];while(l--)m=m.lastChild;if(!d.support.tbody){var n=V.test(i),o=j==="table"&&!n?m.firstChild&&m.firstChild.childNodes:k[1]==="<table>"&&!n?m.childNodes:[];for(var p=o.length-1;p>=0;--p)d.nodeName(o[p],"tbody")&&!o[p].childNodes.length&&o[p].parentNode.removeChild(o[p])}!d.support.leadingWhitespace&&S.test(i)&&m.insertBefore(b.createTextNode(S.exec(i)[0]),m.firstChild),i=m.childNodes}}else i=b.createTextNode(i);i.nodeType?g.push(i):g=d.merge(g,i)}if(e)for(h=0;g[h];h++)!f||!d.nodeName(g[h],"script")||g[h].type&&g[h].type.toLowerCase()!=="text/javascript"?(g[h].nodeType===1&&g.splice.apply(g,[h+1,0].concat(d.makeArray(g[h].getElementsByTagName("script")))),e.appendChild(g[h])):f.push(g[h].parentNode?g[h].parentNode.removeChild(g[h]):g[h]);return g},cleanData:function(a){var b,c,e=d.cache,f=d.expando,g=d.event.special,h=d.support.deleteExpando;for(var i=0,j;(j=a[i])!=null;i++){if(j.nodeName&&d.noData[j.nodeName.toLowerCase()])continue;c=j[d.expando];if(c){b=e[c]&&e[c][f];if(b&&b.events){for(var k in b.events)g[k]?d.event.remove(j,k):d.removeEvent(j,k,b.handle);b.handle&&(b.handle.elem=null)}h?delete j[d.expando]:j.removeAttribute&&j.removeAttribute(d.expando),delete e[c]}}}});var bd=/alpha\([^)]*\)/i,be=/opacity=([^)]*)/,bf=/-([a-z])/ig,bg=/([A-Z]|^ms)/g,bh=/^-?\d+(?:px)?$/i,bi=/^-?\d/,bj={position:"absolute",visibility:"hidden",display:"block"},bk=["Left","Right"],bl=["Top","Bottom"],bm,bn,bo,bp=function(a,b){return b.toUpperCase()};d.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return d.access(this,a,c,!0,function(a,c,e){return e!==b?d.style(a,c,e):d.css(a,c)})},d.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bm(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{zIndex:!0,fontWeight:!0,opacity:!0,zoom:!0,lineHeight:!0},cssProps:{"float":d.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,e,f){if(a&&a.nodeType!==3&&a.nodeType!==8&&a.style){var g,h=d.camelCase(c),i=a.style,j=d.cssHooks[h];c=d.cssProps[h]||h;if(e===b){if(j&&"get"in j&&(g=j.get(a,!1,f))!==b)return g;return i[c]}if(typeof e==="number"&&isNaN(e)||e==null)return;typeof e==="number"&&!d.cssNumber[h]&&(e+="px");if(!j||!("set"in j)||(e=j.set(a,e))!==b)try{i[c]=e}catch(k){}}},css:function(a,c,e){var f,g=d.camelCase(c),h=d.cssHooks[g];c=d.cssProps[g]||g;if(h&&"get"in h&&(f=h.get(a,!0,e))!==b)return f;if(bm)return bm(a,c,g)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]},camelCase:function(a){return a.replace(bf,bp)}}),d.curCSS=d.css,d.each(["height","width"],function(a,b){d.cssHooks[b]={get:function(a,c,e){var f;if(c){a.offsetWidth!==0?f=bq(a,b,e):d.swap(a,bj,function(){f=bq(a,b,e)});if(f<=0){f=bm(a,b,b),f==="0px"&&bo&&(f=bo(a,b,b));if(f!=null)return f===""||f==="auto"?"0px":f}if(f<0||f==null){f=a.style[b];return f===""||f==="auto"?"0px":f}return typeof f==="string"?f:f+"px"}},set:function(a,b){if(!bh.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),d.support.opacity||(d.cssHooks.opacity={get:function(a,b){return be.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style;c.zoom=1;var e=d.isNaN(b)?"":"alpha(opacity="+b*100+")",f=c.filter||"";c.filter=bd.test(f)?f.replace(bd,e):c.filter+" "+e}}),d(function(){d.support.reliableMarginRight||(d.cssHooks.marginRight={get:function(a,b){var c;d.swap(a,{display:"inline-block"},function(){b?c=bm(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bn=function(a,c,e){var f,g,h;e=e.replace(bg,"-$1").toLowerCase();if(!(g=a.ownerDocument.defaultView))return b;if(h=g.getComputedStyle(a,null))f=h.getPropertyValue(e),f===""&&!d.contains(a.ownerDocument.documentElement,a)&&(f=d.style(a,e));return f}),c.documentElement.currentStyle&&(bo=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bh.test(d)&&bi.test(d)&&(c=f.left,e&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":d||0,d=f.pixelLeft+"px",f.left=c,e&&(a.runtimeStyle.left=e));return d===""?"auto":d}),bm=bn||bo,d.expr&&d.expr.filters&&(d.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!d.support.reliableHiddenOffsets&&(a.style.display||d.css(a,"display"))==="none"},d.expr.filters.visible=function(a){return!d.expr.filters.hidden(a)});var br=/%20/g,bs=/\[\]$/,bt=/\r?\n/g,bu=/#.*$/,bv=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bw=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bx=/^(?:about|app|app\-storage|.+\-extension|file|widget):$/,by=/^(?:GET|HEAD)$/,bz=/^\/\//,bA=/\?/,bB=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bC=/^(?:select|textarea)/i,bD=/\s+/,bE=/([?&])_=[^&]*/,bF=/(^|\-)([a-z])/g,bG=function(a,b,c){return b+c.toUpperCase()},bH=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bI=d.fn.load,bJ={},bK={},bL,bM;try{bL=c.location.href}catch(bN){bL=c.createElement("a"),bL.href="",bL=bL.href}bM=bH.exec(bL.toLowerCase())||[],d.fn.extend({load:function(a,c,e){if(typeof a!=="string"&&bI)return bI.apply(this,arguments);if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var g=a.slice(f,a.length);a=a.slice(0,f)}var h="GET";c&&(d.isFunction(c)?(e=c,c=b):typeof c==="object"&&(c=d.param(c,d.ajaxSettings.traditional),h="POST"));var i=this;d.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?d("<div>").append(c.replace(bB,"")).find(g):c)),e&&i.each(e,[c,b,a])}});return this},serialize:function(){return d.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?d.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bC.test(this.nodeName)||bw.test(this.type))}).map(function(a,b){var c=d(this).val();return c==null?null:d.isArray(c)?d.map(c,function(a,c){return{name:b.name,value:a.replace(bt,"\r\n")}}):{name:b.name,value:c.replace(bt,"\r\n")}}).get()}}),d.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){d.fn[b]=function(a){return this.bind(b,a)}}),d.each(["get","post"],function(a,c){d[c]=function(a,e,f,g){d.isFunction(e)&&(g=g||f,f=e,e=b);return d.ajax({type:c,url:a,data:e,success:f,dataType:g})}}),d.extend({getScript:function(a,c){return d.get(a,b,c,"script")},getJSON:function(a,b,c){return d.get(a,b,c,"json")},ajaxSetup:function(a,b){b?d.extend(!0,a,d.ajaxSettings,b):(b=a,a=d.extend(!0,d.ajaxSettings,b));for(var c in {context:1,url:1})c in b?a[c]=b[c]:c in d.ajaxSettings&&(a[c]=d.ajaxSettings[c]);return a},ajaxSettings:{url:bL,isLocal:bx.test(bM[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":"*/*"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":d.parseJSON,"text xml":d.parseXML}},ajaxPrefilter:bO(bJ),ajaxTransport:bO(bK),ajax:function(a,c){function v(a,c,l,n){if(r!==2){r=2,p&&clearTimeout(p),o=b,m=n||"",u.readyState=a?4:0;var q,t,v,w=l?bR(e,u,l):b,x,y;if(a>=200&&a<300||a===304){if(e.ifModified){if(x=u.getResponseHeader("Last-Modified"))d.lastModified[k]=x;if(y=u.getResponseHeader("Etag"))d.etag[k]=y}if(a===304)c="notmodified",q=!0;else try{t=bS(e,w),c="success",q=!0}catch(z){c="parsererror",v=z}}else{v=c;if(!c||a)c="error",a<0&&(a=0)}u.status=a,u.statusText=c,q?h.resolveWith(f,[t,c,u]):h.rejectWith(f,[u,c,v]),u.statusCode(j),j=b,s&&g.trigger("ajax"+(q?"Success":"Error"),[u,e,q?t:v]),i.resolveWith(f,[u,c]),s&&(g.trigger("ajaxComplete",[u,e]),--d.active||d.event.trigger("ajaxStop"))}}typeof a==="object"&&(c=a,a=b),c=c||{};var e=d.ajaxSetup({},c),f=e.context||e,g=f!==e&&(f.nodeType||f instanceof d)?d(f):d.event,h=d.Deferred(),i=d._Deferred(),j=e.statusCode||{},k,l={},m,n,o,p,q,r=0,s,t,u={readyState:0,setRequestHeader:function(a,b){r||(l[a.toLowerCase().replace(bF,bG)]=b);return this},getAllResponseHeaders:function(){return r===2?m:null},getResponseHeader:function(a){var c;if(r===2){if(!n){n={};while(c=bv.exec(m))n[c[1].toLowerCase()]=c[2]}c=n[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){r||(e.mimeType=a);return this},abort:function(a){a=a||"abort",o&&o.abort(a),v(0,a);return this}};h.promise(u),u.success=u.done,u.error=u.fail,u.complete=i.done,u.statusCode=function(a){if(a){var b;if(r<2)for(b in a)j[b]=[j[b],a[b]];else b=a[u.status],u.then(b,b)}return this},e.url=((a||e.url)+"").replace(bu,"").replace(bz,bM[1]+"//"),e.dataTypes=d.trim(e.dataType||"*").toLowerCase().split(bD),e.crossDomain==null&&(q=bH.exec(e.url.toLowerCase()),e.crossDomain=q&&(q[1]!=bM[1]||q[2]!=bM[2]||(q[3]||(q[1]==="http:"?80:443))!=(bM[3]||(bM[1]==="http:"?80:443)))),e.data&&e.processData&&typeof e.data!=="string"&&(e.data=d.param(e.data,e.traditional)),bP(bJ,e,c,u);if(r===2)return!1;s=e.global,e.type=e.type.toUpperCase(),e.hasContent=!by.test(e.type),s&&d.active++===0&&d.event.trigger("ajaxStart");if(!e.hasContent){e.data&&(e.url+=(bA.test(e.url)?"&":"?")+e.data),k=e.url;if(e.cache===!1){var w=d.now(),x=e.url.replace(bE,"$1_="+w);e.url=x+(x===e.url?(bA.test(e.url)?"&":"?")+"_="+w:"")}}if(e.data&&e.hasContent&&e.contentType!==!1||c.contentType)l["Content-Type"]=e.contentType;e.ifModified&&(k=k||e.url,d.lastModified[k]&&(l["If-Modified-Since"]=d.lastModified[k]),d.etag[k]&&(l["If-None-Match"]=d.etag[k])),l.Accept=e.dataTypes[0]&&e.accepts[e.dataTypes[0]]?e.accepts[e.dataTypes[0]]+(e.dataTypes[0]!=="*"?", */*; q=0.01":""):e.accepts["*"];for(t in e.headers)u.setRequestHeader(t,e.headers[t]);if(e.beforeSend&&(e.beforeSend.call(f,u,e)===!1||r===2)){u.abort();return!1}for(t in {success:1,error:1,complete:1})u[t](e[t]);o=bP(bK,e,c,u);if(o){u.readyState=1,s&&g.trigger("ajaxSend",[u,e]),e.async&&e.timeout>0&&(p=setTimeout(function(){u.abort("timeout")},e.timeout));try{r=1,o.send(l,v)}catch(y){status<2?v(-1,y):d.error(y)}}else v(-1,"No Transport");return u},param:function(a,c){var e=[],f=function(a,b){b=d.isFunction(b)?b():b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=d.ajaxSettings.traditional);if(d.isArray(a)||a.jquery&&!d.isPlainObject(a))d.each(a,function(){f(this.name,this.value)});else for(var g in a)bQ(g,a[g],c,f);return e.join("&").replace(br,"+")}}),d.extend({active:0,lastModified:{},etag:{}});var bT=d.now(),bU=/(\=)\?(&|$)|\?\?/i;d.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return d.expando+"_"+bT++}}),d.ajaxPrefilter("json jsonp",function(b,c,e){var f=typeof b.data==="string";if(b.dataTypes[0]==="jsonp"||c.jsonpCallback||c.jsonp!=null||b.jsonp!==!1&&(bU.test(b.url)||f&&bU.test(b.data))){var g,h=b.jsonpCallback=d.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2",m=function(){a[h]=i,g&&d.isFunction(i)&&a[h](g[0])};b.jsonp!==!1&&(j=j.replace(bU,l),b.url===j&&(f&&(k=k.replace(bU,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},e.then(m,m),b.converters["script json"]=function(){g||d.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),d.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){d.globalEval(a);return a}}}),d.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),d.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var bV=d.now(),bW,bX;d.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&bZ()||b$()}:bZ,bX=d.ajaxSettings.xhr(),d.support.ajax=!!bX,d.support.cors=bX&&"withCredentials"in bX,bX=b,d.support.ajax&&d.ajaxTransport(function(a){if(!a.crossDomain||d.support.cors){var c;return{send:function(e,f){var g=a.xhr(),h,i;a.username?g.open(a.type,a.url,a.async,a.username,a.password):g.open(a.type,a.url,a.async);if(a.xhrFields)for(i in a.xhrFields)g[i]=a.xhrFields[i];a.mimeType&&g.overrideMimeType&&g.overrideMimeType(a.mimeType),!a.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(i in e)g.setRequestHeader(i,e[i])}catch(j){}g.send(a.hasContent&&a.data||null),c=function(e,i){var j,k,l,m,n;try{if(c&&(i||g.readyState===4)){c=b,h&&(g.onreadystatechange=d.noop,delete bW[h]);if(i)g.readyState!==4&&g.abort();else{j=g.status,l=g.getAllResponseHeaders(),m={},n=g.responseXML,n&&n.documentElement&&(m.xml=n),m.text=g.responseText;try{k=g.statusText}catch(o){k=""}j||!a.isLocal||a.crossDomain?j===1223&&(j=204):j=m.text?200:404}}}catch(p){i||f(-1,p)}m&&f(j,k,m,l)},a.async&&g.readyState!==4?(bW||(bW={},bY()),h=bV++,g.onreadystatechange=bW[h]=c):c()},abort:function(){c&&c(0,1)}}}});var b_={},ca=/^(?:toggle|show|hide)$/,cb=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cc,cd=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];d.fn.extend({show:function(a,b,c){var e,f;if(a||a===0)return this.animate(ce("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)e=this[g],f=e.style.display,!d._data(e,"olddisplay")&&f==="none"&&(f=e.style.display=""),f===""&&d.css(e,"display")==="none"&&d._data(e,"olddisplay",cf(e.nodeName));for(g=0;g<h;g++){e=this[g],f=e.style.display;if(f===""||f==="none")e.style.display=d._data(e,"olddisplay")||""}return this},hide:function(a,b,c){if(a||a===0)return this.animate(ce("hide",3),a,b,c);for(var e=0,f=this.length;e<f;e++){var g=d.css(this[e],"display");g!=="none"&&!d._data(this[e],"olddisplay")&&d._data(this[e],"olddisplay",g)}for(e=0;e<f;e++)this[e].style.display="none";return this},_toggle:d.fn.toggle,toggle:function(a,b,c){var e=typeof a==="boolean";d.isFunction(a)&&d.isFunction(b)?this._toggle.apply(this,arguments):a==null||e?this.each(function(){var b=e?a:d(this).is(":hidden");d(this)[b?"show":"hide"]()}):this.animate(ce("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,e){var f=d.speed(b,c,e);if(d.isEmptyObject(a))return this.each(f.complete);return this[f.queue===!1?"each":"queue"](function(){var b=d.extend({},f),c,e=this.nodeType===1,g=e&&d(this).is(":hidden"),h=this;for(c in a){var i=d.camelCase(c);c!==i&&(a[i]=a[c],delete a[c],c=i);if(a[c]==="hide"&&g||a[c]==="show"&&!g)return b.complete.call(this);if(e&&(c==="height"||c==="width")){b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(d.css(this,"display")==="inline"&&d.css(this,"float")==="none")if(d.support.inlineBlockNeedsLayout){var j=cf(this.nodeName);j==="inline"?this.style.display="inline-block":(this.style.display="inline",this.style.zoom=1)}else this.style.display="inline-block"}d.isArray(a[c])&&((b.specialEasing=b.specialEasing||{})[c]=a[c][1],a[c]=a[c][0])}b.overflow!=null&&(this.style.overflow="hidden"),b.curAnim=d.extend({},a),d.each(a,function(c,e){var f=new d.fx(h,b,c);if(ca.test(e))f[e==="toggle"?g?"show":"hide":e](a);else{var i=cb.exec(e),j=f.cur();if(i){var k=parseFloat(i[2]),l=i[3]||(d.cssNumber[c]?"":"px");l!=="px"&&(d.style(h,c,(k||1)+l),j=(k||1)/f.cur()*j,d.style(h,c,j+l)),i[1]&&(k=(i[1]==="-="?-1:1)*k+j),f.custom(j,k,l)}else f.custom(j,e,"")}});return!0})},stop:function(a,b){var c=d.timers;a&&this.queue([]),this.each(function(){for(var a=c.length-1;a>=0;a--)c[a].elem===this&&(b&&c[a](!0),c.splice(a,1))}),b||this.dequeue();return this}}),d.each({slideDown:ce("show",1),slideUp:ce("hide",1),slideToggle:ce("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){d.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),d.extend({speed:function(a,b,c){var e=a&&typeof a==="object"?d.extend({},a):{complete:c||!c&&b||d.isFunction(a)&&a,duration:a,easing:c&&b||b&&!d.isFunction(b)&&b};e.duration=d.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in d.fx.speeds?d.fx.speeds[e.duration]:d.fx.speeds._default,e.old=e.complete,e.complete=function(){e.queue!==!1&&d(this).dequeue(),d.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig||(b.orig={})}}),d.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(d.fx.step[this.prop]||d.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=d.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,b,c){function g(a){return e.step(a)}var e=this,f=d.fx;this.startTime=d.now(),this.start=a,this.end=b,this.unit=c||this.unit||(d.cssNumber[this.prop]?"":"px"),this.now=this.start,this.pos=this.state=0,g.elem=this.elem,g()&&d.timers.push(g)&&!cc&&(cc=setInterval(f.tick,f.interval))},show:function(){this.options.orig[this.prop]=d.style(this.elem,this.prop),this.options.show=!0,this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),d(this.elem).show()},hide:function(){this.options.orig[this.prop]=d.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b=d.now(),c=!0;if(a||b>=this.options.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),this.options.curAnim[this.prop]=!0;for(var e in this.options.curAnim)this.options.curAnim[e]!==!0&&(c=!1);if(c){if(this.options.overflow!=null&&!d.support.shrinkWrapBlocks){var f=this.elem,g=this.options;d.each(["","X","Y"],function(a,b){f.style["overflow"+b]=g.overflow[a]})}this.options.hide&&d(this.elem).hide();if(this.options.hide||this.options.show)for(var h in this.options.curAnim)d.style(this.elem,h,this.options.orig[h]);this.options.complete.call(this.elem)}return!1}var i=b-this.startTime;this.state=i/this.options.duration;var j=this.options.specialEasing&&this.options.specialEasing[this.prop],k=this.options.easing||(d.easing.swing?"swing":"linear");this.pos=d.easing[j||k](this.state,i,0,1,this.options.duration),this.now=this.start+(this.end-this.start)*this.pos,this.update();return!0}},d.extend(d.fx,{tick:function(){var a=d.timers;for(var b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||d.fx.stop()},interval:13,stop:function(){clearInterval(cc),cc=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){d.style(a.elem,"opacity",a.now)},_default:function(a){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:a.elem[a.prop]=a.now}}}),d.expr&&d.expr.filters&&(d.expr.filters.animated=function(a){return d.grep(d.timers,function(b){return a===b.elem}).length});var cg=/^t(?:able|d|h)$/i,ch=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?d.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){d.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return d.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,g=f.documentElement;if(!c||!d.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=f.body,i=ci(f),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||d.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||d.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:d.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){d.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return d.offset.bodyOffset(b);d.offset.initialize();var c,e=b.offsetParent,f=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(d.offset.supportsFixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===e&&(l+=b.offsetTop,m+=b.offsetLeft,d.offset.doesNotAddBorder&&(!d.offset.doesAddBorderForTableAndCells||!cg.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),f=e,e=b.offsetParent),d.offset.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;d.offset.supportsFixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},d.offset={initialize:function(){var a=c.body,b=c.createElement("div"),e,f,g,h,i=parseFloat(d.css(a,"marginTop"))||0,j="<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>";d.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"}),b.innerHTML=j,a.insertBefore(b,a.firstChild),e=b.firstChild,f=e.firstChild,h=e.nextSibling.firstChild.firstChild,this.doesNotAddBorder=f.offsetTop!==5,this.doesAddBorderForTableAndCells=h.offsetTop===5,f.style.position="fixed",f.style.top="20px",this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15,f.style.position=f.style.top="",e.style.overflow="hidden",e.style.position="relative",this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5,this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i,a.removeChild(b),d.offset.initialize=d.noop},bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;d.offset.initialize(),d.offset.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(d.css(a,"marginTop"))||0,c+=parseFloat(d.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var e=d.css(a,"position");e==="static"&&(a.style.position="relative");var f=d(a),g=f.offset(),h=d.css(a,"top"),i=d.css(a,"left"),j=(e==="absolute"||e==="fixed")&&d.inArray("auto",[h,i])>-1,k={},l={},m,n;j&&(l=f.position()),m=j?l.top:parseInt(h,10)||0,n=j?l.left:parseInt(i,10)||0,d.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):f.css(k)}},d.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),e=ch.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(d.css(a,"marginTop"))||0,c.left-=parseFloat(d.css(a,"marginLeft"))||0,e.top+=parseFloat(d.css(b[0],"borderTopWidth"))||0,e.left+=parseFloat(d.css(b[0],"borderLeftWidth"))||0;return{top:c.top-e.top,left:c.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&(!ch.test(a.nodeName)&&d.css(a,"position")==="static"))a=a.offsetParent;return a})}}),d.each(["Left","Top"],function(a,c){var e="scroll"+c;d.fn[e]=function(c){var f=this[0],g;if(!f)return null;if(c!==b)return this.each(function(){g=ci(this),g?g.scrollTo(a?d(g).scrollLeft():c,a?c:d(g).scrollTop()):this[e]=c});g=ci(f);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:d.support.boxModel&&g.document.documentElement[e]||g.document.body[e]:f[e]}}),d.each(["Height","Width"],function(a,c){var e=c.toLowerCase();d.fn["inner"+c]=function(){return this[0]?parseFloat(d.css(this[0],e,"padding")):null},d.fn["outer"+c]=function(a){return this[0]?parseFloat(d.css(this[0],e,a?"margin":"border")):null},d.fn[e]=function(a){var f=this[0];if(!f)return a==null?null:this;if(d.isFunction(a))return this.each(function(b){var c=d(this);c[e](a.call(this,b,c[e]()))});if(d.isWindow(f)){var g=f.document.documentElement["client"+c];return f.document.compatMode==="CSS1Compat"&&g||f.document.body["client"+c]||g}if(f.nodeType===9)return Math.max(f.documentElement["client"+c],f.body["scroll"+c],f.documentElement["scroll"+c],f.body["offset"+c],f.documentElement["offset"+c]);if(a===b){var h=d.css(f,e),i=parseFloat(h);return d.isNaN(i)?h:i}return this.css(e,typeof a==="string"?a:a+"px")}}),a.jQuery=a.$=d})(window);
ajax/libs/forerunnerdb/1.3.603/fdb-legacy.js
dhenson02/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), CollectionGroup = _dereq_('../lib/CollectionGroup'), View = _dereq_('../lib/View'), Highchart = _dereq_('../lib/Highchart'), Persist = _dereq_('../lib/Persist'), Document = _dereq_('../lib/Document'), Overview = _dereq_('../lib/Overview'), OldView = _dereq_('../lib/OldView'), OldViewBind = _dereq_('../lib/OldView.Bind'), Grid = _dereq_('../lib/Grid'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/CollectionGroup":5,"../lib/Core":6,"../lib/Document":9,"../lib/Grid":11,"../lib/Highchart":12,"../lib/OldView":29,"../lib/OldView.Bind":28,"../lib/Overview":32,"../lib/Persist":34,"../lib/View":40}],2:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver; /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; this._keyArr = sharedPathSolver.parse(orderBy, true); }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); sharedPathSolver = new Path(); /** * Gets / sets the primary key used by the active bucket. * @returns {String} The current primary key. */ Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof sharedPathSolver.get(obj, sortType.path); if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.value === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.value === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += sharedPathSolver.get(obj, sortType.path); } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Path":33,"./Shared":39}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver = new Path(); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) { this._store = []; this._keys = []; if (primaryKey !== undefined) { this.primaryKey(primaryKey); } if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'primaryKey'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (this.debug()) { console.log('Setting index', index, sharedPathSolver.parse(index, true)); } // Convert the index object to an array of key val objects this.keys(sharedPathSolver.parse(index, true)); } return this.$super.call(this, index); }); /** * Remove all data from the binary tree. */ BinaryTree.prototype.clear = function () { delete this._data; delete this._left; delete this._right; this._store = []; }; /** * Sets this node's data object. All further inserted documents that * match this node's key and value will be pushed via the push() * method into the this._store array. When deciding if a new data * should be created left, right or middle (pushed) of this node the * new data is checked against the data set via this method. * @param val * @returns {*} */ BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.value === 1) { result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (this.debug()) { console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result); } if (result !== 0) { if (this.debug()) { console.log('Retuning result %d', result); } return result; } } if (this.debug()) { console.log('Retuning result %d', result); } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.path]; } return hash;*/ return obj[this._keys[0].path]; }; /** * Removes (deletes reference to) either left or right child if the passed * node matches one of them. * @param {BinaryTree} node The node to remove. */ BinaryTree.prototype.removeChildNode = function (node) { if (this._left === node) { // Remove left delete this._left; } else if (this._right === node) { // Remove right delete this._right; } }; /** * Returns the branch this node matches (left or right). * @param node * @returns {String} */ BinaryTree.prototype.nodeBranch = function (node) { if (this._left === node) { return 'left'; } else if (this._right === node) { return 'right'; } }; /** * Inserts a document into the binary tree. * @param data * @returns {*} */ BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (this.debug()) { console.log('Inserting', data); } if (!this._data) { if (this.debug()) { console.log('Node has no data, setting data', data); } // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { if (this.debug()) { console.log('Data is equal (currrent, new)', this._data, data); } //this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } if (result === -1) { if (this.debug()) { console.log('Data is greater (currrent, new)', this._data, data); } // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._right._parent = this; } return true; } if (result === 1) { if (this.debug()) { console.log('Data is less (currrent, new)', this._data, data); } // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } return false; }; BinaryTree.prototype.remove = function (data) { var pk = this.primaryKey(), result, removed, i; if (data instanceof Array) { // Insert array of data removed = []; for (i = 0; i < data.length; i++) { if (this.remove(data[i])) { removed.push(data[i]); } } return removed; } if (this.debug()) { console.log('Removing', data); } if (this._data[pk] === data[pk]) { // Remove this node return this._remove(this); } // Compare the data to work out which branch to send the remove command down result = this._compareFunc(this._data, data); if (result === -1 && this._right) { return this._right.remove(data); } if (result === 1 && this._left) { return this._left.remove(data); } return false; }; BinaryTree.prototype._remove = function (node) { var leftNode, rightNode; if (this._left) { // Backup branch data leftNode = this._left; rightNode = this._right; // Copy data from left node this._left = leftNode._left; this._right = leftNode._right; this._data = leftNode._data; this._store = leftNode._store; if (rightNode) { // Attach the rightNode data to the right-most node // of the leftNode leftNode.rightMost()._right = rightNode; } } else if (this._right) { // Backup branch data rightNode = this._right; // Copy data from right node this._left = rightNode._left; this._right = rightNode._right; this._data = rightNode._data; this._store = rightNode._store; } else { this.clear(); } return true; }; BinaryTree.prototype.leftMost = function () { if (!this._left) { return this; } else { return this._left.leftMost(); } }; BinaryTree.prototype.rightMost = function () { if (!this._right) { return this; } else { return this._right.rightMost(); } }; /** * Searches the binary tree for all matching documents based on the data * passed (query). * @param data * @param options * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visited === undefined) { resultArr._visited = 0; } resultArr._visited++; result = this.sortAsc(thisDataPathVal, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":33,"./Shared":39}],4:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Crc, Overload, ReactorIO, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); sharedPathSolver = new Path(); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. */ Shared.synthesize(Collection.prototype, 'cappedSize'); Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', keyName, {oldData: oldKey}); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = new Date(); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = this.jStringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } // Handle transform update = this.transformIn(update); var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: updated }, options); op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback(false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback(resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback(resultObj); } this._onChange(); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); self.chainSend('insert', doc, {index: index}); //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = this.jStringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = this.jStringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback('Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearchQuery, joinSearchOptions, joinMulti, joinRequire, joinFindResults, joinFindResult, joinItem, joinPrefix, joinMatchData, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, l, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinCollectionName]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB if (joinCollection[joinCollectionName]) { joinCollectionInstance = joinCollection[joinCollectionName]; } else { joinCollectionInstance = this._db.collection(joinCollectionName); } // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self._resolveDynamicQuery(joinMatchData.$query, resultArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatchData, resultArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultCollectionName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = resultArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; Collection.prototype._resolveDynamicQuery = function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = new Path(query.substr(3, query.length - 3)).value(item); } else { pathResult = new Path(query).value(item); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self._resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ /*Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; };*/ /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents that matches * the subDocQuery parameter. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; case '2d': index = new Index2d(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); } else { self.insert(packet.data); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":7,"./Index2d":13,"./IndexBinaryTree":14,"./IndexHashMap":15,"./KeyValueStore":16,"./Metrics":17,"./Overload":31,"./Path":33,"./ReactorIO":37,"./Shared":39}],5:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {Name=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Remove old data this._data.remove(chainPacket.options.oldData); // Add new data this._data.insert(chainPacket.data); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Add new data this._data.insert(chainPacket.data); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); delete this._listeners; if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; Db.prototype.collectionGroup = function (collectionGroupName) { if (collectionGroupName) { // Handle being passed an instance if (collectionGroupName instanceof CollectionGroup) { return collectionGroupName; } this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this); return this._collectionGroup[collectionGroupName]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":4,"./Shared":39}],6:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":8,"./Metrics.js":17,"./Overload":31,"./Shared":39}],7:[function(_dereq_,module,exports){ "use strict"; /** * @mixin */ var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],8:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":17,"./Overload":31,"./Shared":39}],9:[function(_dereq_,module,exports){ "use strict"; // TODO: Remove the _update* methods because we are already mixing them // TODO: in now via Mixin.Updating and update autobind to extend the _update* // TODO: methods like we already do with collection var Shared, Collection, Db; Shared = _dereq_('./Shared'); /** * Creates a new Document instance. Documents allow you to create individual * objects that can have standard ForerunnerDB CRUD operations run against * them, as well as data-binding if the AutoBind module is included in your * project. * @name Document * @class Document * @constructor */ var FdbDocument = function () { this.init.apply(this, arguments); }; FdbDocument.prototype.init = function (name) { this._name = name; this._data = {}; }; Shared.addModule('Document', FdbDocument); Shared.mixin(FdbDocument.prototype, 'Mixin.Common'); Shared.mixin(FdbDocument.prototype, 'Mixin.Events'); Shared.mixin(FdbDocument.prototype, 'Mixin.ChainReactor'); Shared.mixin(FdbDocument.prototype, 'Mixin.Constants'); Shared.mixin(FdbDocument.prototype, 'Mixin.Triggers'); Shared.mixin(FdbDocument.prototype, 'Mixin.Matching'); Shared.mixin(FdbDocument.prototype, 'Mixin.Updating'); Shared.mixin(FdbDocument.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; /** * Gets / sets the current state. * @func state * @memberof Document * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'state'); /** * Gets / sets the db instance this class instance belongs to. * @func db * @memberof Document * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'db'); /** * Gets / sets the document name. * @func name * @memberof Document * @param {String=} val The name to assign * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'name'); /** * Sets the data for the document. * @func setData * @memberof Document * @param data * @param options * @returns {Document} */ FdbDocument.prototype.setData = function (data, options) { var i, $unset; if (data) { options = options || { $decouple: true }; if (options && options.$decouple === true) { data = this.decouple(data); } if (this._linked) { $unset = {}; // Remove keys that don't exist in the new data from the current object for (i in this._data) { if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) { // Check if existing data has key if (data[i] === undefined) { // Add property name to those to unset $unset[i] = 1; } } } data.$unset = $unset; // Now update the object with new data this.updateObject(this._data, data, {}); } else { // Straight data assignment this._data = data; } this.deferEmit('change', {type: 'setData', data: this.decouple(this._data)}); } return this; }; /** * Gets the document's data returned as a single object. * @func find * @memberof Document * @param {Object} query The query object - currently unused, just * provide a blank object e.g. {} * @param {Object=} options An options object. * @returns {Object} The document's data object. */ FdbDocument.prototype.find = function (query, options) { var result; if (options && options.$decouple === false) { result = this._data; } else { result = this.decouple(this._data); } return result; }; /** * Modifies the document. This will update the document with the data held in 'update'. * @func update * @memberof Document * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ FdbDocument.prototype.update = function (query, update, options) { var result = this.updateObject(this._data, update, query, options); if (result) { this.deferEmit('change', {type: 'update', data: this.decouple(this._data)}); } }; /** * Internal method for document updating. * @func updateObject * @memberof Document * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ FdbDocument.prototype.updateObject = Collection.prototype.updateObject; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @func _isPositionalKey * @memberof Document * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ FdbDocument.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Updates a property on an object depending on if the collection is * currently running data-binding or not. * @func _updateProperty * @memberof Document * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ FdbDocument.prototype._updateProperty = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, val); if (this.debug()) { console.log(this.logIdentifier() + ' Setting data-bound document property "' + prop + '"'); } } else { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } } }; /** * Increments a value for a property on a document by the passed number. * @func _updateIncrement * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ FdbDocument.prototype._updateIncrement = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, doc[prop] + val); } else { doc[prop] += val; } }; /** * Changes the index of an item in the passed array. * @func _updateSpliceMove * @memberof Document * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ FdbDocument.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) { if (this._linked) { window.jQuery.observable(arr).move(indexFrom, indexTo); if (this.debug()) { console.log(this.logIdentifier() + ' Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } } else { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } } }; /** * Inserts an item into the passed array at the specified index. * @func _updateSplicePush * @memberof Document * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ FdbDocument.prototype._updateSplicePush = function (arr, index, doc) { if (arr.length > index) { if (this._linked) { window.jQuery.observable(arr).insert(index, doc); } else { arr.splice(index, 0, doc); } } else { if (this._linked) { window.jQuery.observable(arr).insert(doc); } else { arr.push(doc); } } }; /** * Inserts an item at the end of an array. * @func _updatePush * @memberof Document * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ FdbDocument.prototype._updatePush = function (arr, doc) { if (this._linked) { window.jQuery.observable(arr).insert(doc); } else { arr.push(doc); } }; /** * Removes an item from the passed array. * @func _updatePull * @memberof Document * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ FdbDocument.prototype._updatePull = function (arr, index) { if (this._linked) { window.jQuery.observable(arr).remove(index); } else { arr.splice(index, 1); } }; /** * Multiplies a value for a property on a document by the passed number. * @func _updateMultiply * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ FdbDocument.prototype._updateMultiply = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, doc[prop] * val); } else { doc[prop] *= val; } }; /** * Renames a property on a document to the passed property. * @func _updateRename * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ FdbDocument.prototype._updateRename = function (doc, prop, val) { var existingVal = doc[prop]; if (this._linked) { window.jQuery.observable(doc).setProperty(val, existingVal); window.jQuery.observable(doc).removeProperty(prop); } else { doc[val] = existingVal; delete doc[prop]; } }; /** * Deletes a property on a document. * @func _updateUnset * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ FdbDocument.prototype._updateUnset = function (doc, prop) { if (this._linked) { window.jQuery.observable(doc).removeProperty(prop); } else { delete doc[prop]; } }; /** * Drops the document. * @func drop * @memberof Document * @returns {boolean} True if successful, false if not. */ FdbDocument.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._db && this._name) { if (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); if (callback) { callback(false, true); } delete this._listeners; return true; } } } else { return true; } return false; }; /** * Creates a new document instance. * @func document * @memberof Db * @param {String} documentName The name of the document to create. * @returns {*} */ Db.prototype.document = function (documentName) { if (documentName) { // Handle being passed an instance if (documentName instanceof FdbDocument) { if (documentName.state() !== 'droppped') { return documentName; } else { documentName = documentName.name(); } } this._document = this._document || {}; this._document[documentName] = this._document[documentName] || new FdbDocument(documentName).db(this); return this._document[documentName]; } else { // Return an object of document data return this._document; } }; /** * Returns an array of documents the DB currently has. * @func documents * @memberof Db * @returns {Array} An array of objects containing details of each document * the database is currently managing. */ Db.prototype.documents = function () { var arr = [], item, i; for (i in this._document) { if (this._document.hasOwnProperty(i)) { item = this._document[i]; arr.push({ name: i, linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Document'); module.exports = FdbDocument; },{"./Collection":4,"./Shared":39}],10:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - [email protected] "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders; bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to longitude/latitude. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { latitude: lat, longitude: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; module.exports = GeoHash; },{}],11:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, View, CollectionInit, DbInit, ReactorIO; //Shared = ForerunnerDB.shared; Shared = _dereq_('./Shared'); /** * Creates a new grid instance. * @name Grid * @class Grid * @param {String} selector jQuery selector. * @param {String} template The template selector. * @param {Object=} options The options object to apply to the grid. * @constructor */ var Grid = function (selector, template, options) { this.init.apply(this, arguments); }; Grid.prototype.init = function (selector, template, options) { var self = this; this._selector = selector; this._template = template; this._options = options || {}; this._debug = {}; this._id = this.objectId(); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; }; Shared.addModule('Grid', Grid); Shared.mixin(Grid.prototype, 'Mixin.Common'); Shared.mixin(Grid.prototype, 'Mixin.ChainReactor'); Shared.mixin(Grid.prototype, 'Mixin.Constants'); Shared.mixin(Grid.prototype, 'Mixin.Triggers'); Shared.mixin(Grid.prototype, 'Mixin.Events'); Shared.mixin(Grid.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); View = _dereq_('./View'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @func state * @memberof Grid * @param {String=} val The name of the state to set. * @returns {Grid} */ Shared.synthesize(Grid.prototype, 'state'); /** * Gets / sets the current name. * @func name * @memberof Grid * @param {String=} val The name to set. * @returns {Grid} */ Shared.synthesize(Grid.prototype, 'name'); /** * Executes an insert against the grid's underlying data-source. * @func insert * @memberof Grid */ Grid.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the grid's underlying data-source. * @func update * @memberof Grid */ Grid.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the grid's underlying data-source. * @func updateById * @memberof Grid */ Grid.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the grid's underlying data-source. * @func remove * @memberof Grid */ Grid.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Sets the collection from which the grid will assemble its data. * @func from * @memberof Grid * @param {Collection} collection The collection to use to assemble grid data. * @returns {Grid} */ Grid.prototype.from = function (collection) { //var self = this; if (collection !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); this._from._removeGrid(this); } if (typeof(collection) === 'string') { collection = this._db.collection(collection); } this._from = collection; this._from.on('drop', this._collectionDroppedWrap); this.refresh(); } return this; }; /** * Gets / sets the db instance this class instance belongs to. * @func db * @memberof Grid * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Grid.prototype, 'db', function (db) { if (db) { // Apply the same debug settings this.debug(db.debug()); } return this.$super.apply(this, arguments); }); Grid.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from grid delete this._from; } }; /** * Drops a grid and all it's stored data from the database. * @func drop * @memberof Grid * @returns {boolean} True on success, false on failure. */ Grid.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { // Remove data-binding this._from.unlink(this._selector, this.template()); // Kill listeners and references this._from.off('drop', this._collectionDroppedWrap); this._from._removeGrid(this); if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping grid ' + this._selector); } this._state = 'dropped'; if (this._db && this._selector) { delete this._db._grid[this._selector]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._selector; delete this._template; delete this._from; delete this._db; delete this._listeners; return true; } } else { return true; } return false; }; /** * Gets / sets the grid's HTML template to use when rendering. * @func template * @memberof Grid * @param {Selector} template The template's jQuery selector. * @returns {*} */ Grid.prototype.template = function (template) { if (template !== undefined) { this._template = template; return this; } return this._template; }; Grid.prototype._sortGridClick = function (e) { var elem = window.jQuery(e.currentTarget), sortColText = elem.attr('data-grid-sort') || '', sortColDir = parseInt((elem.attr('data-grid-dir') || "-1"), 10) === -1 ? 1 : -1, sortCols = sortColText.split(','), sortObj = {}, i; // Remove all grid sort tags from the grid window.jQuery(this._selector).find('[data-grid-dir]').removeAttr('data-grid-dir'); // Flip the sort direction elem.attr('data-grid-dir', sortColDir); for (i = 0; i < sortCols.length; i++) { sortObj[sortCols] = sortColDir; } Shared.mixin(sortObj, this._options.$orderBy); this._from.orderBy(sortObj); this.emit('sort', sortObj); }; /** * Refreshes the grid data such as ordering etc. * @func refresh * @memberof Grid */ Grid.prototype.refresh = function () { if (this._from) { if (this._from.link) { var self = this, elem = window.jQuery(this._selector), sortClickListener = function () { self._sortGridClick.apply(self, arguments); }; // Clear the container elem.html(''); if (self._from.orderBy) { // Remove listeners elem.off('click', '[data-grid-sort]', sortClickListener); } if (self._from.query) { // Remove listeners elem.off('click', '[data-grid-filter]', sortClickListener ); } // Set wrap name if none is provided self._options.$wrap = self._options.$wrap || 'gridRow'; // Auto-bind the data to the grid template self._from.link(self._selector, self.template(), self._options); // Check if the data source (collection or view) has an // orderBy method (usually only views) and if so activate // the sorting system if (self._from.orderBy) { // Listen for sort requests elem.on('click', '[data-grid-sort]', sortClickListener); } if (self._from.query) { // Listen for filter requests var queryObj = {}; elem.find('[data-grid-filter]').each(function (index, filterElem) { filterElem = window.jQuery(filterElem); var filterField = filterElem.attr('data-grid-filter'), filterVarType = filterElem.attr('data-grid-vartype'), filterSort = {}, title = filterElem.html(), dropDownButton, dropDownMenu, template, filterQuery, filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField); filterSort[filterField] = 1; filterQuery = { $distinct: filterSort }; filterView .query(filterQuery) .orderBy(filterSort) .from(self._from._from); template = [ '<div class="dropdown" id="' + self._id + '_' + filterField + '">', '<button class="btn btn-default dropdown-toggle" type="button" id="' + self._id + '_' + filterField + '_dropdownButton" data-toggle="dropdown" aria-expanded="true">', title + ' <span class="caret"></span>', '</button>', '</div>' ]; dropDownButton = window.jQuery(template.join('')); dropDownMenu = window.jQuery('<ul class="dropdown-menu" role="menu" id="' + self._id + '_' + filterField + '_dropdownMenu"></ul>'); dropDownButton.append(dropDownMenu); filterElem.html(dropDownButton); // Data-link the underlying data to the grid filter drop-down filterView.link(dropDownMenu, { 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{:' + filterField + '}">', '<a role="menuitem" tabindex="-1">', '<input type="checkbox">&nbsp;{^{:' + filterField + '}}', '</a>', '</li>', '{{/for}}' ].join('') }, { $wrap: 'options' }); elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) { var elem = window.jQuery(this), query = filterView.query(), search = elem.val(); if (search) { query[filterField] = new RegExp(search, 'gi'); } else { delete query[filterField]; } filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) { // Clear search text box window.jQuery(this).parents('li').find('.gridFilterSearch').val(''); // Clear view query var query = filterView.query(); delete query[filterField]; filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) { e.stopPropagation(); var fieldValue, elem = $(this), checkbox = elem.find('input[type="checkbox"]'), checked, addMode = true, fieldInArr, liElem, i; // If the checkbox is not the one clicked on if (!window.jQuery(e.target).is('input')) { // Set checkbox to opposite of current value checkbox.prop('checked', !checkbox.prop('checked')); checked = checkbox.is(':checked'); } else { checkbox.prop('checked', checkbox.prop('checked')); checked = checkbox.is(':checked'); } liElem = window.jQuery(this); fieldValue = liElem.attr('data-val'); // Check if the selection is the "all" option if (fieldValue === '$all') { // Remove the field from the query delete queryObj[filterField]; // Clear all other checkboxes liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false); } else { // Clear the "all" checkbox liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false); // Check if the type needs casting switch (filterVarType) { case 'integer': fieldValue = parseInt(fieldValue, 10); break; case 'float': fieldValue = parseFloat(fieldValue); break; default: } // Check if the item exists already queryObj[filterField] = queryObj[filterField] || { $in: [] }; fieldInArr = queryObj[filterField].$in; for (i = 0; i < fieldInArr.length; i++) { if (fieldInArr[i] === fieldValue) { // Item already exists if (checked === false) { // Remove the item fieldInArr.splice(i, 1); } addMode = false; break; } } if (addMode && checked) { fieldInArr.push(fieldValue); } if (!fieldInArr.length) { // Remove the field from the query delete queryObj[filterField]; } } // Set the view query self._from.queryData(queryObj); if (self._from.pageFirst) { self._from.pageFirst(); } }); }); } self.emit('refresh'); } else { throw('Grid requires the AutoBind module in order to operate!'); } } return this; }; /** * Returns the number of documents currently in the grid. * @func count * @memberof Grid * @returns {Number} */ Grid.prototype.count = function () { return this._from.count(); }; /** * Creates a grid and assigns the collection as its data source. * @func grid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.grid = View.prototype.grid = function (selector, template, options) { if (this._db && this._db._grid ) { if (selector !== undefined) { if (template !== undefined) { if (!this._db._grid[selector]) { var grid = new Grid(selector, template, options) .db(this._db) .from(this); this._grid = this._grid || []; this._grid.push(grid); this._db._grid[selector] = grid; return grid; } else { throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector); } } return this._db._grid[selector]; } return this._db._grid; } }; /** * Removes a grid safely from the DOM. Must be called when grid is * no longer required / is being removed from DOM otherwise references * will stick around and cause memory leaks. * @func unGrid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) { var i, grid; if (this._db && this._db._grid ) { if (selector && template) { if (this._db._grid[selector]) { grid = this._db._grid[selector]; delete this._db._grid[selector]; return grid.drop(); } else { throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name); } } else { // No parameters passed, remove all grids from this module for (i in this._db._grid) { if (this._db._grid.hasOwnProperty(i)) { grid = this._db._grid[i]; delete this._db._grid[i]; grid.drop(); if (this.debug()) { console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"'); } } } this._db._grid = {}; } } }; /** * Adds a grid to the internal grid lookup. * @func _addGrid * @memberof Collection * @param {Grid} grid The grid to add. * @returns {Collection} * @private */ Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) { if (grid !== undefined) { this._grid = this._grid || []; this._grid.push(grid); } return this; }; /** * Removes a grid from the internal grid lookup. * @func _removeGrid * @memberof Collection * @param {Grid} grid The grid to remove. * @returns {Collection} * @private */ Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) { if (grid !== undefined && this._grid) { var index = this._grid.indexOf(grid); if (index > -1) { this._grid.splice(index, 1); } } return this; }; // Extend DB with grids init Db.prototype.init = function () { this._grid = {}; DbInit.apply(this, arguments); }; /** * Determine if a grid with the passed name already exists. * @func gridExists * @memberof Db * @param {String} selector The jQuery selector to bind the grid to. * @returns {boolean} */ Db.prototype.gridExists = function (selector) { return Boolean(this._grid[selector]); }; /** * Creates a grid based on the passed arguments. * @func grid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.grid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Removes a grid based on the passed arguments. * @func unGrid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.unGrid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Returns an array of grids the DB currently has. * @func grids * @memberof Db * @returns {Array} An array of objects containing details of each grid * the database is currently managing. */ Db.prototype.grids = function () { var arr = [], item, i; for (i in this._grid) { if (this._grid.hasOwnProperty(i)) { item = this._grid[i]; arr.push({ name: i, count: item.count(), linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Grid'); module.exports = Grid; },{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":37,"./Shared":39,"./View":40}],12:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Collection, CollectionInit, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The constructor. * * @constructor */ var Highchart = function (collection, options) { this.init.apply(this, arguments); }; Highchart.prototype.init = function (collection, options) { this._options = options; this._selector = window.jQuery(this._options.selector); if (!this._selector[0]) { throw(this.classIdentifier() + ' "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector); } this._listeners = {}; this._collection = collection; // Setup the chart this._options.series = []; // Disable attribution on highcharts options.chartOptions = options.chartOptions || {}; options.chartOptions.credits = false; // Set the data for the chart var data, seriesObj, chartData; switch (this._options.type) { case 'pie': // Create chart from data this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); // Generate graph data from collection data data = this._collection.find(); seriesObj = { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)', style: { color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black' } } }; chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField); window.jQuery.extend(seriesObj, this._options.seriesOptions); window.jQuery.extend(seriesObj, { name: this._options.seriesName, data: chartData }); this._chart.addSeries(seriesObj, true, true); break; case 'line': case 'area': case 'column': case 'bar': // Generate graph data from collection data chartData = this.seriesDataFromCollectionData( this._options.seriesField, this._options.keyField, this._options.valField, this._options.orderBy, this._options ); this._options.chartOptions.xAxis = chartData.xAxis; this._options.chartOptions.series = chartData.series; this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); break; default: throw(this.classIdentifier() + ' "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type); } // Hook the collection events to auto-update the chart this._hookEvents(); }; Shared.addModule('Highchart', Highchart); Collection = Shared.modules.Collection; CollectionInit = Collection.prototype.init; Shared.mixin(Highchart.prototype, 'Mixin.Common'); Shared.mixin(Highchart.prototype, 'Mixin.Events'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Highchart.prototype, 'state'); /** * Generate pie-chart series data from the given collection data array. * @param data * @param keyField * @param valField * @returns {Array} */ Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) { var graphData = [], i; for (i = 0; i < data.length; i++) { graphData.push([data[i][keyField], data[i][valField]]); } return graphData; }; /** * Generate line-chart series data from the given collection data array. * @param seriesField * @param keyField * @param valField * @param orderBy */ Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy, options) { var data = this._collection.distinct(seriesField), seriesData = [], xAxis = options && options.chartOptions && options.chartOptions.xAxis ? options.chartOptions.xAxis : { categories: [] }, seriesName, query, dataSearch, seriesValues, sData, i, k; // What we WANT to output: /*series: [{ name: 'Responses', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6] }]*/ // Loop keys for (i = 0; i < data.length; i++) { seriesName = data[i]; query = {}; query[seriesField] = seriesName; seriesValues = []; dataSearch = this._collection.find(query, { orderBy: orderBy }); // Loop the keySearch data and grab the value for each item for (k = 0; k < dataSearch.length; k++) { if (xAxis.categories) { xAxis.categories.push(dataSearch[k][keyField]); seriesValues.push(dataSearch[k][valField]); } else { seriesValues.push([dataSearch[k][keyField], dataSearch[k][valField]]); } } sData = { name: seriesName, data: seriesValues }; if (options.seriesOptions) { for (k in options.seriesOptions) { if (options.seriesOptions.hasOwnProperty(k)) { sData[k] = options.seriesOptions[k]; } } } seriesData.push(sData); } return { xAxis: xAxis, series: seriesData }; }; /** * Hook the events the chart needs to know about from the internal collection. * @private */ Highchart.prototype._hookEvents = function () { var self = this; self._collection.on('change', function () { self._changeListener.apply(self, arguments); }); // If the collection is dropped, clean up after ourselves self._collection.on('drop', function () { self.drop.apply(self); }); }; /** * Handles changes to the collection data that the chart is reading from and then * updates the data in the chart display. * @private */ Highchart.prototype._changeListener = function () { var self = this; // Update the series data on the chart if (typeof self._collection !== 'undefined' && self._chart) { var data = self._collection.find(), i; switch (self._options.type) { case 'pie': self._chart.series[0].setData( self.pieDataFromCollectionData( data, self._options.keyField, self._options.valField ), true, true ); break; case 'bar': case 'line': case 'area': case 'column': var seriesData = self.seriesDataFromCollectionData( self._options.seriesField, self._options.keyField, self._options.valField, self._options.orderBy, self._options ); if (seriesData.xAxis.categories) { self._chart.xAxis[0].setCategories( seriesData.xAxis.categories ); } for (i = 0; i < seriesData.series.length; i++) { if (self._chart.series[i]) { // Series exists, set it's data self._chart.series[i].setData( seriesData.series[i].data, true, true ); } else { // Series data does not yet exist, add a new series self._chart.addSeries( seriesData.series[i], true, true ); } } break; default: break; } } }; /** * Destroys the chart and all internal references. * @returns {Boolean} */ Highchart.prototype.drop = function (callback) { if (!this.isDropped()) { this._state = 'dropped'; if (this._chart) { this._chart.destroy(); } if (this._collection) { this._collection.off('change', this._changeListener); this._collection.off('drop', this.drop); if (this._collection._highcharts) { delete this._collection._highcharts[this._options.selector]; } } delete this._chart; delete this._options; delete this._collection; this.emit('drop', this); if (callback) { callback(false, true); } delete this._listeners; return true; } else { return true; } }; // Extend collection with highchart init Collection.prototype.init = function () { this._highcharts = {}; CollectionInit.apply(this, arguments); }; /** * Creates a pie chart from the collection. * @type {Overload} */ Collection.prototype.pieChart = new Overload({ /** * Chart via options object. * @func pieChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'pie'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'pie'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func pieChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {String} seriesName The name of the series to display on the chart. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) { options = options || {}; options.selector = selector; options.keyField = keyField; options.valField = valField; options.seriesName = seriesName; // Call the main chart method this.pieChart(options); } }); /** * Creates a line chart from the collection. * @type {Overload} */ Collection.prototype.lineChart = new Overload({ /** * Chart via selector. * @func lineChart * @memberof Highchart * @param {String} selector The chart selector. * @returns {*} */ 'string': function (selector) { return this._highcharts[selector]; }, /** * Chart via options object. * @func lineChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'line'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'line'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func lineChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.lineChart(options); } }); /** * Creates an area chart from the collection. * @type {Overload} */ Collection.prototype.areaChart = new Overload({ /** * Chart via options object. * @func areaChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'area'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'area'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func areaChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.areaChart(options); } }); /** * Creates a column chart from the collection. * @type {Overload} */ Collection.prototype.columnChart = new Overload({ /** * Chart via options object. * @func columnChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'column'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'column'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func columnChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.columnChart(options); } }); /** * Creates a bar chart from the collection. * @type {Overload} */ Collection.prototype.barChart = new Overload({ /** * Chart via options object. * @func barChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'bar'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'bar'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func barChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.barChart(options); } }); /** * Creates a stacked bar chart from the collection. * @type {Overload} */ Collection.prototype.stackedBarChart = new Overload({ /** * Chart via options object. * @func stackedBarChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'bar'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'bar'; options.plotOptions = options.plotOptions || {}; options.plotOptions.series = options.plotOptions.series || {}; options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func stackedBarChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.stackedBarChart(options); } }); /** * Removes a chart from the page by it's selector. * @memberof Collection * @param {String} selector The chart selector. */ Collection.prototype.dropChart = function (selector) { if (this._highcharts && this._highcharts[selector]) { this._highcharts[selector].drop(); } }; Shared.finishModule('Highchart'); module.exports = Highchart; },{"./Overload":31,"./Shared":39}],13:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.lookup = function (query, options) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options) { var self = this, geoHash, neighbours, visited, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } // Get the lngLat geohash from the query geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision); // Calculate 9 box geohashes neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'}); // Lookup all matching co-ordinates from the btree results = []; visited = 0; for (i = 0; i < 9; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visited += search._visited; results = results.concat(search); } // Work with original data results = this._collection._primaryIndex.lookup(results); if (results.length) { distance = {}; // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { // Add item inside radius distance finalResults.push(results[i]); } } // Sort by distance from center finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":3,"./GeoHash":10,"./Path":33,"./Shared":39}],14:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query, options) { return this._btree.lookup(query, options); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":3,"./Path":33,"./Shared":39}],15:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":33,"./Shared":39}],16:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} val A lookup query. * @returns {*} */ KeyValueStore.prototype.lookup = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, result = []; // Check for early exit conditions if (valType === 'string' || valType === 'number') { lookupItem = this.get(val); if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } else if (valType === 'object') { if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this.lookup(val[arrIndex]); if (lookupItem) { if (lookupItem instanceof Array) { result = result.concat(lookupItem); } else { result.push(lookupItem); } } } return result; } else if (val[pk]) { return this.lookup(val[pk]); } } // COMMENTED AS CODE WILL NEVER BE REACHED // Complex lookup /*lookupData = this._lookupKeys(val); keys = lookupData.keys; negate = lookupData.negate; if (!negate) { // Loop keys and return values for (arrIndex = 0; arrIndex < keys.length; arrIndex++) { result.push(this.get(keys[arrIndex])); } } else { // Loop data and return non-matching keys for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (keys.indexOf(arrIndex) === -1) { result.push(this.get(arrIndex)); } } } } return result;*/ }; // COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES /*KeyValueStore.prototype._lookupKeys = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, bool, result; if (valType === 'string' || valType === 'number') { return { keys: [val], negate: false }; } else if (valType === 'object') { if (val instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (val.test(arrIndex)) { result.push(arrIndex); } } } return { keys: result, negate: false }; } else if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { result = result.concat(this._lookupKeys(val[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val.$in && (val.$in instanceof Array)) { return { keys: this._lookupKeys(val.$in).keys, negate: false }; } else if (val.$nin && (val.$nin instanceof Array)) { return { keys: this._lookupKeys(val.$nin).keys, negate: true }; } else if (val.$ne) { return { keys: this._lookupKeys(val.$ne, true).keys, negate: true }; } else if (val.$or && (val.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) { result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val[pk]) { return this._lookupKeys(val[pk]); } } };*/ /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":39}],17:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":30,"./Shared":39}],18:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],19:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @param obj */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index; for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, data, options); } } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; if (this.debug && this.debug()) { console.log(this.logIdentifier() + 'Received data from parent reactor node'); } // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],20:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined && data !== "") { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return serialiser.parse(data); //return JSON.parse(data); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { return serialiser.stringify(data); //return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return this.classIdentifier() + ': ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; } }; module.exports = Common; },{"./Overload":31,"./Serialiser":38}],21:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],22:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":31}],23:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; } }; module.exports = Matching; },{}],24:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],25:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],26:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":31}],27:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],28:[function(_dereq_,module,exports){ "use strict"; // Grab the view class var Shared, Core, OldView, OldViewInit; Shared = _dereq_('./Shared'); Core = Shared.modules.Core; OldView = Shared.modules.OldView; OldViewInit = OldView.prototype.init; OldView.prototype.init = function () { var self = this; this._binds = []; this._renderStart = 0; this._renderEnd = 0; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], _bindInsert: [], _bindUpdate: [], _bindRemove: [], _bindUpsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100, _bindInsert: 100, _bindUpdate: 100, _bindRemove: 100, _bindUpsert: 100 }; this._deferTime = { insert: 100, update: 1, remove: 1, upsert: 1, _bindInsert: 100, _bindUpdate: 1, _bindRemove: 1, _bindUpsert: 1 }; OldViewInit.apply(this, arguments); // Hook view events to update binds this.on('insert', function (successArr, failArr) { self._bindEvent('insert', successArr, failArr); }); this.on('update', function (successArr, failArr) { self._bindEvent('update', successArr, failArr); }); this.on('remove', function (successArr, failArr) { self._bindEvent('remove', successArr, failArr); }); this.on('change', self._bindChange); }; /** * Binds a selector to the insert, update and delete events of a particular * view and keeps the selector in sync so that updates are reflected on the * web page in real-time. * * @param {String} selector The jQuery selector string to get target elements. * @param {Object} options The options object. */ OldView.prototype.bind = function (selector, options) { if (options && options.template) { this._binds[selector] = options; } else { throw('ForerunnerDB.OldView "' + this.name() + '": Cannot bind data to element, missing options information!'); } return this; }; /** * Un-binds a selector from the view changes. * @param {String} selector The jQuery selector string to identify the bind to remove. * @returns {Collection} */ OldView.prototype.unBind = function (selector) { delete this._binds[selector]; return this; }; /** * Returns true if the selector is bound to the view. * @param {String} selector The jQuery selector string to identify the bind to check for. * @returns {boolean} */ OldView.prototype.isBound = function (selector) { return Boolean(this._binds[selector]); }; /** * Sorts items in the DOM based on the bind settings and the passed item array. * @param {String} selector The jQuery selector of the bind container. * @param {Array} itemArr The array of items used to determine the order the DOM * elements should be in based on the order they are in, in the array. */ OldView.prototype.bindSortDom = function (selector, itemArr) { var container = window.jQuery(selector), arrIndex, arrItem, domItem; if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting data in DOM...', itemArr); } for (arrIndex = 0; arrIndex < itemArr.length; arrIndex++) { arrItem = itemArr[arrIndex]; // Now we've done our inserts into the DOM, let's ensure // they are still ordered correctly domItem = container.find('#' + arrItem[this._primaryKey]); if (domItem.length) { if (arrIndex === 0) { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sort, moving to index 0...', domItem); } container.prepend(domItem); } else { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sort, moving to index ' + arrIndex + '...', domItem); } domItem.insertAfter(container.children(':eq(' + (arrIndex - 1) + ')')); } } else { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Warning, element for array item not found!', arrItem); } } } }; OldView.prototype.bindRefresh = function (obj) { var binds = this._binds, bindKey, bind; if (!obj) { // Grab current data obj = { data: this.find() }; } for (bindKey in binds) { if (binds.hasOwnProperty(bindKey)) { bind = binds[bindKey]; if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting DOM...'); } this.bindSortDom(bindKey, obj.data); if (bind.afterOperation) { bind.afterOperation(); } if (bind.refresh) { bind.refresh(); } } } }; /** * Renders a bind view data to the DOM. * @param {String} bindSelector The jQuery selector string to use to identify * the bind target. Must match the selector used when defining the original bind. * @param {Function=} domHandler If specified, this handler method will be called * with the final HTML for the view instead of the DB handling the DOM insertion. */ OldView.prototype.bindRender = function (bindSelector, domHandler) { // Check the bind exists var bind = this._binds[bindSelector], domTarget = window.jQuery(bindSelector), allData, dataItem, itemHtml, finalHtml = window.jQuery('<ul></ul>'), bindCallback, i; if (bind) { allData = this._data.find(); bindCallback = function (itemHtml) { finalHtml.append(itemHtml); }; // Loop all items and add them to the screen for (i = 0; i < allData.length; i++) { dataItem = allData[i]; itemHtml = bind.template(dataItem, bindCallback); } if (!domHandler) { domTarget.append(finalHtml.html()); } else { domHandler(bindSelector, finalHtml.html()); } } }; OldView.prototype.processQueue = function (type, callback) { var queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type]; if (queue.length) { var self = this, dataArr; // Process items up to the threshold if (queue.length) { if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } this._bindEvent(type, dataArr, []); } // Queue another process setTimeout(function () { self.processQueue(type, callback); }, deferTime); } else { if (callback) { callback(); } this.emit('bindQueueComplete'); } }; OldView.prototype._bindEvent = function (type, successArr, failArr) { /*var queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type];*/ var binds = this._binds, unfilteredDataSet = this.find({}), filteredDataSet, bindKey; // Check if the number of inserts is greater than the defer threshold /*if (successArr && successArr.length > deferThreshold) { // Break up upsert into blocks this._deferQueue[type] = queue.concat(successArr); // Fire off the insert queue handler this.processQueue(type); return; } else {*/ for (bindKey in binds) { if (binds.hasOwnProperty(bindKey)) { if (binds[bindKey].reduce) { filteredDataSet = this.find(binds[bindKey].reduce.query, binds[bindKey].reduce.options); } else { filteredDataSet = unfilteredDataSet; } switch (type) { case 'insert': this._bindInsert(bindKey, binds[bindKey], successArr, failArr, filteredDataSet); break; case 'update': this._bindUpdate(bindKey, binds[bindKey], successArr, failArr, filteredDataSet); break; case 'remove': this._bindRemove(bindKey, binds[bindKey], successArr, failArr, filteredDataSet); break; } } } //} }; OldView.prototype._bindChange = function (newDataArr) { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...', newDataArr); } this.bindRefresh(newDataArr); }; OldView.prototype._bindInsert = function (selector, options, successArr, failArr, all) { var container = window.jQuery(selector), itemElem, itemHtml, makeCallback, i; makeCallback = function (itemElem, insertedItem, failArr, all) { return function (itemHtml) { // Check if there is custom DOM insert method if (options.insert) { options.insert(itemHtml, insertedItem, failArr, all); } else { // Handle the insert automatically // Add the item to the container if (options.prependInsert) { container.prepend(itemHtml); } else { container.append(itemHtml); } } if (options.afterInsert) { options.afterInsert(itemHtml, insertedItem, failArr, all); } }; }; // Loop the inserted items for (i = 0; i < successArr.length; i++) { // Check for existing item in the container itemElem = container.find('#' + successArr[i][this._primaryKey]); if (!itemElem.length) { itemHtml = options.template(successArr[i], makeCallback(itemElem, successArr[i], failArr, all)); } } }; OldView.prototype._bindUpdate = function (selector, options, successArr, failArr, all) { var container = window.jQuery(selector), itemElem, makeCallback, i; makeCallback = function (itemElem, itemData) { return function (itemHtml) { // Check if there is custom DOM insert method if (options.update) { options.update(itemHtml, itemData, all, itemElem.length ? 'update' : 'append'); } else { if (itemElem.length) { // An existing item is in the container, replace it with the // new rendered item from the updated data itemElem.replaceWith(itemHtml); } else { // The item element does not already exist, append it if (options.prependUpdate) { container.prepend(itemHtml); } else { container.append(itemHtml); } } } if (options.afterUpdate) { options.afterUpdate(itemHtml, itemData, all); } }; }; // Loop the updated items for (i = 0; i < successArr.length; i++) { // Check for existing item in the container itemElem = container.find('#' + successArr[i][this._primaryKey]); options.template(successArr[i], makeCallback(itemElem, successArr[i])); } }; OldView.prototype._bindRemove = function (selector, options, successArr, failArr, all) { var container = window.jQuery(selector), itemElem, makeCallback, i; makeCallback = function (itemElem, data, all) { return function () { if (options.remove) { options.remove(itemElem, data, all); } else { itemElem.remove(); if (options.afterRemove) { options.afterRemove(itemElem, data, all); } } }; }; // Loop the removed items for (i = 0; i < successArr.length; i++) { // Check for existing item in the container itemElem = container.find('#' + successArr[i][this._primaryKey]); if (itemElem.length) { if (options.beforeRemove) { options.beforeRemove(itemElem, successArr[i], all, makeCallback(itemElem, successArr[i], all)); } else { if (options.remove) { options.remove(itemElem, successArr[i], all); } else { itemElem.remove(); if (options.afterRemove) { options.afterRemove(itemElem, successArr[i], all); } } } } } }; },{"./Shared":39}],29:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, CollectionGroup, Collection, CollectionInit, CollectionGroupInit, DbInit; Shared = _dereq_('./Shared'); /** * The view constructor. * @param viewName * @constructor */ var OldView = function (viewName) { this.init.apply(this, arguments); }; OldView.prototype.init = function (viewName) { var self = this; this._name = viewName; this._listeners = {}; this._query = { query: {}, options: {} }; // Register listeners for the CRUD events this._onFromSetData = function () { self._onSetData.apply(self, arguments); }; this._onFromInsert = function () { self._onInsert.apply(self, arguments); }; this._onFromUpdate = function () { self._onUpdate.apply(self, arguments); }; this._onFromRemove = function () { self._onRemove.apply(self, arguments); }; this._onFromChange = function () { if (self.debug()) { console.log('ForerunnerDB.OldView: Received change'); } self._onChange.apply(self, arguments); }; }; Shared.addModule('OldView', OldView); CollectionGroup = _dereq_('./CollectionGroup'); Collection = _dereq_('./Collection'); CollectionInit = Collection.prototype.init; CollectionGroupInit = CollectionGroup.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; Shared.mixin(OldView.prototype, 'Mixin.Events'); /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ OldView.prototype.drop = function () { if ((this._db || this._from) && this._name) { if (this.debug()) { console.log('ForerunnerDB.OldView: Dropping view ' + this._name); } this._state = 'dropped'; this.emit('drop', this); if (this._db && this._db._oldViews) { delete this._db._oldViews[this._name]; } if (this._from && this._from._oldViews) { delete this._from._oldViews[this._name]; } delete this._listeners; return true; } return false; }; OldView.prototype.debug = function () { // TODO: Make this function work return false; }; /** * Gets / sets the DB the view is bound against. Automatically set * when the db.oldView(viewName) method is called. * @param db * @returns {*} */ OldView.prototype.db = function (db) { if (db !== undefined) { this._db = db; return this; } return this._db; }; /** * Gets / sets the collection that the view derives it's data from. * @param {*} collection A collection instance or the name of a collection * to use as the data set to derive view data from. * @returns {*} */ OldView.prototype.from = function (collection) { if (collection !== undefined) { // Check if this is a collection name or a collection instance if (typeof(collection) === 'string') { if (this._db.collectionExists(collection)) { collection = this._db.collection(collection); } else { throw('ForerunnerDB.OldView "' + this.name() + '": Invalid collection in view.from() call.'); } } // Check if the existing from matches the passed one if (this._from !== collection) { // Check if we already have a collection assigned if (this._from) { // Remove ourselves from the collection view lookup this.removeFrom(); } this.addFrom(collection); } return this; } return this._from; }; OldView.prototype.addFrom = function (collection) { //var self = this; this._from = collection; if (this._from) { this._from.on('setData', this._onFromSetData); //this._from.on('insert', this._onFromInsert); //this._from.on('update', this._onFromUpdate); //this._from.on('remove', this._onFromRemove); this._from.on('change', this._onFromChange); // Add this view to the collection's view lookup this._from._addOldView(this); this._primaryKey = this._from._primaryKey; this.refresh(); return this; } else { throw('ForerunnerDB.OldView "' + this.name() + '": Cannot determine collection type in view.from()'); } }; OldView.prototype.removeFrom = function () { // Unsubscribe from events on this "from" this._from.off('setData', this._onFromSetData); //this._from.off('insert', this._onFromInsert); //this._from.off('update', this._onFromUpdate); //this._from.off('remove', this._onFromRemove); this._from.off('change', this._onFromChange); this._from._removeOldView(this); }; /** * Gets the primary key for this view from the assigned collection. * @returns {String} */ OldView.prototype.primaryKey = function () { if (this._from) { return this._from.primaryKey(); } return undefined; }; /** * Gets / sets the query that the view uses to build it's data set. * @param {Object=} query * @param {Boolean=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ OldView.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._query.query = query; } if (options !== undefined) { this._query.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._query; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ OldView.prototype.queryAdd = function (obj, overwrite, refresh) { var query = this._query.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ OldView.prototype.queryRemove = function (obj, refresh) { var query = this._query.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Gets / sets the query being used to generate the view data. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ OldView.prototype.query = function (query, refresh) { if (query !== undefined) { this._query.query = query; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._query.query; }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ OldView.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._query.options = options; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._query.options; }; /** * Refreshes the view data and diffs between previous and new data to * determine if any events need to be triggered or DOM binds updated. */ OldView.prototype.refresh = function (force) { if (this._from) { // Take a copy of the data before updating it, we will use this to // "diff" between the old and new data and handle DOM bind updates var oldData = this._data, oldDataArr, oldDataItem, newData, newDataArr, query, primaryKey, dataItem, inserted = [], updated = [], removed = [], operated = false, i; if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing view ' + this._name); console.log('ForerunnerDB.OldView: Existing data: ' + (typeof(this._data) !== "undefined")); if (typeof(this._data) !== "undefined") { console.log('ForerunnerDB.OldView: Current data rows: ' + this._data.find().length); } //console.log(OldView.prototype.refresh.caller); } // Query the collection and update the data if (this._query) { if (this.debug()) { console.log('ForerunnerDB.OldView: View has query and options, getting subset...'); } // Run query against collection //console.log('refresh with query and options', this._query.options); this._data = this._from.subset(this._query.query, this._query.options); //console.log(this._data); } else { // No query, return whole collection if (this._query.options) { if (this.debug()) { console.log('ForerunnerDB.OldView: View has options, getting subset...'); } this._data = this._from.subset({}, this._query.options); } else { if (this.debug()) { console.log('ForerunnerDB.OldView: View has no query or options, getting subset...'); } this._data = this._from.subset({}); } } // Check if there was old data if (!force && oldData) { if (this.debug()) { console.log('ForerunnerDB.OldView: Refresh not forced, old data detected...'); } // Now determine the difference newData = this._data; if (oldData.subsetOf() === newData.subsetOf()) { if (this.debug()) { console.log('ForerunnerDB.OldView: Old and new data are from same collection...'); } newDataArr = newData.find(); oldDataArr = oldData.find(); primaryKey = newData._primaryKey; // The old data and new data were derived from the same parent collection // so scan the data to determine changes for (i = 0; i < newDataArr.length; i++) { dataItem = newDataArr[i]; query = {}; query[primaryKey] = dataItem[primaryKey]; // Check if this item exists in the old data oldDataItem = oldData.find(query)[0]; if (!oldDataItem) { // New item detected inserted.push(dataItem); } else { // Check if an update has occurred if (JSON.stringify(oldDataItem) !== JSON.stringify(dataItem)) { // Updated / already included item detected updated.push(dataItem); } } } // Now loop the old data and check if any records were removed for (i = 0; i < oldDataArr.length; i++) { dataItem = oldDataArr[i]; query = {}; query[primaryKey] = dataItem[primaryKey]; // Check if this item exists in the old data if (!newData.find(query)[0]) { // Removed item detected removed.push(dataItem); } } if (this.debug()) { console.log('ForerunnerDB.OldView: Removed ' + removed.length + ' rows'); console.log('ForerunnerDB.OldView: Inserted ' + inserted.length + ' rows'); console.log('ForerunnerDB.OldView: Updated ' + updated.length + ' rows'); } // Now we have a diff of the two data sets, we need to get the DOM updated if (inserted.length) { this._onInsert(inserted, []); operated = true; } if (updated.length) { this._onUpdate(updated, []); operated = true; } if (removed.length) { this._onRemove(removed, []); operated = true; } } else { // The previous data and the new data are derived from different collections // and can therefore not be compared, all data is therefore effectively "new" // so first perform a remove of all existing data then do an insert on all new data if (this.debug()) { console.log('ForerunnerDB.OldView: Old and new data are from different collections...'); } removed = oldData.find(); if (removed.length) { this._onRemove(removed); operated = true; } inserted = newData.find(); if (inserted.length) { this._onInsert(inserted); operated = true; } } } else { // Force an update as if the view never got created by padding all elements // to the insert if (this.debug()) { console.log('ForerunnerDB.OldView: Forcing data update', newDataArr); } this._data = this._from.subset(this._query.query, this._query.options); newDataArr = this._data.find(); if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change event with data', newDataArr); } this._onInsert(newDataArr, []); } if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change'); } this.emit('change'); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ OldView.prototype.count = function () { return this._data && this._data._data ? this._data._data.length : 0; }; /** * Queries the view data. See Collection.find() for more information. * @returns {*} */ OldView.prototype.find = function () { if (this._data) { if (this.debug()) { console.log('ForerunnerDB.OldView: Finding data in view collection...', this._data); } return this._data.find.apply(this._data, arguments); } else { return []; } }; /** * Inserts into view data via the view collection. See Collection.insert() for more information. * @returns {*} */ OldView.prototype.insert = function () { if (this._from) { // Pass the args through to the from object return this._from.insert.apply(this._from, arguments); } else { return []; } }; /** * Updates into view data via the view collection. See Collection.update() for more information. * @returns {*} */ OldView.prototype.update = function () { if (this._from) { // Pass the args through to the from object return this._from.update.apply(this._from, arguments); } else { return []; } }; /** * Removed from view data via the view collection. See Collection.remove() for more information. * @returns {*} */ OldView.prototype.remove = function () { if (this._from) { // Pass the args through to the from object return this._from.remove.apply(this._from, arguments); } else { return []; } }; OldView.prototype._onSetData = function (newDataArr, oldDataArr) { this.emit('remove', oldDataArr, []); this.emit('insert', newDataArr, []); //this.refresh(); }; OldView.prototype._onInsert = function (successArr, failArr) { this.emit('insert', successArr, failArr); //this.refresh(); }; OldView.prototype._onUpdate = function (successArr, failArr) { this.emit('update', successArr, failArr); //this.refresh(); }; OldView.prototype._onRemove = function (successArr, failArr) { this.emit('remove', successArr, failArr); //this.refresh(); }; OldView.prototype._onChange = function () { if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing data'); } this.refresh(); }; // Extend collection with view init Collection.prototype.init = function () { this._oldViews = []; CollectionInit.apply(this, arguments); }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addOldView = function (view) { if (view !== undefined) { this._oldViews[view._name] = view; } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeOldView = function (view) { if (view !== undefined) { delete this._oldViews[view._name]; } return this; }; // Extend collection with view init CollectionGroup.prototype.init = function () { this._oldViews = []; CollectionGroupInit.apply(this, arguments); }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ CollectionGroup.prototype._addOldView = function (view) { if (view !== undefined) { this._oldViews[view._name] = view; } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ CollectionGroup.prototype._removeOldView = function (view) { if (view !== undefined) { delete this._oldViews[view._name]; } return this; }; // Extend DB with views init Db.prototype.init = function () { this._oldViews = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Db.prototype.oldView = function (viewName) { if (!this._oldViews[viewName]) { if (this.debug()) { console.log('ForerunnerDB.OldView: Creating view ' + viewName); } } this._oldViews[viewName] = this._oldViews[viewName] || new OldView(viewName).db(this); return this._oldViews[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Db.prototype.oldViewExists = function (viewName) { return Boolean(this._oldViews[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.oldViews = function () { var arr = [], i; for (i in this._oldViews) { if (this._oldViews.hasOwnProperty(i)) { arr.push({ name: i, count: this._oldViews[i].count() }); } } return arr; }; Shared.finishModule('OldView'); module.exports = OldView; },{"./Collection":4,"./CollectionGroup":5,"./Shared":39}],30:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":33,"./Shared":39}],31:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, name; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } name = typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload: ', def); throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],32:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, DbDocument; Shared = _dereq_('./Shared'); var Overview = function () { this.init.apply(this, arguments); }; Overview.prototype.init = function (name) { var self = this; this._name = name; this._data = new DbDocument('__FDB__dc_data_' + this._name); this._collData = new Collection(); this._sources = []; this._sourceDroppedWrap = function () { self._sourceDropped.apply(self, arguments); }; }; Shared.addModule('Overview', Overview); Shared.mixin(Overview.prototype, 'Mixin.Common'); Shared.mixin(Overview.prototype, 'Mixin.ChainReactor'); Shared.mixin(Overview.prototype, 'Mixin.Constants'); Shared.mixin(Overview.prototype, 'Mixin.Triggers'); Shared.mixin(Overview.prototype, 'Mixin.Events'); Shared.mixin(Overview.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); DbDocument = _dereq_('./Document'); Db = Shared.modules.Db; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Overview.prototype, 'state'); Shared.synthesize(Overview.prototype, 'db'); Shared.synthesize(Overview.prototype, 'name'); Shared.synthesize(Overview.prototype, 'query', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Shared.synthesize(Overview.prototype, 'queryOptions', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Shared.synthesize(Overview.prototype, 'reduce', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Overview.prototype.from = function (source) { if (source !== undefined) { if (typeof(source) === 'string') { source = this._db.collection(source); } this._setFrom(source); return this; } return this._sources; }; Overview.prototype.find = function () { return this._collData.find.apply(this._collData, arguments); }; /** * Executes and returns the response from the current reduce method * assigned to the overview. * @returns {*} */ Overview.prototype.exec = function () { var reduceFunc = this.reduce(); return reduceFunc ? reduceFunc.apply(this) : undefined; }; Overview.prototype.count = function () { return this._collData.count.apply(this._collData, arguments); }; Overview.prototype._setFrom = function (source) { // Remove all source references while (this._sources.length) { this._removeSource(this._sources[0]); } this._addSource(source); return this; }; Overview.prototype._addSource = function (source) { if (source && source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } if (this._sources.indexOf(source) === -1) { this._sources.push(source); source.chain(this); source.on('drop', this._sourceDroppedWrap); this._refresh(); } return this; }; Overview.prototype._removeSource = function (source) { if (source && source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } var sourceIndex = this._sources.indexOf(source); if (sourceIndex > -1) { this._sources.splice(source, 1); source.unChain(this); source.off('drop', this._sourceDroppedWrap); this._refresh(); } return this; }; Overview.prototype._sourceDropped = function (source) { if (source) { // Source was dropped, remove from overview this._removeSource(source); } }; Overview.prototype._refresh = function () { if (!this.isDropped()) { if (this._sources && this._sources[0]) { this._collData.primaryKey(this._sources[0].primaryKey()); var tempArr = [], i; for (i = 0; i < this._sources.length; i++) { tempArr = tempArr.concat(this._sources[i].find(this._query, this._queryOptions)); } this._collData.setData(tempArr); } // Now execute the reduce method if (this._reduce) { var reducedData = this._reduce.apply(this); // Update the document with the newly returned data this._data.setData(reducedData); } } }; Overview.prototype._chainHandler = function (chainPacket) { switch (chainPacket.type) { case 'setData': case 'insert': case 'update': case 'remove': this._refresh(); break; default: break; } }; /** * Gets the module's internal data collection. * @returns {Collection} */ Overview.prototype.data = function () { return this._data; }; Overview.prototype.drop = function (callback) { if (!this.isDropped()) { this._state = 'dropped'; delete this._data; delete this._collData; // Remove all source references while (this._sources.length) { this._removeSource(this._sources[0]); } delete this._sources; if (this._db && this._name) { delete this._db._overview[this._name]; } delete this._name; this.emit('drop', this); if (callback) { callback(false, true); } delete this._listeners; } return true; }; Db.prototype.overview = function (overviewName) { if (overviewName) { // Handle being passed an instance if (overviewName instanceof Overview) { return overviewName; } this._overview = this._overview || {}; this._overview[overviewName] = this._overview[overviewName] || new Overview(overviewName).db(this); return this._overview[overviewName]; } else { // Return an object of collection data return this._overview || {}; } }; /** * Returns an array of overviews the DB currently has. * @returns {Array} An array of objects containing details of each overview * the database is currently managing. */ Db.prototype.overviews = function () { var arr = [], item, i; for (i in this._overview) { if (this._overview.hasOwnProperty(i)) { item = this._overview[i]; arr.push({ name: i, count: item.count(), linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Overview'); module.exports = Overview; },{"./Collection":4,"./Document":9,"./Shared":39}],33:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Gets a single value from the passed object and given path. * @param {Object} obj The object to inspect. * @param {String} path The path to retrieve data from. * @returns {*} */ Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; // Detect early exit if (path && path.indexOf('.') === -1) { return [obj[path]]; } if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.get(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":39}],34:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared = _dereq_('./Shared'), async = _dereq_('async'), localforage = _dereq_('localforage'), FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line Db, Collection, CollectionDrop, CollectionGroup, CollectionInit, DbInit, DbDrop, Persist, Overload;//, //DataVersion = '2.0'; /** * The persistent storage class handles loading and saving data to browser * storage. * @constructor */ Persist = function () { this.init.apply(this, arguments); }; /** * The local forage library. */ Persist.prototype.localforage = localforage; /** * The init method that can be overridden or extended. * @param {Db} db The ForerunnerDB database instance. */ Persist.prototype.init = function (db) { var self = this; this._encodeSteps = [ function () { return self._encode.apply(self, arguments); } ]; this._decodeSteps = [ function () { return self._decode.apply(self, arguments); } ]; // Check environment if (db.isClient()) { if (window.Storage !== undefined) { this.mode('localforage'); localforage.config({ driver: [ localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE ], name: String(db.core().name()), storeName: 'FDB' }); } } }; Shared.addModule('Persist', Persist); Shared.mixin(Persist.prototype, 'Mixin.ChainReactor'); Shared.mixin(Persist.prototype, 'Mixin.Common'); Db = Shared.modules.Db; Collection = _dereq_('./Collection'); CollectionDrop = Collection.prototype.drop; CollectionGroup = _dereq_('./CollectionGroup'); CollectionInit = Collection.prototype.init; DbInit = Db.prototype.init; DbDrop = Db.prototype.drop; Overload = Shared.overload; /** * Gets / sets the auto flag which determines if the persistence module * will automatically load data for collections the first time they are * accessed and save data whenever it changes. This is disabled by * default. * @param {Boolean} val Set to true to enable, false to disable * @returns {*} */ Shared.synthesize(Persist.prototype, 'auto', function (val) { var self = this; if (val !== undefined) { if (val) { // Hook db events this._db.on('create', function () { self._autoLoad.apply(self, arguments); }); this._db.on('change', function () { self._autoSave.apply(self, arguments); }); if (this._db.debug()) { console.log(this._db.logIdentifier() + ' Automatic load/save enabled'); } } else { // Un-hook db events this._db.off('create', this._autoLoad); this._db.off('change', this._autoSave); if (this._db.debug()) { console.log(this._db.logIdentifier() + ' Automatic load/save disbled'); } } } return this.$super.call(this, val); }); Persist.prototype._autoLoad = function (obj, objType, name) { var self = this; if (typeof obj.load === 'function') { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-loading data for ' + objType + ':', name); } obj.load(function (err, data) { if (err && self._db.debug()) { console.log(self._db.logIdentifier() + ' Automatic load failed:', err); } self.emit('load', err, data); }); } else { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-load for ' + objType + ':', name, 'no load method, skipping'); } } }; Persist.prototype._autoSave = function (obj, objType, name) { var self = this; if (typeof obj.save === 'function') { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-saving data for ' + objType + ':', name); } obj.save(function (err, data) { if (err && self._db.debug()) { console.log(self._db.logIdentifier() + ' Automatic save failed:', err); } self.emit('save', err, data); }); } }; /** * Gets / sets the persistent storage mode (the library used * to persist data to the browser - defaults to localForage). * @param {String} type The library to use for storage. Defaults * to localForage. * @returns {*} */ Persist.prototype.mode = function (type) { if (type !== undefined) { this._mode = type; return this; } return this._mode; }; /** * Gets / sets the driver used when persisting data. * @param {String} val Specify the driver type (LOCALSTORAGE, * WEBSQL or INDEXEDDB) * @returns {*} */ Persist.prototype.driver = function (val) { if (val !== undefined) { switch (val.toUpperCase()) { case 'LOCALSTORAGE': localforage.setDriver(localforage.LOCALSTORAGE); break; case 'WEBSQL': localforage.setDriver(localforage.WEBSQL); break; case 'INDEXEDDB': localforage.setDriver(localforage.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 localforage.driver(); }; /** * Starts a decode waterfall process. * @param {*} val The data to be decoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.decode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._decodeSteps), finished); }; /** * Starts an encode waterfall process. * @param {*} val The data to be encoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.encode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._encodeSteps), finished); }; Shared.synthesize(Persist.prototype, 'encodeSteps'); Shared.synthesize(Persist.prototype, 'decodeSteps'); /** * Adds an encode/decode step to the persistent storage system so * that you can add custom functionality. * @param {Function} encode The encode method called with the data from the * previous encode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the encoder will fail and throw an error. * @param {Function} decode The decode method called with the data from the * previous decode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the decoder will fail and throw an error. * @param {Number=} index Optional index to add the encoder step to. This * allows you to place a step before or after other existing steps. If not * provided your step is placed last in the list of steps. For instance if * you are providing an encryption step it makes sense to place this last * since all previous steps will then have their data encrypted by your * final step. */ Persist.prototype.addStep = new Overload({ 'object': function (obj) { this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0); }, 'function, function': function (encode, decode) { this.$main.call(this, encode, decode, 0); }, 'function, function, number': function (encode, decode, index) { this.$main.call(this, encode, decode, index); }, $main: function (encode, decode, index) { if (index === 0 || index === undefined) { this._encodeSteps.push(encode); this._decodeSteps.unshift(decode); } else { // Place encoder step at index then work out correct // index to place decoder step this._encodeSteps.splice(index, 0, encode); this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode); } } }); Persist.prototype.unwrap = function (dataStr) { var parts = dataStr.split('::fdb::'), data; switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } }; /** * Takes encoded data and decodes it for use as JS native objects and arrays. * @param {String} val The currently encoded string data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when decoding is * completed. * @private */ Persist.prototype._decode = function (val, meta, finished) { var parts, data; if (val) { parts = val.split('::fdb::'); switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } if (data) { meta.foundData = true; meta.rowCount = data.length; } else { meta.foundData = false; } if (finished) { finished(false, data, meta); } } else { meta.foundData = false; meta.rowCount = 0; if (finished) { finished(false, val, meta); } } }; /** * Takes native JS data and encodes it for for storage as a string. * @param {Object} val The current un-encoded data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when encoding is * completed. * @private */ Persist.prototype._encode = function (val, meta, finished) { var data = val; if (typeof val === 'object') { val = 'json::fdb::' + this.jStringify(val); } else { val = 'raw::fdb::' + val; } if (data) { meta.foundData = true; meta.rowCount = data.length; } else { meta.foundData = false; } if (finished) { finished(false, val, meta); } }; /** * Encodes passed data and then stores it in the browser's persistent * storage layer. * @param {String} key The key to store the data under in the persistent * storage. * @param {Object} data The data to store under the key. * @param {Function=} callback The method to call when the save process * has completed. */ Persist.prototype.save = function (key, data, callback) { switch (this.mode()) { case 'localforage': this.encode(data, function (err, data, tableStats) { localforage.setItem(key, data).then(function (data) { if (callback) { callback(false, data, tableStats); } }, function (err) { if (callback) { callback(err); } }); }); break; default: if (callback) { callback('No data handler.'); } break; } }; /** * Loads and decodes data from the passed key. * @param {String} key The key to retrieve data from in the persistent * storage. * @param {Function=} callback The method to call when the load process * has completed. */ Persist.prototype.load = function (key, callback) { var self = this; switch (this.mode()) { case 'localforage': localforage.getItem(key).then(function (val) { self.decode(val, callback); }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; /** * Deletes data in persistent storage stored under the passed key. * @param {String} key The key to drop data for in the storage. * @param {Function=} callback The method to call when the data is dropped. */ Persist.prototype.drop = function (key, callback) { switch (this.mode()) { case 'localforage': localforage.removeItem(key).then(function () { if (callback) { callback(false); } }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; // Extend the Collection prototype with persist methods Collection.prototype.drop = new Overload({ /** * Drop collection and persistent storage. */ '': function () { if (!this.isDropped()) { this.drop(true); } }, /** * Drop collection and persistent storage with callback. * @param {Function} callback Callback method. */ 'function': function (callback) { if (!this.isDropped()) { this.drop(true, callback); } }, /** * Drop collection and optionally drop persistent storage. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. */ 'boolean': function (removePersistent) { if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name); this._db.persist.drop(this._db._name + '-' + this._name + '-metaData'); } } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } // Call the original method CollectionDrop.call(this); } }, /** * Drop collections and optionally drop persistent storage with callback. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. * @param {Function} callback Callback method. */ 'boolean, function': function (removePersistent, callback) { var self = this; if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name, function () { self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback); }); return CollectionDrop.call(this); } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); } } } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } } else { // Call the original method return CollectionDrop.call(this, callback); } } } }); /** * Saves an entire collection's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ Collection.prototype.save = function (callback) { var self = this, processSave; if (self._name) { if (self._db) { processSave = function () { // Save the collection data self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, data, tableStats) { if (!err) { self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, data, metaStats) { if (callback) { callback(err, data, tableStats, metaStats); } }); } else { if (callback) { callback(err); } } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads an entire collection's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ Collection.prototype.load = function (callback) { var self = this; if (self._name) { if (self._db) { // Load the collection data self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); //self.setData(data); } // Now load the collection's metadata self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); } } if (callback) { callback(err, tableStats, metaStats); } }); } else { if (callback) { callback(err); } } }); } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; /** * Gets the data that represents this collection for easy storage using * a third-party method / plugin instead of using the standard persistent * storage system. * @param {Function} callback The method to call with the data response. */ Collection.prototype.saveCustom = function (callback) { var self = this, myData = {}, processSave; if (self._name) { if (self._db) { processSave = function () { self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.data = { name: self._db._name + '-' + self._name, store: data, tableStats: tableStats }; self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.metaData = { name: self._db._name + '-' + self._name + '-metaData', store: data, tableStats: tableStats }; callback(false, myData); } else { callback(err); } }); } else { callback(err); } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads custom data loaded by a third-party plugin into the collection. * @param {Object} myData Data object previously saved by using saveCustom() * @param {Function} callback A callback method to receive notification when * data has loaded. */ Collection.prototype.loadCustom = function (myData, callback) { var self = this; if (self._name) { if (self._db) { if (myData.data && myData.data.store) { if (myData.metaData && myData.metaData.store) { self.decode(myData.data.store, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); self.decode(myData.metaData.store, function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); if (callback) { callback(err, tableStats, metaStats); } } } else { callback(err); } }); } } else { callback(err); } }); } else { callback('No "metaData" key found in passed object!'); } } else { callback('No "data" key found in passed object!'); } } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; // Override the DB init to instantiate the plugin Db.prototype.init = function () { DbInit.apply(this, arguments); this.persist = new Persist(this); }; Db.prototype.load = new Overload({ /** * Loads an entire database's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (myData, callback) { this.$main.call(this, myData, callback); }, '$main': function (myData, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, loadCallback, index; loadCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection load method if (!myData) { obj[index].load(loadCallback); } else { obj[index].loadCustom(myData, loadCallback); } } } } }); Db.prototype.save = new Overload({ /** * Saves an entire database's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (options, callback) { this.$main.call(this, options, callback); }, '$main': function (options, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, saveCallback, index; saveCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection save method if (!options.custom) { obj[index].save(saveCallback); } else { obj[index].saveCustom(saveCallback); } } } } }); Shared.finishModule('Persist'); module.exports = Persist; },{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":35,"./PersistCrypto":36,"./Shared":39,"async":41,"localforage":77}],35:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), pako = _dereq_('pako'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); Plugin.prototype.encode = function (val, meta, finished) { var wrapper = { data: val, type: 'fdbCompress', enabled: false }, before, after, compressedVal; // Compress the data before = val.length; compressedVal = pako.deflate(val, {to: 'string'}); after = compressedVal.length; // If the compressed version is smaller than the original, use it! if (after < before) { wrapper.data = compressedVal; wrapper.enabled = true; } meta.compression = { enabled: wrapper.enabled, compressedBytes: after, uncompressedBytes: before, effect: Math.round((100 / before) * after) + '%' }; finished(false, this.jStringify(wrapper), meta); }; Plugin.prototype.decode = function (wrapper, meta, finished) { var compressionEnabled = false, data; if (wrapper) { wrapper = this.jParse(wrapper); // Check if we need to decompress the string if (wrapper.enabled) { data = pako.inflate(wrapper.data, {to: 'string'}); compressionEnabled = true; } else { data = wrapper.data; compressionEnabled = false; } meta.compression = { enabled: compressionEnabled }; if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, data, meta); } } }; // Register this plugin with ForerunnerDB Shared.plugins.FdbCompress = Plugin; module.exports = Plugin; },{"./Shared":39,"pako":78}],36:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), CryptoJS = _dereq_('crypto-js'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { // Ensure at least a password is passed in options if (!options || !options.pass) { throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.'); } this._algo = options.algo || 'AES'; this._pass = options.pass; }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); /** * Gets / sets the current pass-phrase being used to encrypt / decrypt * data with the plugin. */ Shared.synthesize(Plugin.prototype, 'pass'); Plugin.prototype.stringify = function (cipherParams) { // create json object with ciphertext var jsonObj = { ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64) }; // optionally add iv and salt if (cipherParams.iv) { jsonObj.iv = cipherParams.iv.toString(); } if (cipherParams.salt) { jsonObj.s = cipherParams.salt.toString(); } // stringify json object return this.jStringify(jsonObj); }; Plugin.prototype.parse = function (jsonStr) { // parse json string var jsonObj = this.jParse(jsonStr); // extract ciphertext from json object, and create cipher params object var cipherParams = CryptoJS.lib.CipherParams.create({ ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct) }); // optionally extract iv and salt if (jsonObj.iv) { cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv); } if (jsonObj.s) { cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s); } return cipherParams; }; Plugin.prototype.encode = function (val, meta, finished) { var self = this, wrapper = { type: 'fdbCrypto' }, encryptedVal; // Encrypt the data encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }); wrapper.data = encryptedVal.toString(); wrapper.enabled = true; meta.encryption = { enabled: wrapper.enabled }; if (finished) { finished(false, this.jStringify(wrapper), meta); } }; Plugin.prototype.decode = function (wrapper, meta, finished) { var self = this, data; if (wrapper) { wrapper = this.jParse(wrapper); data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }).toString(CryptoJS.enc.Utf8); if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, wrapper, meta); } } }; // Register this plugin with ForerunnerDB Shared.plugins.FdbCrypto = Plugin; module.exports = Plugin; },{"./Shared":39,"crypto-js":50}],37:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); delete this._listeners; } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":39}],38:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { this._encoder = []; this._decoder = {}; // Handler for Date() objects this.registerEncoder('$date', function (data) { if (data instanceof Date) { return data.toISOString(); } }); this.registerDecoder('$date', function (data) { return new Date(data); }); // Handler for RegExp() objects this.registerEncoder('$regexp', function (data) { if (data instanceof RegExp) { return { source: data.source, params: '' + (data.global ? 'g' : '') + (data.ignoreCase ? 'i' : '') }; } }); this.registerDecoder('$regexp', function (data) { var type = typeof data; if (type === 'object') { return new RegExp(data.source, data.params); } else if (type === 'string') { return new RegExp(data); } }); }; /** * Register an encoder that can handle encoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. * @param {Function} method The encoder method. */ Serialiser.prototype.registerEncoder = function (handles, method) { this._encoder.push(function (data) { var methodVal = method(data), returnObj; if (methodVal !== undefined) { returnObj = {}; returnObj[handles] = methodVal; } return returnObj; }); }; /** * Register a decoder that can handle decoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. When an object * has a field matching this handler name then this decode will be invoked * to provide a decoded version of the data that was previously encoded by * it's counterpart encoder method. * @param {Function} method The decoder method. */ Serialiser.prototype.registerDecoder = function (handles, method) { this._decoder[handles] = method; }; /** * Loops the encoders and asks each one if it wants to handle encoding for * the passed data object. If no value is returned (undefined) then the data * will be passed to the next encoder and so on. If a value is returned the * loop will break and the encoded data will be used. * @param {Object} data The data object to handle. * @returns {*} The encoded data. * @private */ Serialiser.prototype._encode = function (data) { // Loop the encoders and if a return value is given by an encoder // the loop will exit and return that value. var count = this._encoder.length, retVal; while (count-- && !retVal) { retVal = this._encoder[count](data); } return retVal; }; /** * Converts a previously encoded string back into an object. * @param {String} data The string to convert to an object. * @returns {Object} The reconstituted object. */ Serialiser.prototype.parse = function (data) { return this._parse(JSON.parse(data)); }; /** * Handles restoring an object with special data markers back into * it's original format. * @param {Object} data The object to recurse. * @param {Object=} target The target object to restore data to. * @returns {Object} The final restored object. * @private */ Serialiser.prototype._parse = function (data, target) { var i; if (typeof data === 'object' && data !== null) { if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and handle // special object types and restore them for (i in data) { if (data.hasOwnProperty(i)) { if (i.substr(0, 1) === '$' && this._decoder[i]) { // This is a special object type and a handler // exists, restore it return this._decoder[i](data[i]); } // Not a special object or no handler, recurse as normal target[i] = this._parse(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; /** * Converts an object to a encoded string representation. * @param {Object} data The object to encode. */ Serialiser.prototype.stringify = function (data) { return JSON.stringify(this._stringify(data)); }; /** * Recurse down an object and encode special objects so they can be * stringified and later restored. * @param {Object} data The object to parse. * @param {Object=} target The target object to store converted data to. * @returns {Object} The converted object. * @private */ Serialiser.prototype._stringify = function (data, target) { var handledData, i; if (typeof data === 'object' && data !== null) { // Handle special object types so they can be encoded with // a special marker and later restored by a decoder counterpart handledData = this._encode(data); if (handledData) { // An encoder handled this object type so return it now return handledData; } if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and serialise for (i in data) { if (data.hasOwnProperty(i)) { target[i] = this._stringify(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; module.exports = Serialiser; },{}],39:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.603', modules: {}, plugins: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":18,"./Mixin.ChainReactor":19,"./Mixin.Common":20,"./Mixin.Constants":21,"./Mixin.Events":22,"./Mixin.Matching":23,"./Mixin.Sorting":24,"./Mixin.Tags":25,"./Mixin.Triggers":26,"./Mixin.Updating":27,"./Overload":31}],40:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket, Overload = _dereq_('./Overload'); Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; View.prototype.init = function (name, query, options) { var self = this; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._privateData = new Collection(this.name() + '_internalPrivate'); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); Shared.mixin(View.prototype, 'Mixin.Triggers'); Shared.mixin(View.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this.publicData().find(query, options); }; /** * Queries the view data for a single document. * @see Collection::findOne() * @returns {Object} The result of the find query. */ View.prototype.findOne = function (query, options) { return this.publicData().findOne(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this.publicData().findById(id, options); }; /** * Queries the view data in a sub-array. * @see Collection::findSub() * @returns {Array} The result of the find query. */ View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this.publicData().findSub(match, path, subDocQuery, subDocOptions); }; /** * Queries the view data in a sub-array and returns first match. * @see Collection::findSubOne() * @returns {Object} The result of the find query. */ View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.publicData().findSubOne(match, path, subDocQuery, subDocOptions); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._privateData; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @param {Function=} callback A callback method. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source, callback) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); delete this._from; } // Check if we have an existing reactor io if (this._io) { // Drop the io and remove it this._io.drop(); delete this._io; } if (typeof(source) === 'string') { source = this._db.collection(source); } if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } this._from = source; this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's "from" source and determines how they should be interpreted by // this view. If the view does not have a query then this reactor IO will // simply pass along the chain packet without modifying it. this._io = new ReactorIO(source, this, function (chainPacket) { var data, diff, query, filteredData, doSend, pk, i; // Check that the state of the "self" object is not dropped if (self && !self.isDropped()) { // Check if we have a constraining query if (self._querySettings.query) { if (chainPacket.type === 'insert') { data = chainPacket.data; // Check if the data matches our query if (data instanceof Array) { filteredData = []; for (i = 0; i < data.length; i++) { if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData.push(data[i]); doSend = true; } } } else { if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData = data; doSend = true; } } if (doSend) { this.chainSend('insert', filteredData); } return true; } if (chainPacket.type === 'update') { // Do a DB diff between this view's data and the underlying collection it reads from // to see if something has changed diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options)); if (diff.insert.length || diff.remove.length) { // Now send out new chain packets for each operation if (diff.insert.length) { this.chainSend('insert', diff.insert); } if (diff.update.length) { pk = self._privateData.primaryKey(); for (i = 0; i < diff.update.length; i++) { query = {}; query[pk] = diff.update[i][pk]; this.chainSend('update', { query: query, update: diff.update[i] }); } } if (diff.remove.length) { pk = self._privateData.primaryKey(); var $or = [], removeQuery = { query: { $or: $or } }; for (i = 0; i < diff.remove.length; i++) { $or.push({_id: diff.remove[i][pk]}); } this.chainSend('remove', removeQuery); } // Return true to stop further propagation of the chain packet return true; } else { // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } } } } // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; }); var collData = source.find(this._querySettings.query, this._querySettings.options); this._privateData.primaryKey(source.primaryKey()); this._privateData.setData(collData, {}, callback); if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._privateData.ensureIndex.apply(this._privateData, arguments); }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, updates, primaryKey, item, currentIndex; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data'); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); this._privateData.setData(collData); break; case 'insert': if (this.debug()) { console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Make sure we are working with an array if (!(chainPacket.data instanceof Array)) { chainPacket.data = [chainPacket.data]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); this._privateData._insertHandle(chainPacket.data, insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._privateData._data.length; this._privateData._insertHandle(chainPacket.data, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"'); } primaryKey = this._privateData.primaryKey(); // Do the update updates = this._privateData.update( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._privateData._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex); } } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"'); } this._privateData.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._privateData.on.apply(this._privateData, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._privateData.off.apply(this._privateData, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._privateData.emit.apply(this._privateData, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { var coll = this.publicData(); return coll.distinct.apply(coll, arguments); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this.publicData().primaryKey(); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._privateData) { this._privateData.drop(); } if (this._publicData && this._publicData !== this._privateData) { this._publicData.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._chain; delete this._from; delete this._privateData; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } return false; }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this.privateData().db(db); this.publicData().db(db); // Apply the same debug settings this.debug(db.debug()); this.privateData().debug(db.debug()); this.publicData().debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} * @deprecated Use query(<query>, <options>, <refresh>) instead. Query * now supports being presented with multiple different variations of * arguments. */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._privateData.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._privateData.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = new Overload({ '': function () { return this._querySettings.query; }, 'object': function (query) { return this.$main.call(this, query, undefined, true); }, '*, boolean': function (query, refresh) { return this.$main.call(this, query, undefined, refresh); }, 'object, object': function (query, options) { return this.$main.call(this, query, options, true); }, '*, *, boolean': function (query, options, refresh) { return this.$main.call(this, query, options, refresh); }, '$main': function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._privateData.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._privateData.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; } }); /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { this.rebuildActiveBucket(options.$orderBy); } return this; } return this._querySettings.options; }; View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._privateData._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._privateData.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { if (this._from) { var pubData = this.publicData(), refreshResults; // Re-grab all the data for the view from the collection this._privateData.remove(); //pubData.remove(); refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); this._privateData.insert(refreshResults); this._privateData._data.$cursor = refreshResults.$cursor; pubData._data.$cursor = refreshResults.$cursor; /*if (pubData._linked) { // Update data and observers //var transformedData = this._privateData.find(); // TODO: Shouldn't this data get passed into a transformIn first? // TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data // TODO: Is this even required anymore? After commenting it all seems to work // TODO: Might be worth setting up a test to check transforms and linking then remove this if working? //jQuery.observable(pubData._data).refresh(transformedData); }*/ } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { if (this.publicData()) { return this.publicData().count.apply(this.publicData(), arguments); } return 0; }; // Call underlying View.prototype.subset = function () { return this.publicData().subset.apply(this._privateData, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { var self = this; if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } if (this._transformEnabled) { // Check for / create the public data collection if (!this._publicData) { // Create the public data collection this._publicData = new Collection('__FDB__view_publicData_' + this._name); this._publicData.db(this._privateData._db); this._publicData.transform({ enabled: true, dataIn: this._transformIn, dataOut: this._transformOut }); // Create a chain reaction IO node to keep the private and // public data collections in sync this._transformIo = new ReactorIO(this._privateData, this._publicData, function (chainPacket) { var data = chainPacket.data; switch (chainPacket.type) { case 'primaryKey': self._publicData.primaryKey(data); this.chainSend('primaryKey', data); break; case 'setData': self._publicData.setData(data); this.chainSend('setData', data); break; case 'insert': self._publicData.insert(data); this.chainSend('insert', data); break; case 'update': // Do the update self._publicData.update( data.query, data.update, data.options ); this.chainSend('update', data); break; case 'remove': self._publicData.remove(data.query, chainPacket.options); this.chainSend('remove', data); break; default: break; } }); } // Set initial data and settings this._publicData.primaryKey(this.privateData().primaryKey()); this._publicData.setData(this.privateData().find()); } else { // Remove the public data collection if (this._publicData) { this._publicData.drop(); delete this._publicData; if (this._transformIo) { this._transformIo.drop(); delete this._transformIo; } } } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return (this.publicData()).filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.privateData = function () { return this._privateData; }; /** * Returns a data object representing the public data this view * contains. This can change depending on if transforms are being * applied to the view or not. * * If no transforms are applied then the public data will be the * same as the private data the view holds. If transforms are * applied then the public data will contain the transformed version * of the private data. * * The public data collection is also used by data binding to only * changes to the publicData will show in a data-bound element. */ View.prototype.publicData = function () { if (this._transformEnabled) { return this._publicData; } else { return this._privateData; } }; // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (viewName) { var self = this; // Handle being passed an instance if (viewName instanceof View) { return viewName; } if (this._view[viewName]) { return this._view[viewName]; } else { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + viewName); } } this._view[viewName] = this._view[viewName] || new View(viewName).db(this); self.emit('create', [self._view[viewName], 'view', viewName]); return this._view[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (viewName) { return Boolean(this._view[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":2,"./Collection":4,"./CollectionGroup":5,"./Overload":31,"./ReactorIO":37,"./Shared":39}],41:[function(_dereq_,module,exports){ (function (process,global){ /*! * async * https://github.com/caolan/async * * Copyright 2010-2014 Caolan McMahon * Released under the MIT license */ (function () { var async = {}; function noop() {} function identity(v) { return v; } function toBool(v) { return !!v; } function notId(v) { return !v; } // global on the server, window in the browser var previous_async; // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. var root = typeof self === 'object' && self.self === self && self || typeof global === 'object' && global.global === global && global || this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { return function() { if (fn === null) throw new Error("Callback was already called."); fn.apply(this, arguments); fn = null; }; } function _once(fn) { return function() { if (fn === null) return; fn.apply(this, arguments); fn = null; }; } //// cross-browser compatiblity functions //// var _toString = Object.prototype.toString; var _isArray = Array.isArray || function (obj) { return _toString.call(obj) === '[object Array]'; }; // Ported from underscore.js isObject var _isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; function _isArrayLike(arr) { return _isArray(arr) || ( // has a positive integer length property typeof arr.length === "number" && arr.length >= 0 && arr.length % 1 === 0 ); } function _arrayEach(arr, iterator) { var index = -1, length = arr.length; while (++index < length) { iterator(arr[index], index, arr); } } function _map(arr, iterator) { var index = -1, length = arr.length, result = Array(length); while (++index < length) { result[index] = iterator(arr[index], index, arr); } return result; } function _range(count) { return _map(Array(count), function (v, i) { return i; }); } function _reduce(arr, iterator, memo) { _arrayEach(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; } function _forEachOf(object, iterator) { _arrayEach(_keys(object), function (key) { iterator(object[key], key); }); } function _indexOf(arr, item) { for (var i = 0; i < arr.length; i++) { if (arr[i] === item) return i; } return -1; } var _keys = Object.keys || function (obj) { var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; function _keyIterator(coll) { var i = -1; var len; var keys; if (_isArrayLike(coll)) { len = coll.length; return function next() { i++; return i < len ? i : null; }; } else { keys = _keys(coll); len = keys.length; return function next() { i++; return i < len ? keys[i] : null; }; } } // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) // This accumulates the arguments passed into an array, after a given index. // From underscore.js (https://github.com/jashkenas/underscore/pull/2140). function _restParam(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0); var rest = Array(length); for (var index = 0; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); } // Currently unused but handle cases outside of the switch statement: // var args = Array(startIndex + 1); // for (index = 0; index < startIndex; index++) { // args[index] = arguments[index]; // } // args[startIndex] = rest; // return func.apply(this, args); }; } function _withoutIndex(iterator) { return function (value, index, callback) { return iterator(value, callback); }; } //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// // capture the global reference to guard against fakeTimer mocks var _setImmediate = typeof setImmediate === 'function' && setImmediate; var _delay = _setImmediate ? function(fn) { // not a direct alias for IE10 compatibility _setImmediate(fn); } : function(fn) { setTimeout(fn, 0); }; if (typeof process === 'object' && typeof process.nextTick === 'function') { async.nextTick = process.nextTick; } else { async.nextTick = _delay; } async.setImmediate = _setImmediate ? _delay : async.nextTick; async.forEach = async.each = function (arr, iterator, callback) { return async.eachOf(arr, _withoutIndex(iterator), callback); }; async.forEachSeries = async.eachSeries = function (arr, iterator, callback) { return async.eachOfSeries(arr, _withoutIndex(iterator), callback); }; async.forEachLimit = async.eachLimit = function (arr, limit, iterator, callback) { return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback); }; async.forEachOf = async.eachOf = function (object, iterator, callback) { callback = _once(callback || noop); object = object || []; var iter = _keyIterator(object); var key, completed = 0; while ((key = iter()) != null) { completed += 1; iterator(object[key], key, only_once(done)); } if (completed === 0) callback(null); function done(err) { completed--; if (err) { callback(err); } // Check key is null in case iterator isn't exhausted // and done resolved synchronously. else if (key === null && completed <= 0) { callback(null); } } }; async.forEachOfSeries = async.eachOfSeries = function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); var key = nextKey(); function iterate() { var sync = true; if (key === null) { return callback(null); } iterator(obj[key], key, only_once(function (err) { if (err) { callback(err); } else { key = nextKey(); if (key === null) { return callback(null); } else { if (sync) { async.setImmediate(iterate); } else { iterate(); } } } })); sync = false; } iterate(); }; async.forEachOfLimit = async.eachOfLimit = function (obj, limit, iterator, callback) { _eachOfLimit(limit)(obj, iterator, callback); }; function _eachOfLimit(limit) { return function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); if (limit <= 0) { return callback(null); } var done = false; var running = 0; var errored = false; (function replenish () { if (done && running <= 0) { return callback(null); } while (running < limit && !errored) { var key = nextKey(); if (key === null) { done = true; if (running <= 0) { callback(null); } return; } running += 1; iterator(obj[key], key, only_once(function (err) { running -= 1; if (err) { callback(err); errored = true; } else { replenish(); } })); } })(); }; } function doParallel(fn) { return function (obj, iterator, callback) { return fn(async.eachOf, obj, iterator, callback); }; } function doParallelLimit(fn) { return function (obj, limit, iterator, callback) { return fn(_eachOfLimit(limit), obj, iterator, callback); }; } function doSeries(fn) { return function (obj, iterator, callback) { return fn(async.eachOfSeries, obj, iterator, callback); }; } function _asyncMap(eachfn, arr, iterator, callback) { callback = _once(callback || noop); arr = arr || []; var results = _isArrayLike(arr) ? [] : {}; eachfn(arr, function (value, index, callback) { iterator(value, function (err, v) { results[index] = v; callback(err); }); }, function (err) { callback(err, results); }); } async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = doParallelLimit(_asyncMap); // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.inject = async.foldl = async.reduce = function (arr, memo, iterator, callback) { async.eachOfSeries(arr, function (x, i, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; async.foldr = async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, identity).reverse(); async.reduce(reversed, memo, iterator, callback); }; async.transform = function (arr, memo, iterator, callback) { if (arguments.length === 3) { callback = iterator; iterator = memo; memo = _isArray(arr) ? [] : {}; } async.eachOf(arr, function(v, k, cb) { iterator(memo, v, k, cb); }, function(err) { callback(err, memo); }); }; function _filter(eachfn, arr, iterator, callback) { var results = []; eachfn(arr, function (x, index, callback) { iterator(x, function (v) { if (v) { results.push({index: index, value: x}); } callback(); }); }, function () { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); } async.select = async.filter = doParallel(_filter); async.selectLimit = async.filterLimit = doParallelLimit(_filter); async.selectSeries = async.filterSeries = doSeries(_filter); function _reject(eachfn, arr, iterator, callback) { _filter(eachfn, arr, function(value, cb) { iterator(value, function(v) { cb(!v); }); }, callback); } async.reject = doParallel(_reject); async.rejectLimit = doParallelLimit(_reject); async.rejectSeries = doSeries(_reject); function _createTester(eachfn, check, getResult) { return function(arr, limit, iterator, cb) { function done() { if (cb) cb(getResult(false, void 0)); } function iteratee(x, _, callback) { if (!cb) return callback(); iterator(x, function (v) { if (cb && check(v)) { cb(getResult(true, x)); cb = iterator = false; } callback(); }); } if (arguments.length > 3) { eachfn(arr, limit, iteratee, done); } else { cb = iterator; iterator = limit; eachfn(arr, iteratee, done); } }; } async.any = async.some = _createTester(async.eachOf, toBool, identity); async.someLimit = _createTester(async.eachOfLimit, toBool, identity); async.all = async.every = _createTester(async.eachOf, notId, notId); async.everyLimit = _createTester(async.eachOfLimit, notId, notId); function _findGetResult(v, x) { return x; } async.detect = _createTester(async.eachOf, identity, _findGetResult); async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult); async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult); async.sortBy = function (arr, iterator, callback) { async.map(arr, function (x, callback) { iterator(x, function (err, criteria) { if (err) { callback(err); } else { callback(null, {value: x, criteria: criteria}); } }); }, function (err, results) { if (err) { return callback(err); } else { callback(null, _map(results.sort(comparator), function (x) { return x.value; })); } }); function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } }; async.auto = function (tasks, concurrency, callback) { if (!callback) { // concurrency is optional, shift the args. callback = concurrency; concurrency = null; } callback = _once(callback || noop); var keys = _keys(tasks); var remainingTasks = keys.length; if (!remainingTasks) { return callback(null); } if (!concurrency) { concurrency = remainingTasks; } var results = {}; var runningTasks = 0; var listeners = []; function addListener(fn) { listeners.unshift(fn); } function removeListener(fn) { var idx = _indexOf(listeners, fn); if (idx >= 0) listeners.splice(idx, 1); } function taskComplete() { remainingTasks--; _arrayEach(listeners.slice(0), function (fn) { fn(); }); } addListener(function () { if (!remainingTasks) { callback(null, results); } }); _arrayEach(keys, function (k) { var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; var taskCallback = _restParam(function(err, args) { runningTasks--; if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _forEachOf(results, function(val, rkey) { safeResults[rkey] = val; }); safeResults[k] = args; callback(err, safeResults); } else { results[k] = args; async.setImmediate(taskComplete); } }); var requires = task.slice(0, task.length - 1); // prevent dead-locks var len = requires.length; var dep; while (len--) { if (!(dep = tasks[requires[len]])) { throw new Error('Has inexistant dependency'); } if (_isArray(dep) && _indexOf(dep, k) >= 0) { throw new Error('Has cyclic dependencies'); } } function ready() { return runningTasks < concurrency && _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); } if (ready()) { runningTasks++; task[task.length - 1](taskCallback, results); } else { addListener(listener); } function listener() { if (ready()) { runningTasks++; removeListener(listener); task[task.length - 1](taskCallback, results); } } }); }; async.retry = function(times, task, callback) { var DEFAULT_TIMES = 5; var DEFAULT_INTERVAL = 0; var attempts = []; var opts = { times: DEFAULT_TIMES, interval: DEFAULT_INTERVAL }; function parseTimes(acc, t){ if(typeof t === 'number'){ acc.times = parseInt(t, 10) || DEFAULT_TIMES; } else if(typeof t === 'object'){ acc.times = parseInt(t.times, 10) || DEFAULT_TIMES; acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL; } else { throw new Error('Unsupported argument type for \'times\': ' + typeof t); } } var length = arguments.length; if (length < 1 || length > 3) { throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)'); } else if (length <= 2 && typeof times === 'function') { callback = task; task = times; } if (typeof times !== 'function') { parseTimes(opts, times); } opts.callback = callback; opts.task = task; function wrappedTask(wrappedCallback, wrappedResults) { function retryAttempt(task, finalAttempt) { return function(seriesCallback) { task(function(err, result){ seriesCallback(!err || finalAttempt, {err: err, result: result}); }, wrappedResults); }; } function retryInterval(interval){ return function(seriesCallback){ setTimeout(function(){ seriesCallback(null); }, interval); }; } while (opts.times) { var finalAttempt = !(opts.times-=1); attempts.push(retryAttempt(opts.task, finalAttempt)); if(!finalAttempt && opts.interval > 0){ attempts.push(retryInterval(opts.interval)); } } async.series(attempts, function(done, data){ data = data[data.length - 1]; (wrappedCallback || opts.callback)(data.err, data.result); }); } // If a callback is passed, run this as a controll flow return opts.callback ? wrappedTask() : wrappedTask; }; async.waterfall = function (tasks, callback) { callback = _once(callback || noop); if (!_isArray(tasks)) { var err = new Error('First argument to waterfall must be an array of functions'); return callback(err); } if (!tasks.length) { return callback(); } function wrapIterator(iterator) { return _restParam(function (err, args) { if (err) { callback.apply(null, [err].concat(args)); } else { var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } ensureAsync(iterator).apply(null, args); } }); } wrapIterator(async.iterator(tasks))(); }; function _parallel(eachfn, tasks, callback) { callback = callback || noop; var results = _isArrayLike(tasks) ? [] : {}; eachfn(tasks, function (task, key, callback) { task(_restParam(function (err, args) { if (args.length <= 1) { args = args[0]; } results[key] = args; callback(err); })); }, function (err) { callback(err, results); }); } async.parallel = function (tasks, callback) { _parallel(async.eachOf, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel(_eachOfLimit(limit), tasks, callback); }; async.series = function(tasks, callback) { _parallel(async.eachOfSeries, tasks, callback); }; async.iterator = function (tasks) { function makeCallback(index) { function fn() { if (tasks.length) { tasks[index].apply(null, arguments); } return fn.next(); } fn.next = function () { return (index < tasks.length - 1) ? makeCallback(index + 1): null; }; return fn; } return makeCallback(0); }; async.apply = _restParam(function (fn, args) { return _restParam(function (callArgs) { return fn.apply( null, args.concat(callArgs) ); }); }); function _concat(eachfn, arr, fn, callback) { var result = []; eachfn(arr, function (x, index, cb) { fn(x, function (err, y) { result = result.concat(y || []); cb(err); }); }, function (err) { callback(err, result); }); } async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { callback = callback || noop; if (test()) { var next = _restParam(function(err, args) { if (err) { callback(err); } else if (test.apply(this, args)) { iterator(next); } else { callback(null); } }); iterator(next); } else { callback(null); } }; async.doWhilst = function (iterator, test, callback) { var calls = 0; return async.whilst(function() { return ++calls <= 1 || test.apply(this, arguments); }, iterator, callback); }; async.until = function (test, iterator, callback) { return async.whilst(function() { return !test.apply(this, arguments); }, iterator, callback); }; async.doUntil = function (iterator, test, callback) { return async.doWhilst(iterator, function() { return !test.apply(this, arguments); }, callback); }; async.during = function (test, iterator, callback) { callback = callback || noop; var next = _restParam(function(err, args) { if (err) { callback(err); } else { args.push(check); test.apply(this, args); } }); var check = function(err, truth) { if (err) { callback(err); } else if (truth) { iterator(next); } else { callback(null); } }; test(check); }; async.doDuring = function (iterator, test, callback) { var calls = 0; async.during(function(next) { if (calls++ < 1) { next(null, true); } else { test.apply(this, arguments); } }, iterator, callback); }; function _queue(worker, concurrency, payload) { if (concurrency == null) { concurrency = 1; } else if(concurrency === 0) { throw new Error('Concurrency must not be zero'); } function _insert(q, data, pos, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0 && q.idle()) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, callback: callback || noop }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.tasks.length === q.concurrency) { q.saturated(); } }); async.setImmediate(q.process); } function _next(q, tasks) { return function(){ workers -= 1; var removed = false; var args = arguments; _arrayEach(tasks, function (task) { _arrayEach(workersList, function (worker, index) { if (worker === task && !removed) { workersList.splice(index, 1); removed = true; } }); task.callback.apply(task, args); }); if (q.tasks.length + workers === 0) { q.drain(); } q.process(); }; } var workers = 0; var workersList = []; var q = { tasks: [], concurrency: concurrency, payload: payload, saturated: noop, empty: noop, drain: noop, started: false, paused: false, push: function (data, callback) { _insert(q, data, false, callback); }, kill: function () { q.drain = noop; q.tasks = []; }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { if (!q.paused && workers < q.concurrency && q.tasks.length) { while(workers < q.concurrency && q.tasks.length){ var tasks = q.payload ? q.tasks.splice(0, q.payload) : q.tasks.splice(0, q.tasks.length); var data = _map(tasks, function (task) { return task.data; }); if (q.tasks.length === 0) { q.empty(); } workers += 1; workersList.push(tasks[0]); var cb = only_once(_next(q, tasks)); worker(data, cb); } } }, length: function () { return q.tasks.length; }, running: function () { return workers; }, workersList: function () { return workersList; }, idle: function() { return q.tasks.length + workers === 0; }, pause: function () { q.paused = true; }, resume: function () { if (q.paused === false) { return; } q.paused = false; var resumeCount = Math.min(q.concurrency, q.tasks.length); // Need to call q.process once per concurrent // worker to preserve full concurrency after pause for (var w = 1; w <= resumeCount; w++) { async.setImmediate(q.process); } } }; return q; } async.queue = function (worker, concurrency) { var q = _queue(function (items, cb) { worker(items[0], cb); }, concurrency, 1); return q; }; async.priorityQueue = function (worker, concurrency) { function _compareTasks(a, b){ return a.priority - b.priority; } function _binarySearch(sequence, item, compare) { var beg = -1, end = sequence.length - 1; while (beg < end) { var mid = beg + ((end - beg + 1) >>> 1); if (compare(item, sequence[mid]) >= 0) { beg = mid; } else { end = mid - 1; } } return beg; } function _insert(q, data, priority, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, priority: priority, callback: typeof callback === 'function' ? callback : noop }; q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); if (q.tasks.length === q.concurrency) { q.saturated(); } async.setImmediate(q.process); }); } // Start with a normal queue var q = async.queue(worker, concurrency); // Override push to accept second parameter representing priority q.push = function (data, priority, callback) { _insert(q, data, priority, callback); }; // Remove unshift function delete q.unshift; return q; }; async.cargo = function (worker, payload) { return _queue(worker, 1, payload); }; function _console_fn(name) { return _restParam(function (fn, args) { fn.apply(null, args.concat([_restParam(function (err, args) { if (typeof console === 'object') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _arrayEach(args, function (x) { console[name](x); }); } } })])); }); } async.log = _console_fn('log'); async.dir = _console_fn('dir'); /*async.info = _console_fn('info'); async.warn = _console_fn('warn'); async.error = _console_fn('error');*/ async.memoize = function (fn, hasher) { var memo = {}; var queues = {}; hasher = hasher || identity; var memoized = _restParam(function memoized(args) { var callback = args.pop(); var key = hasher.apply(null, args); if (key in memo) { async.setImmediate(function () { callback.apply(null, memo[key]); }); } else if (key in queues) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([_restParam(function (args) { memo[key] = args; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, args); } })])); } }); memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; function _times(mapper) { return function (count, iterator, callback) { mapper(_range(count), iterator, callback); }; } async.times = _times(async.map); async.timesSeries = _times(async.mapSeries); async.timesLimit = function (count, limit, iterator, callback) { return async.mapLimit(_range(count), limit, iterator, callback); }; async.seq = function (/* functions... */) { var fns = arguments; return _restParam(function (args) { var that = this; var callback = args[args.length - 1]; if (typeof callback == 'function') { args.pop(); } else { callback = noop; } async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([_restParam(function (err, nextargs) { cb(err, nextargs); })])); }, function (err, results) { callback.apply(that, [err].concat(results)); }); }); }; async.compose = function (/* functions... */) { return async.seq.apply(null, Array.prototype.reverse.call(arguments)); }; function _applyEach(eachfn) { return _restParam(function(fns, args) { var go = _restParam(function(args) { var that = this; var callback = args.pop(); return eachfn(fns, function (fn, _, cb) { fn.apply(that, args.concat([cb])); }, callback); }); if (args.length) { return go.apply(this, args); } else { return go; } }); } async.applyEach = _applyEach(async.eachOf); async.applyEachSeries = _applyEach(async.eachOfSeries); async.forever = function (fn, callback) { var done = only_once(callback || noop); var task = ensureAsync(fn); function next(err) { if (err) { return done(err); } task(next); } next(); }; function ensureAsync(fn) { return _restParam(function (args) { var callback = args.pop(); args.push(function () { var innerArgs = arguments; if (sync) { async.setImmediate(function () { callback.apply(null, innerArgs); }); } else { callback.apply(null, innerArgs); } }); var sync = true; fn.apply(this, args); sync = false; }); } async.ensureAsync = ensureAsync; async.constant = _restParam(function(values) { var args = [null].concat(values); return function (callback) { return callback.apply(this, args); }; }); async.wrapSync = async.asyncify = function asyncify(func) { return _restParam(function (args) { var callback = args.pop(); var result; try { result = func.apply(this, args); } catch (e) { return callback(e); } // if result is Promise object if (_isObject(result) && typeof result.then === "function") { result.then(function(value) { callback(null, value); })["catch"](function(err) { callback(err.message ? err : new Error(err)); }); } else { callback(null, result); } }); }; // Node.js if (typeof module === 'object' && module.exports) { module.exports = async; } // AMD / RequireJS else if (typeof define === 'function' && define.amd) { define([], function () { return async; }); } // included directly via <script> tag else { root.async = async; } }()); }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":76}],42:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Lookup tables var SBOX = []; var INV_SBOX = []; var SUB_MIX_0 = []; var SUB_MIX_1 = []; var SUB_MIX_2 = []; var SUB_MIX_3 = []; var INV_SUB_MIX_0 = []; var INV_SUB_MIX_1 = []; var INV_SUB_MIX_2 = []; var INV_SUB_MIX_3 = []; // Compute lookup tables (function () { // Compute double table var d = []; for (var i = 0; i < 256; i++) { if (i < 128) { d[i] = i << 1; } else { d[i] = (i << 1) ^ 0x11b; } } // Walk GF(2^8) var x = 0; var xi = 0; for (var i = 0; i < 256; i++) { // Compute sbox var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; SBOX[x] = sx; INV_SBOX[sx] = x; // Compute multiplication var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; // Compute sub bytes, mix columns tables var t = (d[sx] * 0x101) ^ (sx * 0x1010100); SUB_MIX_0[x] = (t << 24) | (t >>> 8); SUB_MIX_1[x] = (t << 16) | (t >>> 16); SUB_MIX_2[x] = (t << 8) | (t >>> 24); SUB_MIX_3[x] = t; // Compute inv sub bytes, inv mix columns tables var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); INV_SUB_MIX_3[sx] = t; // Compute next counter if (!x) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } }()); // Precomputed Rcon lookup var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; /** * AES block cipher algorithm. */ var AES = C_algo.AES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySize = key.sigBytes / 4; // Compute number of rounds var nRounds = this._nRounds = keySize + 6 // Compute number of key schedule rows var ksRows = (nRounds + 1) * 4; // Compute key schedule var keySchedule = this._keySchedule = []; for (var ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { keySchedule[ksRow] = keyWords[ksRow]; } else { var t = keySchedule[ksRow - 1]; if (!(ksRow % keySize)) { // Rot word t = (t << 8) | (t >>> 24); // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; // Mix Rcon t ^= RCON[(ksRow / keySize) | 0] << 24; } else if (keySize > 6 && ksRow % keySize == 4) { // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; } keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; } } // Compute inv key schedule var invKeySchedule = this._invKeySchedule = []; for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { var ksRow = ksRows - invKsRow; if (invKsRow % 4) { var t = keySchedule[ksRow]; } else { var t = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t; } else { invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; } } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); }, decryptBlock: function (M, offset) { // Swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); // Inv swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; }, _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { // Shortcut var nRounds = this._nRounds; // Get input, add round key var s0 = M[offset] ^ keySchedule[0]; var s1 = M[offset + 1] ^ keySchedule[1]; var s2 = M[offset + 2] ^ keySchedule[2]; var s3 = M[offset + 3] ^ keySchedule[3]; // Key schedule row counter var ksRow = 4; // Rounds for (var round = 1; round < nRounds; round++) { // Shift rows, sub bytes, mix columns, add round key var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; // Update state s0 = t0; s1 = t1; s2 = t2; s3 = t3; } // Shift rows, sub bytes, add round key var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; // Set output M[offset] = t0; M[offset + 1] = t1; M[offset + 2] = t2; M[offset + 3] = t3; }, keySize: 256/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); */ C.AES = BlockCipher._createHelper(AES); }()); return CryptoJS.AES; })); },{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],43:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher core components. */ CryptoJS.lib.Cipher || (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var Base64 = C_enc.Base64; var C_algo = C.algo; var EvpKDF = C_algo.EvpKDF; /** * Abstract base cipher template. * * @property {number} keySize This cipher's key size. Default: 4 (128 bits) * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. */ var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ /** * Configuration options. * * @property {WordArray} iv The IV to use for this operation. */ cfg: Base.extend(), /** * Creates this cipher in encryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); */ createEncryptor: function (key, cfg) { return this.create(this._ENC_XFORM_MODE, key, cfg); }, /** * Creates this cipher in decryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); */ createDecryptor: function (key, cfg) { return this.create(this._DEC_XFORM_MODE, key, cfg); }, /** * Initializes a newly created cipher. * * @param {number} xformMode Either the encryption or decryption transormation mode constant. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @example * * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); */ init: function (xformMode, key, cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Store transform mode and key this._xformMode = xformMode; this._key = key; // Set initial values this.reset(); }, /** * Resets this cipher to its initial state. * * @example * * cipher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-cipher logic this._doReset(); }, /** * Adds data to be encrypted or decrypted. * * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. * * @return {WordArray} The data after processing. * * @example * * var encrypted = cipher.process('data'); * var encrypted = cipher.process(wordArray); */ process: function (dataUpdate) { // Append this._append(dataUpdate); // Process available blocks return this._process(); }, /** * Finalizes the encryption or decryption process. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. * * @return {WordArray} The data after final processing. * * @example * * var encrypted = cipher.finalize(); * var encrypted = cipher.finalize('data'); * var encrypted = cipher.finalize(wordArray); */ finalize: function (dataUpdate) { // Final data update if (dataUpdate) { this._append(dataUpdate); } // Perform concrete-cipher logic var finalProcessedData = this._doFinalize(); return finalProcessedData; }, keySize: 128/32, ivSize: 128/32, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, /** * Creates shortcut functions to a cipher's object interface. * * @param {Cipher} cipher The cipher to create a helper for. * * @return {Object} An object with encrypt and decrypt shortcut functions. * * @static * * @example * * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); */ _createHelper: (function () { function selectCipherStrategy(key) { if (typeof key == 'string') { return PasswordBasedCipher; } else { return SerializableCipher; } } return function (cipher) { return { encrypt: function (message, key, cfg) { return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); }, decrypt: function (ciphertext, key, cfg) { return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); } }; }; }()) }); /** * Abstract base stream cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) */ var StreamCipher = C_lib.StreamCipher = Cipher.extend({ _doFinalize: function () { // Process partial blocks var finalProcessedBlocks = this._process(!!'flush'); return finalProcessedBlocks; }, blockSize: 1 }); /** * Mode namespace. */ var C_mode = C.mode = {}; /** * Abstract base block cipher mode template. */ var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ /** * Creates this mode for encryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); */ createEncryptor: function (cipher, iv) { return this.Encryptor.create(cipher, iv); }, /** * Creates this mode for decryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); */ createDecryptor: function (cipher, iv) { return this.Decryptor.create(cipher, iv); }, /** * Initializes a newly created mode. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @example * * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); */ init: function (cipher, iv) { this._cipher = cipher; this._iv = iv; } }); /** * Cipher Block Chaining mode. */ var CBC = C_mode.CBC = (function () { /** * Abstract base CBC mode. */ var CBC = BlockCipherMode.extend(); /** * CBC encryptor. */ CBC.Encryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // XOR and encrypt xorBlock.call(this, words, offset, blockSize); cipher.encryptBlock(words, offset); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); /** * CBC decryptor. */ CBC.Decryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); // Decrypt and XOR cipher.decryptBlock(words, offset); xorBlock.call(this, words, offset, blockSize); // This block becomes the previous block this._prevBlock = thisBlock; } }); function xorBlock(words, offset, blockSize) { // Shortcut var iv = this._iv; // Choose mixing block if (iv) { var block = iv; // Remove IV for subsequent blocks this._iv = undefined; } else { var block = this._prevBlock; } // XOR blocks for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } } return CBC; }()); /** * Padding namespace. */ var C_pad = C.pad = {}; /** * PKCS #5/7 padding strategy. */ var Pkcs7 = C_pad.Pkcs7 = { /** * Pads data using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to pad. * @param {number} blockSize The multiple that the data should be padded to. * * @static * * @example * * CryptoJS.pad.Pkcs7.pad(wordArray, 4); */ pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Create padding word var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; // Create padding var paddingWords = []; for (var i = 0; i < nPaddingBytes; i += 4) { paddingWords.push(paddingWord); } var padding = WordArray.create(paddingWords, nPaddingBytes); // Add padding data.concat(padding); }, /** * Unpads data that had been padded using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to unpad. * * @static * * @example * * CryptoJS.pad.Pkcs7.unpad(wordArray); */ unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; /** * Abstract base block cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) */ var BlockCipher = C_lib.BlockCipher = Cipher.extend({ /** * Configuration options. * * @property {Mode} mode The block mode to use. Default: CBC * @property {Padding} padding The padding strategy to use. Default: Pkcs7 */ cfg: Cipher.cfg.extend({ mode: CBC, padding: Pkcs7 }), reset: function () { // Reset cipher Cipher.reset.call(this); // Shortcuts var cfg = this.cfg; var iv = cfg.iv; var mode = cfg.mode; // Reset block mode if (this._xformMode == this._ENC_XFORM_MODE) { var modeCreator = mode.createEncryptor; } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { var modeCreator = mode.createDecryptor; // Keep at least one block in the buffer for unpadding this._minBufferSize = 1; } this._mode = modeCreator.call(mode, this, iv && iv.words); }, _doProcessBlock: function (words, offset) { this._mode.processBlock(words, offset); }, _doFinalize: function () { // Shortcut var padding = this.cfg.padding; // Finalize if (this._xformMode == this._ENC_XFORM_MODE) { // Pad data padding.pad(this._data, this.blockSize); // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); // Unpad data padding.unpad(finalProcessedBlocks); } return finalProcessedBlocks; }, blockSize: 128/32 }); /** * A collection of cipher parameters. * * @property {WordArray} ciphertext The raw ciphertext. * @property {WordArray} key The key to this ciphertext. * @property {WordArray} iv The IV used in the ciphering operation. * @property {WordArray} salt The salt used with a key derivation function. * @property {Cipher} algorithm The cipher algorithm. * @property {Mode} mode The block mode used in the ciphering operation. * @property {Padding} padding The padding scheme used in the ciphering operation. * @property {number} blockSize The block size of the cipher. * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. */ var CipherParams = C_lib.CipherParams = Base.extend({ /** * Initializes a newly created cipher params object. * * @param {Object} cipherParams An object with any of the possible cipher parameters. * * @example * * var cipherParams = CryptoJS.lib.CipherParams.create({ * ciphertext: ciphertextWordArray, * key: keyWordArray, * iv: ivWordArray, * salt: saltWordArray, * algorithm: CryptoJS.algo.AES, * mode: CryptoJS.mode.CBC, * padding: CryptoJS.pad.PKCS7, * blockSize: 4, * formatter: CryptoJS.format.OpenSSL * }); */ init: function (cipherParams) { this.mixIn(cipherParams); }, /** * Converts this cipher params object to a string. * * @param {Format} formatter (Optional) The formatting strategy to use. * * @return {string} The stringified cipher params. * * @throws Error If neither the formatter nor the default formatter is set. * * @example * * var string = cipherParams + ''; * var string = cipherParams.toString(); * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ toString: function (formatter) { return (formatter || this.formatter).stringify(this); } }); /** * Format namespace. */ var C_format = C.format = {}; /** * OpenSSL formatting strategy. */ var OpenSSLFormatter = C_format.OpenSSL = { /** * Converts a cipher params object to an OpenSSL-compatible string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The OpenSSL-compatible string. * * @static * * @example * * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); */ stringify: function (cipherParams) { // Shortcuts var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; // Format if (salt) { var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); } else { var wordArray = ciphertext; } return wordArray.toString(Base64); }, /** * Converts an OpenSSL-compatible string to a cipher params object. * * @param {string} openSSLStr The OpenSSL-compatible string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); */ parse: function (openSSLStr) { // Parse base64 var ciphertext = Base64.parse(openSSLStr); // Shortcut var ciphertextWords = ciphertext.words; // Test for salt if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { // Extract salt var salt = WordArray.create(ciphertextWords.slice(2, 4)); // Remove salt from ciphertext ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext: ciphertext, salt: salt }); } }; /** * A cipher wrapper that returns ciphertext as a serializable cipher params object. */ var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** * Configuration options. * * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } } }); /** * Key derivation function namespace. */ var C_kdf = C.kdf = {}; /** * OpenSSL key derivation function. */ var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); } }; /** * A serializable cipher wrapper that derives the key from a password, * and returns ciphertext as a serializable cipher params object. */ var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }()); })); },{"./core":44}],44:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD define([], factory); } else { // Global (browser) root.CryptoJS = factory(); } }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { function F() {} return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn F.prototype = this; var subtype = new F(); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init')) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); },{}],45:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex != -1) { base64StrLength = paddingIndex; } } // Convert var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }()); return CryptoJS.enc.Base64; })); },{"./core":44}],46:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * UTF-16 BE encoding strategy. */ var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { /** * Converts a word array to a UTF-16 BE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 BE string. * * @static * * @example * * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 BE string to a word array. * * @param {string} utf16Str The UTF-16 BE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); } return WordArray.create(words, utf16StrLength * 2); } }; /** * UTF-16 LE encoding strategy. */ C_enc.Utf16LE = { /** * Converts a word array to a UTF-16 LE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 LE string. * * @static * * @example * * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 LE string to a word array. * * @param {string} utf16Str The UTF-16 LE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); } return WordArray.create(words, utf16StrLength * 2); } }; function swapEndian(word) { return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); } }()); return CryptoJS.enc.Utf16; })); },{"./core":44}],47:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var MD5 = C_algo.MD5; /** * This key derivation function is meant to conform with EVP_BytesToKey. * www.openssl.org/docs/crypto/EVP_BytesToKey.html */ var EvpKDF = C_algo.EvpKDF = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hash algorithm to use. Default: MD5 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: MD5, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.EvpKDF.create(); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init hasher var hasher = cfg.hasher.create(); // Initial values var derivedKey = WordArray.create(); // Shortcuts var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } var block = hasher.update(password).finalize(salt); hasher.reset(); // Iterations for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.EvpKDF(password, salt); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); */ C.EvpKDF = function (password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); }; }()); return CryptoJS.EvpKDF; })); },{"./core":44,"./hmac":49,"./sha1":68}],48:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var CipherParams = C_lib.CipherParams; var C_enc = C.enc; var Hex = C_enc.Hex; var C_format = C.format; var HexFormatter = C_format.Hex = { /** * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The hexadecimally encoded string. * * @static * * @example * * var hexString = CryptoJS.format.Hex.stringify(cipherParams); */ stringify: function (cipherParams) { return cipherParams.ciphertext.toString(Hex); }, /** * Converts a hexadecimally encoded ciphertext string to a cipher params object. * * @param {string} input The hexadecimally encoded string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.Hex.parse(hexString); */ parse: function (input) { var ciphertext = Hex.parse(input); return CipherParams.create({ ciphertext: ciphertext }); } }; }()); return CryptoJS.format.Hex; })); },{"./cipher-core":43,"./core":44}],49:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var C_algo = C.algo; /** * HMAC algorithm. */ var HMAC = C_algo.HMAC = Base.extend({ /** * Initializes a newly created HMAC. * * @param {Hasher} hasher The hash algorithm to use. * @param {WordArray|string} key The secret key. * * @example * * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); */ init: function (hasher, key) { // Init hasher hasher = this._hasher = new hasher.init(); // Convert string to WordArray, else assume WordArray already if (typeof key == 'string') { key = Utf8.parse(key); } // Shortcuts var hasherBlockSize = hasher.blockSize; var hasherBlockSizeBytes = hasherBlockSize * 4; // Allow arbitrary length keys if (key.sigBytes > hasherBlockSizeBytes) { key = hasher.finalize(key); } // Clamp excess bits key.clamp(); // Clone key for inner and outer pads var oKey = this._oKey = key.clone(); var iKey = this._iKey = key.clone(); // Shortcuts var oKeyWords = oKey.words; var iKeyWords = iKey.words; // XOR keys with pad constants for (var i = 0; i < hasherBlockSize; i++) { oKeyWords[i] ^= 0x5c5c5c5c; iKeyWords[i] ^= 0x36363636; } oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; // Set initial values this.reset(); }, /** * Resets this HMAC to its initial state. * * @example * * hmacHasher.reset(); */ reset: function () { // Shortcut var hasher = this._hasher; // Reset hasher.reset(); hasher.update(this._iKey); }, /** * Updates this HMAC with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {HMAC} This HMAC instance. * * @example * * hmacHasher.update('message'); * hmacHasher.update(wordArray); */ update: function (messageUpdate) { this._hasher.update(messageUpdate); // Chainable return this; }, /** * Finalizes the HMAC computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The HMAC. * * @example * * var hmac = hmacHasher.finalize(); * var hmac = hmacHasher.finalize('message'); * var hmac = hmacHasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Shortcut var hasher = this._hasher; // Compute HMAC var innerHash = hasher.finalize(messageUpdate); hasher.reset(); var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); return hmac; } }); }()); })); },{"./core":44}],50:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy")); } else if (typeof define === "function" && define.amd) { // 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"], factory); } else { // Global (browser) root.CryptoJS = factory(root.CryptoJS); } }(this, function (CryptoJS) { return CryptoJS; })); },{"./aes":42,"./cipher-core":43,"./core":44,"./enc-base64":45,"./enc-utf16":46,"./evpkdf":47,"./format-hex":48,"./hmac":49,"./lib-typedarrays":51,"./md5":52,"./mode-cfb":53,"./mode-ctr":55,"./mode-ctr-gladman":54,"./mode-ecb":56,"./mode-ofb":57,"./pad-ansix923":58,"./pad-iso10126":59,"./pad-iso97971":60,"./pad-nopadding":61,"./pad-zeropadding":62,"./pbkdf2":63,"./rabbit":65,"./rabbit-legacy":64,"./rc4":66,"./ripemd160":67,"./sha1":68,"./sha224":69,"./sha256":70,"./sha3":71,"./sha384":72,"./sha512":73,"./tripledes":74,"./x64-core":75}],51:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Check if typed arrays are supported if (typeof ArrayBuffer != 'function') { return; } // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; // Reference original init var superInit = WordArray.init; // Augment WordArray.init to handle typed arrays var subInit = WordArray.init = function (typedArray) { // Convert buffers to uint8 if (typedArray instanceof ArrayBuffer) { typedArray = new Uint8Array(typedArray); } // Convert other array views to uint8 if ( typedArray instanceof Int8Array || (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array ) { typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); } // Handle Uint8Array if (typedArray instanceof Uint8Array) { // Shortcut var typedArrayByteLength = typedArray.byteLength; // Extract bytes var words = []; for (var i = 0; i < typedArrayByteLength; i++) { words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); } // Initialize this word array superInit.call(this, words, typedArrayByteLength); } else { // Else call normal init superInit.apply(this, arguments); } }; subInit.prototype = WordArray; }()); return CryptoJS.lib.WordArray; })); },{"./core":44}],52:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var T = []; // Compute constants (function () { for (var i = 0; i < 64; i++) { T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; } }()); /** * MD5 hash algorithm. */ var MD5 = C_algo.MD5 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 ]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcuts var H = this._hash.words; var M_offset_0 = M[offset + 0]; var M_offset_1 = M[offset + 1]; var M_offset_2 = M[offset + 2]; var M_offset_3 = M[offset + 3]; var M_offset_4 = M[offset + 4]; var M_offset_5 = M[offset + 5]; var M_offset_6 = M[offset + 6]; var M_offset_7 = M[offset + 7]; var M_offset_8 = M[offset + 8]; var M_offset_9 = M[offset + 9]; var M_offset_10 = M[offset + 10]; var M_offset_11 = M[offset + 11]; var M_offset_12 = M[offset + 12]; var M_offset_13 = M[offset + 13]; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; // Working varialbes var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; // Computation a = FF(a, b, c, d, M_offset_0, 7, T[0]); d = FF(d, a, b, c, M_offset_1, 12, T[1]); c = FF(c, d, a, b, M_offset_2, 17, T[2]); b = FF(b, c, d, a, M_offset_3, 22, T[3]); a = FF(a, b, c, d, M_offset_4, 7, T[4]); d = FF(d, a, b, c, M_offset_5, 12, T[5]); c = FF(c, d, a, b, M_offset_6, 17, T[6]); b = FF(b, c, d, a, M_offset_7, 22, T[7]); a = FF(a, b, c, d, M_offset_8, 7, T[8]); d = FF(d, a, b, c, M_offset_9, 12, T[9]); c = FF(c, d, a, b, M_offset_10, 17, T[10]); b = FF(b, c, d, a, M_offset_11, 22, T[11]); a = FF(a, b, c, d, M_offset_12, 7, T[12]); d = FF(d, a, b, c, M_offset_13, 12, T[13]); c = FF(c, d, a, b, M_offset_14, 17, T[14]); b = FF(b, c, d, a, M_offset_15, 22, T[15]); a = GG(a, b, c, d, M_offset_1, 5, T[16]); d = GG(d, a, b, c, M_offset_6, 9, T[17]); c = GG(c, d, a, b, M_offset_11, 14, T[18]); b = GG(b, c, d, a, M_offset_0, 20, T[19]); a = GG(a, b, c, d, M_offset_5, 5, T[20]); d = GG(d, a, b, c, M_offset_10, 9, T[21]); c = GG(c, d, a, b, M_offset_15, 14, T[22]); b = GG(b, c, d, a, M_offset_4, 20, T[23]); a = GG(a, b, c, d, M_offset_9, 5, T[24]); d = GG(d, a, b, c, M_offset_14, 9, T[25]); c = GG(c, d, a, b, M_offset_3, 14, T[26]); b = GG(b, c, d, a, M_offset_8, 20, T[27]); a = GG(a, b, c, d, M_offset_13, 5, T[28]); d = GG(d, a, b, c, M_offset_2, 9, T[29]); c = GG(c, d, a, b, M_offset_7, 14, T[30]); b = GG(b, c, d, a, M_offset_12, 20, T[31]); a = HH(a, b, c, d, M_offset_5, 4, T[32]); d = HH(d, a, b, c, M_offset_8, 11, T[33]); c = HH(c, d, a, b, M_offset_11, 16, T[34]); b = HH(b, c, d, a, M_offset_14, 23, T[35]); a = HH(a, b, c, d, M_offset_1, 4, T[36]); d = HH(d, a, b, c, M_offset_4, 11, T[37]); c = HH(c, d, a, b, M_offset_7, 16, T[38]); b = HH(b, c, d, a, M_offset_10, 23, T[39]); a = HH(a, b, c, d, M_offset_13, 4, T[40]); d = HH(d, a, b, c, M_offset_0, 11, T[41]); c = HH(c, d, a, b, M_offset_3, 16, T[42]); b = HH(b, c, d, a, M_offset_6, 23, T[43]); a = HH(a, b, c, d, M_offset_9, 4, T[44]); d = HH(d, a, b, c, M_offset_12, 11, T[45]); c = HH(c, d, a, b, M_offset_15, 16, T[46]); b = HH(b, c, d, a, M_offset_2, 23, T[47]); a = II(a, b, c, d, M_offset_0, 6, T[48]); d = II(d, a, b, c, M_offset_7, 10, T[49]); c = II(c, d, a, b, M_offset_14, 15, T[50]); b = II(b, c, d, a, M_offset_5, 21, T[51]); a = II(a, b, c, d, M_offset_12, 6, T[52]); d = II(d, a, b, c, M_offset_3, 10, T[53]); c = II(c, d, a, b, M_offset_10, 15, T[54]); b = II(b, c, d, a, M_offset_1, 21, T[55]); a = II(a, b, c, d, M_offset_8, 6, T[56]); d = II(d, a, b, c, M_offset_15, 10, T[57]); c = II(c, d, a, b, M_offset_6, 15, T[58]); b = II(b, c, d, a, M_offset_13, 21, T[59]); a = II(a, b, c, d, M_offset_4, 6, T[60]); d = II(d, a, b, c, M_offset_11, 10, T[61]); c = II(c, d, a, b, M_offset_2, 15, T[62]); b = II(b, c, d, a, M_offset_9, 21, T[63]); // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); var nBitsTotalL = nBitsTotal; dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) ); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 4; i++) { // Shortcut var H_i = H[i]; H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function FF(a, b, c, d, x, s, t) { var n = a + ((b & c) | (~b & d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function GG(a, b, c, d, x, s, t) { var n = a + ((b & d) | (c & ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function HH(a, b, c, d, x, s, t) { var n = a + (b ^ c ^ d) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function II(a, b, c, d, x, s, t) { var n = a + (c ^ (b | ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.MD5('message'); * var hash = CryptoJS.MD5(wordArray); */ C.MD5 = Hasher._createHelper(MD5); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacMD5(message, key); */ C.HmacMD5 = Hasher._createHmacHelper(MD5); }(Math)); return CryptoJS.MD5; })); },{"./core":44}],53:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher Feedback block mode. */ CryptoJS.mode.CFB = (function () { var CFB = CryptoJS.lib.BlockCipherMode.extend(); CFB.Encryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); CFB.Decryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // This block becomes the previous block this._prevBlock = thisBlock; } }); function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { // Shortcut var iv = this._iv; // Generate keystream if (iv) { var keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } else { var keystream = this._prevBlock; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } return CFB; }()); return CryptoJS.mode.CFB; })); },{"./cipher-core":43,"./core":44}],54:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve * Counter block mode compatible with Dr Brian Gladman fileenc.c * derived from CryptoJS.mode.CTR * Jan Hruby [email protected] */ CryptoJS.mode.CTRGladman = (function () { var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); function incWord(word) { if (((word >> 24) & 0xff) === 0xff) { //overflow var b1 = (word >> 16)&0xff; var b2 = (word >> 8)&0xff; var b3 = word & 0xff; if (b1 === 0xff) // overflow b1 { b1 = 0; if (b2 === 0xff) { b2 = 0; if (b3 === 0xff) { b3 = 0; } else { ++b3; } } else { ++b2; } } else { ++b1; } word = 0; word += (b1 << 16); word += (b2 << 8); word += b3; } else { word += (0x01 << 24); } return word; } function incCounter(counter) { if ((counter[0] = incWord(counter[0])) === 0) { // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 counter[1] = incWord(counter[1]); } return counter; } var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } incCounter(counter); var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTRGladman.Decryptor = Encryptor; return CTRGladman; }()); return CryptoJS.mode.CTRGladman; })); },{"./cipher-core":43,"./core":44}],55:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Counter block mode. */ CryptoJS.mode.CTR = (function () { var CTR = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = CTR.Encryptor = CTR.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Increment counter counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTR.Decryptor = Encryptor; return CTR; }()); return CryptoJS.mode.CTR; })); },{"./cipher-core":43,"./core":44}],56:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Electronic Codebook block mode. */ CryptoJS.mode.ECB = (function () { var ECB = CryptoJS.lib.BlockCipherMode.extend(); ECB.Encryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.encryptBlock(words, offset); } }); ECB.Decryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.decryptBlock(words, offset); } }); return ECB; }()); return CryptoJS.mode.ECB; })); },{"./cipher-core":43,"./core":44}],57:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Output Feedback block mode. */ CryptoJS.mode.OFB = (function () { var OFB = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = OFB.Encryptor = OFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var keystream = this._keystream; // Generate keystream if (iv) { keystream = this._keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); OFB.Decryptor = Encryptor; return OFB; }()); return CryptoJS.mode.OFB; })); },{"./cipher-core":43,"./core":44}],58:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ANSI X.923 padding strategy. */ CryptoJS.pad.AnsiX923 = { pad: function (data, blockSize) { // Shortcuts var dataSigBytes = data.sigBytes; var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; // Compute last byte position var lastBytePos = dataSigBytes + nPaddingBytes - 1; // Pad data.clamp(); data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); data.sigBytes += nPaddingBytes; }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Ansix923; })); },{"./cipher-core":43,"./core":44}],59:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO 10126 padding strategy. */ CryptoJS.pad.Iso10126 = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Pad data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Iso10126; })); },{"./cipher-core":43,"./core":44}],60:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO/IEC 9797-1 Padding Method 2. */ CryptoJS.pad.Iso97971 = { pad: function (data, blockSize) { // Add 0x80 byte data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); // Zero pad the rest CryptoJS.pad.ZeroPadding.pad(data, blockSize); }, unpad: function (data) { // Remove zero padding CryptoJS.pad.ZeroPadding.unpad(data); // Remove one more byte -- the 0x80 byte data.sigBytes--; } }; return CryptoJS.pad.Iso97971; })); },{"./cipher-core":43,"./core":44}],61:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":43,"./core":44}],62:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Zero padding strategy. */ CryptoJS.pad.ZeroPadding = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Pad data.clamp(); data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); }, unpad: function (data) { // Shortcut var dataWords = data.words; // Unpad var i = data.sigBytes - 1; while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { i--; } data.sigBytes = i + 1; } }; return CryptoJS.pad.ZeroPadding; })); },{"./cipher-core":43,"./core":44}],63:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA1 = C_algo.SHA1; var HMAC = C_algo.HMAC; /** * Password-Based Key Derivation Function 2 algorithm. */ var PBKDF2 = C_algo.PBKDF2 = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hasher to use. Default: SHA1 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: SHA1, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.PBKDF2.create(); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init HMAC var hmac = HMAC.create(cfg.hasher, password); // Initial values var derivedKey = WordArray.create(); var blockIndex = WordArray.create([0x00000001]); // Shortcuts var derivedKeyWords = derivedKey.words; var blockIndexWords = blockIndex.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { var block = hmac.update(salt).finalize(blockIndex); hmac.reset(); // Shortcuts var blockWords = block.words; var blockWordsLength = blockWords.length; // Iterations var intermediate = block; for (var i = 1; i < iterations; i++) { intermediate = hmac.finalize(intermediate); hmac.reset(); // Shortcut var intermediateWords = intermediate.words; // XOR intermediate with block for (var j = 0; j < blockWordsLength; j++) { blockWords[j] ^= intermediateWords[j]; } } derivedKey.concat(block); blockIndexWords[0]++; } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.PBKDF2(password, salt); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); */ C.PBKDF2 = function (password, salt, cfg) { return PBKDF2.create(cfg).compute(password, salt); }; }()); return CryptoJS.PBKDF2; })); },{"./core":44,"./hmac":49,"./sha1":68}],64:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm. * * This is a legacy version that neglected to convert the key to little-endian. * This error doesn't affect the cipher's security, * but it does affect its compatibility with other implementations. */ var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); */ C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); }()); return CryptoJS.RabbitLegacy; })); },{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],65:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm */ var Rabbit = C_algo.Rabbit = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Swap endian for (var i = 0; i < 4; i++) { K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); } // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); */ C.Rabbit = StreamCipher._createHelper(Rabbit); }()); return CryptoJS.Rabbit; })); },{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],66:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; /** * RC4 stream cipher algorithm. */ var RC4 = C_algo.RC4 = StreamCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySigBytes = key.sigBytes; // Init sbox var S = this._S = []; for (var i = 0; i < 256; i++) { S[i] = i; } // Key setup for (var i = 0, j = 0; i < 256; i++) { var keyByteIndex = i % keySigBytes; var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; j = (j + S[i] + keyByte) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; } // Counters this._i = this._j = 0; }, _doProcessBlock: function (M, offset) { M[offset] ^= generateKeystreamWord.call(this); }, keySize: 256/32, ivSize: 0 }); function generateKeystreamWord() { // Shortcuts var S = this._S; var i = this._i; var j = this._j; // Generate keystream word var keystreamWord = 0; for (var n = 0; n < 4; n++) { i = (i + 1) % 256; j = (j + S[i]) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); } // Update counters this._i = i; this._j = j; return keystreamWord; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); */ C.RC4 = StreamCipher._createHelper(RC4); /** * Modified RC4 stream cipher algorithm. */ var RC4Drop = C_algo.RC4Drop = RC4.extend({ /** * Configuration options. * * @property {number} drop The number of keystream words to drop. Default 192 */ cfg: RC4.cfg.extend({ drop: 192 }), _doReset: function () { RC4._doReset.call(this); // Drop for (var i = this.cfg.drop; i > 0; i--) { generateKeystreamWord.call(this); } } }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); */ C.RC4Drop = StreamCipher._createHelper(RC4Drop); }()); return CryptoJS.RC4; })); },{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],67:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var _zl = WordArray.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]); var _zr = WordArray.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]); var _sl = WordArray.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 ]); var _sr = WordArray.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 ]); var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); /** * RIPEMD160 hash algorithm. */ var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ _doReset: function () { this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; // Swap M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcut var H = this._hash.words; var hl = _hl.words; var hr = _hr.words; var zl = _zl.words; var zr = _zr.words; var sl = _sl.words; var sr = _sr.words; // Working variables var al, bl, cl, dl, el; var ar, br, cr, dr, er; ar = al = H[0]; br = bl = H[1]; cr = cl = H[2]; dr = dl = H[3]; er = el = H[4]; // Computation var t; for (var i = 0; i < 80; i += 1) { t = (al + M[offset+zl[i]])|0; if (i<16){ t += f1(bl,cl,dl) + hl[0]; } else if (i<32) { t += f2(bl,cl,dl) + hl[1]; } else if (i<48) { t += f3(bl,cl,dl) + hl[2]; } else if (i<64) { t += f4(bl,cl,dl) + hl[3]; } else {// if (i<80) { t += f5(bl,cl,dl) + hl[4]; } t = t|0; t = rotl(t,sl[i]); t = (t+el)|0; al = el; el = dl; dl = rotl(cl, 10); cl = bl; bl = t; t = (ar + M[offset+zr[i]])|0; if (i<16){ t += f5(br,cr,dr) + hr[0]; } else if (i<32) { t += f4(br,cr,dr) + hr[1]; } else if (i<48) { t += f3(br,cr,dr) + hr[2]; } else if (i<64) { t += f2(br,cr,dr) + hr[3]; } else {// if (i<80) { t += f1(br,cr,dr) + hr[4]; } t = t|0; t = rotl(t,sr[i]) ; t = (t+er)|0; ar = er; er = dr; dr = rotl(cr, 10); cr = br; br = t; } // Intermediate hash value t = (H[1] + cl + dr)|0; H[1] = (H[2] + dl + er)|0; H[2] = (H[3] + el + ar)|0; H[3] = (H[4] + al + br)|0; H[4] = (H[0] + bl + cr)|0; H[0] = t; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 5; i++) { // Shortcut var H_i = H[i]; // Swap H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function f1(x, y, z) { return ((x) ^ (y) ^ (z)); } function f2(x, y, z) { return (((x)&(y)) | ((~x)&(z))); } function f3(x, y, z) { return (((x) | (~(y))) ^ (z)); } function f4(x, y, z) { return (((x) & (z)) | ((y)&(~(z)))); } function f5(x, y, z) { return ((x) ^ ((y) |(~(z)))); } function rotl(x,n) { return (x<<n) | (x>>>(32-n)); } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.RIPEMD160('message'); * var hash = CryptoJS.RIPEMD160(wordArray); */ C.RIPEMD160 = Hasher._createHelper(RIPEMD160); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacRIPEMD160(message, key); */ C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); }(Math)); return CryptoJS.RIPEMD160; })); },{"./core":44}],68:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Reusable object var W = []; /** * SHA-1 hash algorithm. */ var SHA1 = C_algo.SHA1 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; // Computation for (var i = 0; i < 80; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; W[i] = (n << 1) | (n >>> 31); } var t = ((a << 5) | (a >>> 27)) + e + W[i]; if (i < 20) { t += ((b & c) | (~b & d)) + 0x5a827999; } else if (i < 40) { t += (b ^ c ^ d) + 0x6ed9eba1; } else if (i < 60) { t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; } else /* if (i < 80) */ { t += (b ^ c ^ d) - 0x359d3e2a; } e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA1('message'); * var hash = CryptoJS.SHA1(wordArray); */ C.SHA1 = Hasher._createHelper(SHA1); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA1(message, key); */ C.HmacSHA1 = Hasher._createHmacHelper(SHA1); }()); return CryptoJS.SHA1; })); },{"./core":44}],69:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha256"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA256 = C_algo.SHA256; /** * SHA-224 hash algorithm. */ var SHA224 = C_algo.SHA224 = SHA256.extend({ _doReset: function () { this._hash = new WordArray.init([ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]); }, _doFinalize: function () { var hash = SHA256._doFinalize.call(this); hash.sigBytes -= 4; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA224('message'); * var hash = CryptoJS.SHA224(wordArray); */ C.SHA224 = SHA256._createHelper(SHA224); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA224(message, key); */ C.HmacSHA224 = SHA256._createHmacHelper(SHA224); }()); return CryptoJS.SHA224; })); },{"./core":44,"./sha256":70}],70:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Initialization and round constants tables var H = []; var K = []; // Compute constants (function () { function isPrime(n) { var sqrtN = Math.sqrt(n); for (var factor = 2; factor <= sqrtN; factor++) { if (!(n % factor)) { return false; } } return true; } function getFractionalBits(n) { return ((n - (n | 0)) * 0x100000000) | 0; } var n = 2; var nPrime = 0; while (nPrime < 64) { if (isPrime(n)) { if (nPrime < 8) { H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); } K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); nPrime++; } n++; } }()); // Reusable object var W = []; /** * SHA-256 hash algorithm. */ var SHA256 = C_algo.SHA256 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init(H.slice(0)); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; var f = H[5]; var g = H[6]; var h = H[7]; // Computation for (var i = 0; i < 64; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var gamma0x = W[i - 15]; var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ ((gamma0x << 14) | (gamma0x >>> 18)) ^ (gamma0x >>> 3); var gamma1x = W[i - 2]; var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ ((gamma1x << 13) | (gamma1x >>> 19)) ^ (gamma1x >>> 10); W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; } var ch = (e & f) ^ (~e & g); var maj = (a & b) ^ (a & c) ^ (b & c); var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); var t1 = h + sigma1 + ch + K[i] + W[i]; var t2 = sigma0 + maj; h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA256('message'); * var hash = CryptoJS.SHA256(wordArray); */ C.SHA256 = Hasher._createHelper(SHA256); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA256(message, key); */ C.HmacSHA256 = Hasher._createHmacHelper(SHA256); }(Math)); return CryptoJS.SHA256; })); },{"./core":44}],71:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var C_algo = C.algo; // Constants tables var RHO_OFFSETS = []; var PI_INDEXES = []; var ROUND_CONSTANTS = []; // Compute Constants (function () { // Compute rho offset constants var x = 1, y = 0; for (var t = 0; t < 24; t++) { RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; var newX = y % 5; var newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } // Compute pi index constants for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; } } // Compute round constants var LFSR = 0x01; for (var i = 0; i < 24; i++) { var roundConstantMsw = 0; var roundConstantLsw = 0; for (var j = 0; j < 7; j++) { if (LFSR & 0x01) { var bitPosition = (1 << j) - 1; if (bitPosition < 32) { roundConstantLsw ^= 1 << bitPosition; } else /* if (bitPosition >= 32) */ { roundConstantMsw ^= 1 << (bitPosition - 32); } } // Compute next LFSR if (LFSR & 0x80) { // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 LFSR = (LFSR << 1) ^ 0x71; } else { LFSR <<= 1; } } ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); } }()); // Reusable objects for temporary values var T = []; (function () { for (var i = 0; i < 25; i++) { T[i] = X64Word.create(); } }()); /** * SHA-3 hash algorithm. */ var SHA3 = C_algo.SHA3 = Hasher.extend({ /** * Configuration options. * * @property {number} outputLength * The desired number of bits in the output hash. * Only values permitted are: 224, 256, 384, 512. * Default: 512 */ cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function () { var state = this._state = [] for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function (M, offset) { // Shortcuts var state = this._state; var nBlockSizeLanes = this.blockSize / 2; // Absorb for (var i = 0; i < nBlockSizeLanes; i++) { // Shortcuts var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; // Swap endian M2i = ( (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) ); M2i1 = ( (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) ); // Absorb message into state var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } // Rounds for (var round = 0; round < 24; round++) { // Theta for (var x = 0; x < 5; x++) { // Mix column lanes var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } // Temporary values var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { // Shortcuts var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; // Mix surrounding columns var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } // Rho Pi for (var laneIndex = 1; laneIndex < 25; laneIndex++) { // Shortcuts var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; // Rotate lanes if (rhoOffset < 32) { var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); } else /* if (rhoOffset >= 32) */ { var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); } // Transpose lanes var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } // Rho pi at x = y = 0 var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; // Chi for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // Shortcuts var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[((x + 1) % 5) + 5 * y]; var Tx2Lane = T[((x + 2) % 5) + 5 * y]; // Mix rows lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); } } // Iota var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low;; } }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; // Add padding dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Shortcuts var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; // Squeeze var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { // Shortcuts var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; // Swap endian laneMsw = ( (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) ); laneLsw = ( (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) ); // Squeeze state to retrieve hash hashWords.push(laneLsw); hashWords.push(laneMsw); } // Return final computed hash return new WordArray.init(hashWords, outputLengthBytes); }, clone: function () { var clone = Hasher.clone.call(this); var state = clone._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA3('message'); * var hash = CryptoJS.SHA3(wordArray); */ C.SHA3 = Hasher._createHelper(SHA3); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA3(message, key); */ C.HmacSHA3 = Hasher._createHmacHelper(SHA3); }(Math)); return CryptoJS.SHA3; })); },{"./core":44,"./x64-core":75}],72:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./sha512"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; var SHA512 = C_algo.SHA512; /** * SHA-384 hash algorithm. */ var SHA384 = C_algo.SHA384 = SHA512.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) ]); }, _doFinalize: function () { var hash = SHA512._doFinalize.call(this); hash.sigBytes -= 16; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA384('message'); * var hash = CryptoJS.SHA384(wordArray); */ C.SHA384 = SHA512._createHelper(SHA384); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA384(message, key); */ C.HmacSHA384 = SHA512._createHmacHelper(SHA384); }()); return CryptoJS.SHA384; })); },{"./core":44,"./sha512":73,"./x64-core":75}],73:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; function X64Word_create() { return X64Word.create.apply(X64Word, arguments); } // Constants var K = [ X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) ]; // Reusable objects var W = []; (function () { for (var i = 0; i < 80; i++) { W[i] = X64Word_create(); } }()); /** * SHA-512 hash algorithm. */ var SHA512 = C_algo.SHA512 = Hasher.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) ]); }, _doProcessBlock: function (M, offset) { // Shortcuts var H = this._hash.words; var H0 = H[0]; var H1 = H[1]; var H2 = H[2]; var H3 = H[3]; var H4 = H[4]; var H5 = H[5]; var H6 = H[6]; var H7 = H[7]; var H0h = H0.high; var H0l = H0.low; var H1h = H1.high; var H1l = H1.low; var H2h = H2.high; var H2l = H2.low; var H3h = H3.high; var H3l = H3.low; var H4h = H4.high; var H4l = H4.low; var H5h = H5.high; var H5l = H5.low; var H6h = H6.high; var H6l = H6.low; var H7h = H7.high; var H7l = H7.low; // Working variables var ah = H0h; var al = H0l; var bh = H1h; var bl = H1l; var ch = H2h; var cl = H2l; var dh = H3h; var dl = H3l; var eh = H4h; var el = H4l; var fh = H5h; var fl = H5l; var gh = H6h; var gl = H6l; var hh = H7h; var hl = H7l; // Rounds for (var i = 0; i < 80; i++) { // Shortcut var Wi = W[i]; // Extend message if (i < 16) { var Wih = Wi.high = M[offset + i * 2] | 0; var Wil = Wi.low = M[offset + i * 2 + 1] | 0; } else { // Gamma0 var gamma0x = W[i - 15]; var gamma0xh = gamma0x.high; var gamma0xl = gamma0x.low; var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); // Gamma1 var gamma1x = W[i - 2]; var gamma1xh = gamma1x.high; var gamma1xl = gamma1x.low; var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] var Wi7 = W[i - 7]; var Wi7h = Wi7.high; var Wi7l = Wi7.low; var Wi16 = W[i - 16]; var Wi16h = Wi16.high; var Wi16l = Wi16.low; var Wil = gamma0l + Wi7l; var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); var Wil = Wil + gamma1l; var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); var Wil = Wil + Wi16l; var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); Wi.high = Wih; Wi.low = Wil; } var chh = (eh & fh) ^ (~eh & gh); var chl = (el & fl) ^ (~el & gl); var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); var majl = (al & bl) ^ (al & cl) ^ (bl & cl); var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); // t1 = h + sigma1 + ch + K[i] + W[i] var Ki = K[i]; var Kih = Ki.high; var Kil = Ki.low; var t1l = hl + sigma1l; var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); var t1l = t1l + chl; var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); var t1l = t1l + Kil; var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); var t1l = t1l + Wil; var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); // t2 = sigma0 + maj var t2l = sigma0l + majl; var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); // Update working variables hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; el = (dl + t1l) | 0; eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; al = (t1l + t2l) | 0; ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; } // Intermediate hash value H0l = H0.low = (H0l + al); H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); H1l = H1.low = (H1l + bl); H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); H2l = H2.low = (H2l + cl); H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); H3l = H3.low = (H3l + dl); H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); H4l = H4.low = (H4l + el); H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); H5l = H5.low = (H5l + fl); H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); H6l = H6.low = (H6l + gl); H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); H7l = H7.low = (H7l + hl); H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Convert hash to 32-bit word array before returning var hash = this._hash.toX32(); // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; }, blockSize: 1024/32 }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA512('message'); * var hash = CryptoJS.SHA512(wordArray); */ C.SHA512 = Hasher._createHelper(SHA512); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA512(message, key); */ C.HmacSHA512 = Hasher._createHmacHelper(SHA512); }()); return CryptoJS.SHA512; })); },{"./core":44,"./x64-core":75}],74:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Permuted Choice 1 constants var PC1 = [ 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 ]; // Permuted Choice 2 constants var PC2 = [ 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 ]; // Cumulative bit shift constants var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; // SBOXes and round permutation constants var SBOX_P = [ { 0x0: 0x808200, 0x10000000: 0x8000, 0x20000000: 0x808002, 0x30000000: 0x2, 0x40000000: 0x200, 0x50000000: 0x808202, 0x60000000: 0x800202, 0x70000000: 0x800000, 0x80000000: 0x202, 0x90000000: 0x800200, 0xa0000000: 0x8200, 0xb0000000: 0x808000, 0xc0000000: 0x8002, 0xd0000000: 0x800002, 0xe0000000: 0x0, 0xf0000000: 0x8202, 0x8000000: 0x0, 0x18000000: 0x808202, 0x28000000: 0x8202, 0x38000000: 0x8000, 0x48000000: 0x808200, 0x58000000: 0x200, 0x68000000: 0x808002, 0x78000000: 0x2, 0x88000000: 0x800200, 0x98000000: 0x8200, 0xa8000000: 0x808000, 0xb8000000: 0x800202, 0xc8000000: 0x800002, 0xd8000000: 0x8002, 0xe8000000: 0x202, 0xf8000000: 0x800000, 0x1: 0x8000, 0x10000001: 0x2, 0x20000001: 0x808200, 0x30000001: 0x800000, 0x40000001: 0x808002, 0x50000001: 0x8200, 0x60000001: 0x200, 0x70000001: 0x800202, 0x80000001: 0x808202, 0x90000001: 0x808000, 0xa0000001: 0x800002, 0xb0000001: 0x8202, 0xc0000001: 0x202, 0xd0000001: 0x800200, 0xe0000001: 0x8002, 0xf0000001: 0x0, 0x8000001: 0x808202, 0x18000001: 0x808000, 0x28000001: 0x800000, 0x38000001: 0x200, 0x48000001: 0x8000, 0x58000001: 0x800002, 0x68000001: 0x2, 0x78000001: 0x8202, 0x88000001: 0x8002, 0x98000001: 0x800202, 0xa8000001: 0x202, 0xb8000001: 0x808200, 0xc8000001: 0x800200, 0xd8000001: 0x0, 0xe8000001: 0x8200, 0xf8000001: 0x808002 }, { 0x0: 0x40084010, 0x1000000: 0x4000, 0x2000000: 0x80000, 0x3000000: 0x40080010, 0x4000000: 0x40000010, 0x5000000: 0x40084000, 0x6000000: 0x40004000, 0x7000000: 0x10, 0x8000000: 0x84000, 0x9000000: 0x40004010, 0xa000000: 0x40000000, 0xb000000: 0x84010, 0xc000000: 0x80010, 0xd000000: 0x0, 0xe000000: 0x4010, 0xf000000: 0x40080000, 0x800000: 0x40004000, 0x1800000: 0x84010, 0x2800000: 0x10, 0x3800000: 0x40004010, 0x4800000: 0x40084010, 0x5800000: 0x40000000, 0x6800000: 0x80000, 0x7800000: 0x40080010, 0x8800000: 0x80010, 0x9800000: 0x0, 0xa800000: 0x4000, 0xb800000: 0x40080000, 0xc800000: 0x40000010, 0xd800000: 0x84000, 0xe800000: 0x40084000, 0xf800000: 0x4010, 0x10000000: 0x0, 0x11000000: 0x40080010, 0x12000000: 0x40004010, 0x13000000: 0x40084000, 0x14000000: 0x40080000, 0x15000000: 0x10, 0x16000000: 0x84010, 0x17000000: 0x4000, 0x18000000: 0x4010, 0x19000000: 0x80000, 0x1a000000: 0x80010, 0x1b000000: 0x40000010, 0x1c000000: 0x84000, 0x1d000000: 0x40004000, 0x1e000000: 0x40000000, 0x1f000000: 0x40084010, 0x10800000: 0x84010, 0x11800000: 0x80000, 0x12800000: 0x40080000, 0x13800000: 0x4000, 0x14800000: 0x40004000, 0x15800000: 0x40084010, 0x16800000: 0x10, 0x17800000: 0x40000000, 0x18800000: 0x40084000, 0x19800000: 0x40000010, 0x1a800000: 0x40004010, 0x1b800000: 0x80010, 0x1c800000: 0x0, 0x1d800000: 0x4010, 0x1e800000: 0x40080010, 0x1f800000: 0x84000 }, { 0x0: 0x104, 0x100000: 0x0, 0x200000: 0x4000100, 0x300000: 0x10104, 0x400000: 0x10004, 0x500000: 0x4000004, 0x600000: 0x4010104, 0x700000: 0x4010000, 0x800000: 0x4000000, 0x900000: 0x4010100, 0xa00000: 0x10100, 0xb00000: 0x4010004, 0xc00000: 0x4000104, 0xd00000: 0x10000, 0xe00000: 0x4, 0xf00000: 0x100, 0x80000: 0x4010100, 0x180000: 0x4010004, 0x280000: 0x0, 0x380000: 0x4000100, 0x480000: 0x4000004, 0x580000: 0x10000, 0x680000: 0x10004, 0x780000: 0x104, 0x880000: 0x4, 0x980000: 0x100, 0xa80000: 0x4010000, 0xb80000: 0x10104, 0xc80000: 0x10100, 0xd80000: 0x4000104, 0xe80000: 0x4010104, 0xf80000: 0x4000000, 0x1000000: 0x4010100, 0x1100000: 0x10004, 0x1200000: 0x10000, 0x1300000: 0x4000100, 0x1400000: 0x100, 0x1500000: 0x4010104, 0x1600000: 0x4000004, 0x1700000: 0x0, 0x1800000: 0x4000104, 0x1900000: 0x4000000, 0x1a00000: 0x4, 0x1b00000: 0x10100, 0x1c00000: 0x4010000, 0x1d00000: 0x104, 0x1e00000: 0x10104, 0x1f00000: 0x4010004, 0x1080000: 0x4000000, 0x1180000: 0x104, 0x1280000: 0x4010100, 0x1380000: 0x0, 0x1480000: 0x10004, 0x1580000: 0x4000100, 0x1680000: 0x100, 0x1780000: 0x4010004, 0x1880000: 0x10000, 0x1980000: 0x4010104, 0x1a80000: 0x10104, 0x1b80000: 0x4000004, 0x1c80000: 0x4000104, 0x1d80000: 0x4010000, 0x1e80000: 0x4, 0x1f80000: 0x10100 }, { 0x0: 0x80401000, 0x10000: 0x80001040, 0x20000: 0x401040, 0x30000: 0x80400000, 0x40000: 0x0, 0x50000: 0x401000, 0x60000: 0x80000040, 0x70000: 0x400040, 0x80000: 0x80000000, 0x90000: 0x400000, 0xa0000: 0x40, 0xb0000: 0x80001000, 0xc0000: 0x80400040, 0xd0000: 0x1040, 0xe0000: 0x1000, 0xf0000: 0x80401040, 0x8000: 0x80001040, 0x18000: 0x40, 0x28000: 0x80400040, 0x38000: 0x80001000, 0x48000: 0x401000, 0x58000: 0x80401040, 0x68000: 0x0, 0x78000: 0x80400000, 0x88000: 0x1000, 0x98000: 0x80401000, 0xa8000: 0x400000, 0xb8000: 0x1040, 0xc8000: 0x80000000, 0xd8000: 0x400040, 0xe8000: 0x401040, 0xf8000: 0x80000040, 0x100000: 0x400040, 0x110000: 0x401000, 0x120000: 0x80000040, 0x130000: 0x0, 0x140000: 0x1040, 0x150000: 0x80400040, 0x160000: 0x80401000, 0x170000: 0x80001040, 0x180000: 0x80401040, 0x190000: 0x80000000, 0x1a0000: 0x80400000, 0x1b0000: 0x401040, 0x1c0000: 0x80001000, 0x1d0000: 0x400000, 0x1e0000: 0x40, 0x1f0000: 0x1000, 0x108000: 0x80400000, 0x118000: 0x80401040, 0x128000: 0x0, 0x138000: 0x401000, 0x148000: 0x400040, 0x158000: 0x80000000, 0x168000: 0x80001040, 0x178000: 0x40, 0x188000: 0x80000040, 0x198000: 0x1000, 0x1a8000: 0x80001000, 0x1b8000: 0x80400040, 0x1c8000: 0x1040, 0x1d8000: 0x80401000, 0x1e8000: 0x400000, 0x1f8000: 0x401040 }, { 0x0: 0x80, 0x1000: 0x1040000, 0x2000: 0x40000, 0x3000: 0x20000000, 0x4000: 0x20040080, 0x5000: 0x1000080, 0x6000: 0x21000080, 0x7000: 0x40080, 0x8000: 0x1000000, 0x9000: 0x20040000, 0xa000: 0x20000080, 0xb000: 0x21040080, 0xc000: 0x21040000, 0xd000: 0x0, 0xe000: 0x1040080, 0xf000: 0x21000000, 0x800: 0x1040080, 0x1800: 0x21000080, 0x2800: 0x80, 0x3800: 0x1040000, 0x4800: 0x40000, 0x5800: 0x20040080, 0x6800: 0x21040000, 0x7800: 0x20000000, 0x8800: 0x20040000, 0x9800: 0x0, 0xa800: 0x21040080, 0xb800: 0x1000080, 0xc800: 0x20000080, 0xd800: 0x21000000, 0xe800: 0x1000000, 0xf800: 0x40080, 0x10000: 0x40000, 0x11000: 0x80, 0x12000: 0x20000000, 0x13000: 0x21000080, 0x14000: 0x1000080, 0x15000: 0x21040000, 0x16000: 0x20040080, 0x17000: 0x1000000, 0x18000: 0x21040080, 0x19000: 0x21000000, 0x1a000: 0x1040000, 0x1b000: 0x20040000, 0x1c000: 0x40080, 0x1d000: 0x20000080, 0x1e000: 0x0, 0x1f000: 0x1040080, 0x10800: 0x21000080, 0x11800: 0x1000000, 0x12800: 0x1040000, 0x13800: 0x20040080, 0x14800: 0x20000000, 0x15800: 0x1040080, 0x16800: 0x80, 0x17800: 0x21040000, 0x18800: 0x40080, 0x19800: 0x21040080, 0x1a800: 0x0, 0x1b800: 0x21000000, 0x1c800: 0x1000080, 0x1d800: 0x40000, 0x1e800: 0x20040000, 0x1f800: 0x20000080 }, { 0x0: 0x10000008, 0x100: 0x2000, 0x200: 0x10200000, 0x300: 0x10202008, 0x400: 0x10002000, 0x500: 0x200000, 0x600: 0x200008, 0x700: 0x10000000, 0x800: 0x0, 0x900: 0x10002008, 0xa00: 0x202000, 0xb00: 0x8, 0xc00: 0x10200008, 0xd00: 0x202008, 0xe00: 0x2008, 0xf00: 0x10202000, 0x80: 0x10200000, 0x180: 0x10202008, 0x280: 0x8, 0x380: 0x200000, 0x480: 0x202008, 0x580: 0x10000008, 0x680: 0x10002000, 0x780: 0x2008, 0x880: 0x200008, 0x980: 0x2000, 0xa80: 0x10002008, 0xb80: 0x10200008, 0xc80: 0x0, 0xd80: 0x10202000, 0xe80: 0x202000, 0xf80: 0x10000000, 0x1000: 0x10002000, 0x1100: 0x10200008, 0x1200: 0x10202008, 0x1300: 0x2008, 0x1400: 0x200000, 0x1500: 0x10000000, 0x1600: 0x10000008, 0x1700: 0x202000, 0x1800: 0x202008, 0x1900: 0x0, 0x1a00: 0x8, 0x1b00: 0x10200000, 0x1c00: 0x2000, 0x1d00: 0x10002008, 0x1e00: 0x10202000, 0x1f00: 0x200008, 0x1080: 0x8, 0x1180: 0x202000, 0x1280: 0x200000, 0x1380: 0x10000008, 0x1480: 0x10002000, 0x1580: 0x2008, 0x1680: 0x10202008, 0x1780: 0x10200000, 0x1880: 0x10202000, 0x1980: 0x10200008, 0x1a80: 0x2000, 0x1b80: 0x202008, 0x1c80: 0x200008, 0x1d80: 0x0, 0x1e80: 0x10000000, 0x1f80: 0x10002008 }, { 0x0: 0x100000, 0x10: 0x2000401, 0x20: 0x400, 0x30: 0x100401, 0x40: 0x2100401, 0x50: 0x0, 0x60: 0x1, 0x70: 0x2100001, 0x80: 0x2000400, 0x90: 0x100001, 0xa0: 0x2000001, 0xb0: 0x2100400, 0xc0: 0x2100000, 0xd0: 0x401, 0xe0: 0x100400, 0xf0: 0x2000000, 0x8: 0x2100001, 0x18: 0x0, 0x28: 0x2000401, 0x38: 0x2100400, 0x48: 0x100000, 0x58: 0x2000001, 0x68: 0x2000000, 0x78: 0x401, 0x88: 0x100401, 0x98: 0x2000400, 0xa8: 0x2100000, 0xb8: 0x100001, 0xc8: 0x400, 0xd8: 0x2100401, 0xe8: 0x1, 0xf8: 0x100400, 0x100: 0x2000000, 0x110: 0x100000, 0x120: 0x2000401, 0x130: 0x2100001, 0x140: 0x100001, 0x150: 0x2000400, 0x160: 0x2100400, 0x170: 0x100401, 0x180: 0x401, 0x190: 0x2100401, 0x1a0: 0x100400, 0x1b0: 0x1, 0x1c0: 0x0, 0x1d0: 0x2100000, 0x1e0: 0x2000001, 0x1f0: 0x400, 0x108: 0x100400, 0x118: 0x2000401, 0x128: 0x2100001, 0x138: 0x1, 0x148: 0x2000000, 0x158: 0x100000, 0x168: 0x401, 0x178: 0x2100400, 0x188: 0x2000001, 0x198: 0x2100000, 0x1a8: 0x0, 0x1b8: 0x2100401, 0x1c8: 0x100401, 0x1d8: 0x400, 0x1e8: 0x2000400, 0x1f8: 0x100001 }, { 0x0: 0x8000820, 0x1: 0x20000, 0x2: 0x8000000, 0x3: 0x20, 0x4: 0x20020, 0x5: 0x8020820, 0x6: 0x8020800, 0x7: 0x800, 0x8: 0x8020000, 0x9: 0x8000800, 0xa: 0x20800, 0xb: 0x8020020, 0xc: 0x820, 0xd: 0x0, 0xe: 0x8000020, 0xf: 0x20820, 0x80000000: 0x800, 0x80000001: 0x8020820, 0x80000002: 0x8000820, 0x80000003: 0x8000000, 0x80000004: 0x8020000, 0x80000005: 0x20800, 0x80000006: 0x20820, 0x80000007: 0x20, 0x80000008: 0x8000020, 0x80000009: 0x820, 0x8000000a: 0x20020, 0x8000000b: 0x8020800, 0x8000000c: 0x0, 0x8000000d: 0x8020020, 0x8000000e: 0x8000800, 0x8000000f: 0x20000, 0x10: 0x20820, 0x11: 0x8020800, 0x12: 0x20, 0x13: 0x800, 0x14: 0x8000800, 0x15: 0x8000020, 0x16: 0x8020020, 0x17: 0x20000, 0x18: 0x0, 0x19: 0x20020, 0x1a: 0x8020000, 0x1b: 0x8000820, 0x1c: 0x8020820, 0x1d: 0x20800, 0x1e: 0x820, 0x1f: 0x8000000, 0x80000010: 0x20000, 0x80000011: 0x800, 0x80000012: 0x8020020, 0x80000013: 0x20820, 0x80000014: 0x20, 0x80000015: 0x8020000, 0x80000016: 0x8000000, 0x80000017: 0x8000820, 0x80000018: 0x8020820, 0x80000019: 0x8000020, 0x8000001a: 0x8000800, 0x8000001b: 0x0, 0x8000001c: 0x20800, 0x8000001d: 0x820, 0x8000001e: 0x20020, 0x8000001f: 0x8020800 } ]; // Masks that select the SBOX input var SBOX_MASK = [ 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f ]; /** * DES block cipher algorithm. */ var DES = C_algo.DES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Select 56 bits according to PC1 var keyBits = []; for (var i = 0; i < 56; i++) { var keyBitPos = PC1[i] - 1; keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; } // Assemble 16 subkeys var subKeys = this._subKeys = []; for (var nSubKey = 0; nSubKey < 16; nSubKey++) { // Create subkey var subKey = subKeys[nSubKey] = []; // Shortcut var bitShift = BIT_SHIFTS[nSubKey]; // Select 48 bits according to PC2 for (var i = 0; i < 24; i++) { // Select from the left 28 key bits subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); // Select from the right 28 key bits subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); } // Since each subkey is applied to an expanded 32-bit input, // the subkey can be broken into 8 values scaled to 32-bits, // which allows the key to be used without expansion subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); for (var i = 1; i < 7; i++) { subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); } subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); } // Compute inverse subkeys var invSubKeys = this._invSubKeys = []; for (var i = 0; i < 16; i++) { invSubKeys[i] = subKeys[15 - i]; } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._subKeys); }, decryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._invSubKeys); }, _doCryptBlock: function (M, offset, subKeys) { // Get input this._lBlock = M[offset]; this._rBlock = M[offset + 1]; // Initial permutation exchangeLR.call(this, 4, 0x0f0f0f0f); exchangeLR.call(this, 16, 0x0000ffff); exchangeRL.call(this, 2, 0x33333333); exchangeRL.call(this, 8, 0x00ff00ff); exchangeLR.call(this, 1, 0x55555555); // Rounds for (var round = 0; round < 16; round++) { // Shortcuts var subKey = subKeys[round]; var lBlock = this._lBlock; var rBlock = this._rBlock; // Feistel function var f = 0; for (var i = 0; i < 8; i++) { f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; } this._lBlock = rBlock; this._rBlock = lBlock ^ f; } // Undo swap from last round var t = this._lBlock; this._lBlock = this._rBlock; this._rBlock = t; // Final permutation exchangeLR.call(this, 1, 0x55555555); exchangeRL.call(this, 8, 0x00ff00ff); exchangeRL.call(this, 2, 0x33333333); exchangeLR.call(this, 16, 0x0000ffff); exchangeLR.call(this, 4, 0x0f0f0f0f); // Set output M[offset] = this._lBlock; M[offset + 1] = this._rBlock; }, keySize: 64/32, ivSize: 64/32, blockSize: 64/32 }); // Swap bits across the left and right words function exchangeLR(offset, mask) { var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; this._rBlock ^= t; this._lBlock ^= t << offset; } function exchangeRL(offset, mask) { var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; this._lBlock ^= t; this._rBlock ^= t << offset; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); */ C.DES = BlockCipher._createHelper(DES); /** * Triple-DES block cipher algorithm. */ var TripleDES = C_algo.TripleDES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Create DES instances this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); }, encryptBlock: function (M, offset) { this._des1.encryptBlock(M, offset); this._des2.decryptBlock(M, offset); this._des3.encryptBlock(M, offset); }, decryptBlock: function (M, offset) { this._des3.decryptBlock(M, offset); this._des2.encryptBlock(M, offset); this._des1.decryptBlock(M, offset); }, keySize: 192/32, ivSize: 64/32, blockSize: 64/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); */ C.TripleDES = BlockCipher._createHelper(TripleDES); }()); return CryptoJS.TripleDES; })); },{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],75:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var X32WordArray = C_lib.WordArray; /** * x64 namespace. */ var C_x64 = C.x64 = {}; /** * A 64-bit word. */ var X64Word = C_x64.Word = Base.extend({ /** * Initializes a newly created 64-bit word. * * @param {number} high The high 32 bits. * @param {number} low The low 32 bits. * * @example * * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); */ init: function (high, low) { this.high = high; this.low = low; } /** * Bitwise NOTs this word. * * @return {X64Word} A new x64-Word object after negating. * * @example * * var negated = x64Word.not(); */ // not: function () { // var high = ~this.high; // var low = ~this.low; // return X64Word.create(high, low); // }, /** * Bitwise ANDs this word with the passed word. * * @param {X64Word} word The x64-Word to AND with this word. * * @return {X64Word} A new x64-Word object after ANDing. * * @example * * var anded = x64Word.and(anotherX64Word); */ // and: function (word) { // var high = this.high & word.high; // var low = this.low & word.low; // return X64Word.create(high, low); // }, /** * Bitwise ORs this word with the passed word. * * @param {X64Word} word The x64-Word to OR with this word. * * @return {X64Word} A new x64-Word object after ORing. * * @example * * var ored = x64Word.or(anotherX64Word); */ // or: function (word) { // var high = this.high | word.high; // var low = this.low | word.low; // return X64Word.create(high, low); // }, /** * Bitwise XORs this word with the passed word. * * @param {X64Word} word The x64-Word to XOR with this word. * * @return {X64Word} A new x64-Word object after XORing. * * @example * * var xored = x64Word.xor(anotherX64Word); */ // xor: function (word) { // var high = this.high ^ word.high; // var low = this.low ^ word.low; // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the left. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftL(25); */ // shiftL: function (n) { // if (n < 32) { // var high = (this.high << n) | (this.low >>> (32 - n)); // var low = this.low << n; // } else { // var high = this.low << (n - 32); // var low = 0; // } // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the right. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftR(7); */ // shiftR: function (n) { // if (n < 32) { // var low = (this.low >>> n) | (this.high << (32 - n)); // var high = this.high >>> n; // } else { // var low = this.high >>> (n - 32); // var high = 0; // } // return X64Word.create(high, low); // }, /** * Rotates this word n bits to the left. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotL(25); */ // rotL: function (n) { // return this.shiftL(n).or(this.shiftR(64 - n)); // }, /** * Rotates this word n bits to the right. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotR(7); */ // rotR: function (n) { // return this.shiftR(n).or(this.shiftL(64 - n)); // }, /** * Adds this word with the passed word. * * @param {X64Word} word The x64-Word to add with this word. * * @return {X64Word} A new x64-Word object after adding. * * @example * * var added = x64Word.add(anotherX64Word); */ // add: function (word) { // var low = (this.low + word.low) | 0; // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; // var high = (this.high + word.high + carry) | 0; // return X64Word.create(high, low); // } }); /** * An array of 64-bit words. * * @property {Array} words The array of CryptoJS.x64.Word objects. * @property {number} sigBytes The number of significant bytes in this word array. */ var X64WordArray = C_x64.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.x64.WordArray.create(); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ]); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ], 10); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } }, /** * Converts this 64-bit word array to a 32-bit word array. * * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. * * @example * * var x32WordArray = x64WordArray.toX32(); */ toX32: function () { // Shortcuts var x64Words = this.words; var x64WordsLength = x64Words.length; // Convert var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); }, /** * Creates a copy of this word array. * * @return {X64WordArray} The clone. * * @example * * var clone = x64WordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); // Clone "words" array var words = clone.words = this.words.slice(0); // Clone each X64Word object var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone; } }); }()); return CryptoJS; })); },{"./core":44}],76:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],77:[function(_dereq_,module,exports){ (function (process,global){ /*! localForage -- Offline Storage, Improved Version 1.3.0 https://mozilla.github.io/localForage (c) 2013-2015 Mozilla, Apache License 2.0 */ (function() { var define, requireModule, _dereq_, requirejs; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requirejs = _dereq_ = requireModule = function(name) { requirejs._eak_seen = registry; if (seen[name]) { return seen[name]; } seen[name] = {}; if (!registry[name]) { throw new Error("Could not find module " + name); } var mod = registry[name], deps = mod.deps, callback = mod.callback, reified = [], exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(resolve(deps[i]))); } } var value = callback.apply(this, reified); return seen[name] = exports || value; function resolve(child) { if (child.charAt(0) !== '.') { return child; } var parts = child.split("/"); var parentBase = name.split("/").slice(0, -1); for (var i=0, l=parts.length; i<l; i++) { var part = parts[i]; if (part === '..') { parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join("/"); } }; })(); define("promise/all", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; var isFunction = __dependency1__.isFunction; /** Returns a promise that is fulfilled when all the given promises have been fulfilled, or rejected if any of them become rejected. The return promise is fulfilled with an array that gives all the values in the order they were passed in the `promises` array argument. Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.resolve(2); var promise3 = RSVP.resolve(3); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `RSVP.all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.reject(new Error("2")); var promise3 = RSVP.reject(new Error("3")); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @for RSVP @param {Array} promises @param {String} label @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. */ function all(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to all.'); } return new Promise(function(resolve, reject) { var results = [], remaining = promises.length, promise; if (remaining === 0) { resolve([]); } function resolver(index) { return function(value) { resolveAll(index, value); }; } function resolveAll(index, value) { results[index] = value; if (--remaining === 0) { resolve(results); } } for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && isFunction(promise.then)) { promise.then(resolver(i), reject); } else { resolveAll(i, promise); } } }); } __exports__.all = all; }); define("promise/asap", ["exports"], function(__exports__) { "use strict"; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this); // node 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() { local.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; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else { scheduleFlush = useSetTimeout(); } function asap(callback, arg) { var length = queue.push([callback, arg]); if (length === 1) { // If length is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. scheduleFlush(); } } __exports__.asap = asap; }); define("promise/config", ["exports"], function(__exports__) { "use strict"; var config = { instrument: false }; function configure(name, value) { if (arguments.length === 2) { config[name] = value; } else { return config[name]; } } __exports__.config = config; __exports__.configure = configure; }); define("promise/polyfill", ["./promise","./utils","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /*global self*/ var RSVPPromise = __dependency1__.Promise; var isFunction = __dependency2__.isFunction; function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = RSVPPromise; } } __exports__.polyfill = polyfill; }); define("promise/promise", ["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __exports__) { "use strict"; var config = __dependency1__.config; var configure = __dependency1__.configure; var objectOrFunction = __dependency2__.objectOrFunction; var isFunction = __dependency2__.isFunction; var now = __dependency2__.now; var all = __dependency3__.all; var race = __dependency4__.race; var staticResolve = __dependency5__.resolve; var staticReject = __dependency6__.reject; var asap = __dependency7__.asap; var counter = 0; config.async = asap; // default async is asap; function Promise(resolver) { if (!isFunction(resolver)) { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } if (!(this instanceof Promise)) { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } this._subscribers = []; invokeResolver(resolver, this); } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch(e) { rejectPromise(e); } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value, error, succeeded, failed; if (hasCallback) { try { value = callback(detail); succeeded = true; } catch(e) { failed = true; error = e; } } else { value = detail; succeeded = true; } if (handleThenable(promise, value)) { return; } else if (hasCallback && succeeded) { resolve(promise, value); } else if (failed) { reject(promise, error); } else if (settled === FULFILLED) { resolve(promise, value); } else if (settled === REJECTED) { reject(promise, value); } } var PENDING = void 0; var SEALED = 0; var FULFILLED = 1; var REJECTED = 2; function subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; subscribers[length] = child; subscribers[length + FULFILLED] = onFulfillment; subscribers[length + REJECTED] = onRejection; } function publish(promise, settled) { var child, callback, subscribers = promise._subscribers, detail = promise._detail; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; invokeCallback(settled, child, callback, detail); } promise._subscribers = null; } Promise.prototype = { constructor: Promise, _state: undefined, _detail: undefined, _subscribers: undefined, then: function(onFulfillment, onRejection) { var promise = this; var thenPromise = new this.constructor(function() {}); if (this._state) { var callbacks = arguments; config.async(function invokePromiseCallback() { invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail); }); } else { subscribe(this, thenPromise, onFulfillment, onRejection); } return thenPromise; }, 'catch': function(onRejection) { return this.then(null, onRejection); } }; Promise.all = all; Promise.race = race; Promise.resolve = staticResolve; Promise.reject = staticReject; function handleThenable(promise, value) { var then = null, resolved; try { if (promise === value) { throw new TypeError("A promises callback cannot return that same promise."); } if (objectOrFunction(value)) { then = value.then; if (isFunction(then)) { then.call(value, function(val) { if (resolved) { return true; } resolved = true; if (value !== val) { resolve(promise, val); } else { fulfill(promise, val); } }, function(val) { if (resolved) { return true; } resolved = true; reject(promise, val); }); return true; } } } catch (error) { if (resolved) { return true; } reject(promise, error); return true; } return false; } function resolve(promise, value) { if (promise === value) { fulfill(promise, value); } else if (!handleThenable(promise, value)) { fulfill(promise, value); } } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = value; config.async(publishFulfillment, promise); } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = reason; config.async(publishRejection, promise); } function publishFulfillment(promise) { publish(promise, promise._state = FULFILLED); } function publishRejection(promise) { publish(promise, promise._state = REJECTED); } __exports__.Promise = Promise; }); define("promise/race", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; /** `RSVP.race` allows you to watch a series of promises and act as soon as the first promise given to the `promises` argument fulfills or rejects. Example: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 2"); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // result === "promise 2" because it was resolved before promise1 // was resolved. }); ``` `RSVP.race` is deterministic in that only the state of the first completed promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first completed promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error("promise 2")); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // Code here never runs because there are rejected promises! }, function(reason){ // reason.message === "promise2" because promise 2 became rejected before // promise 1 became fulfilled }); ``` @method race @for RSVP @param {Array} promises array of promises to observe @param {String} label optional string for describing the promise returned. Useful for tooling. @return {Promise} a promise that becomes fulfilled with the value the first completed promises is resolved with if the first completed promise was fulfilled, or rejected with the reason that the first completed promise was rejected with. */ function race(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to race.'); } return new Promise(function(resolve, reject) { var results = [], promise; for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolve, reject); } else { resolve(promise); } } }); } __exports__.race = race; }); define("promise/reject", ["exports"], function(__exports__) { "use strict"; /** `RSVP.reject` returns a promise that will become rejected with the passed `reason`. `RSVP.reject` is essentially shorthand for the following: ```javascript var promise = new RSVP.Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript var promise = RSVP.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @for RSVP @param {Any} reason value that the returned promise will be rejected with. @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise that will become rejected with the given `reason`. */ function reject(reason) { /*jshint validthis:true */ var Promise = this; return new Promise(function (resolve, reject) { reject(reason); }); } __exports__.reject = reject; }); define("promise/resolve", ["exports"], function(__exports__) { "use strict"; function resolve(value) { /*jshint validthis:true */ if (value && typeof value === 'object' && value.constructor === this) { return value; } var Promise = this; return new Promise(function(resolve) { resolve(value); }); } __exports__.resolve = resolve; }); define("promise/utils", ["exports"], function(__exports__) { "use strict"; function objectOrFunction(x) { return isFunction(x) || (typeof x === "object" && x !== null); } function isFunction(x) { return typeof x === "function"; } function isArray(x) { return Object.prototype.toString.call(x) === "[object Array]"; } // Date.now is not available in browsers < IE9 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility var now = Date.now || function() { return new Date().getTime(); }; __exports__.objectOrFunction = objectOrFunction; __exports__.isFunction = isFunction; __exports__.isArray = isArray; __exports__.now = now; }); requireModule('promise/polyfill').polyfill(); }());(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["localforage"] = factory(); else root["localforage"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { 'use strict'; // Custom drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var CustomDrivers = {}; var DriverType = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage' }; var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE]; var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem']; var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 var driverSupport = (function (self) { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; var result = {}; result[DriverType.WEBSQL] = !!self.openDatabase; result[DriverType.INDEXEDDB] = !!(function () { // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { return false; } try { return indexedDB && typeof indexedDB.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof self.IDBKeyRange !== 'undefined'; } catch (e) { return false; } })(); result[DriverType.LOCALSTORAGE] = !!(function () { try { return self.localStorage && 'setItem' in self.localStorage && self.localStorage.setItem; } catch (e) { return false; } })(); return result; })(this); var isArray = Array.isArray || function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function () { var _args = arguments; return localForageInstance.ready().then(function () { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var LocalForage = (function () { function LocalForage(options) { _classCallCheck(this, LocalForage); this.INDEXEDDB = DriverType.INDEXEDDB; this.LOCALSTORAGE = DriverType.LOCALSTORAGE; this.WEBSQL = DriverType.WEBSQL; this._defaultConfig = extend({}, DefaultConfig); this._config = extend({}, this._defaultConfig, options); this._driverSet = null; this._initDriver = null; this._ready = false; this._dbInfo = null; this._wrapLibraryMethodsWithReady(); this.setDriver(this._config.driver); } // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function config(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if (typeof options === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { this.setDriver(this._config.driver); } return true; } else if (typeof options === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { var promise = new Promise(function (resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); var namingError = new Error('Custom driver name already in use: ' + driverObject._driver); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } if (isLibraryDriver(driverObject._driver)) { reject(namingError); return; } var customDriverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0; i < customDriverMethods.length; i++) { var customDriverMethod = customDriverMethods[i]; if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { reject(complianceError); return; } } var supportPromise = Promise.resolve(true); if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { supportPromise = driverObject._support(); } else { supportPromise = Promise.resolve(!!driverObject._support); } } supportPromise.then(function (supportResult) { driverSupport[driverName] = supportResult; CustomDrivers[driverName] = driverObject; resolve(); }, reject); } catch (e) { reject(e); } }); promise.then(callback, errorCallback); return promise; }; LocalForage.prototype.driver = function driver() { return this._driver || null; }; LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { var self = this; var getDriverPromise = (function () { if (isLibraryDriver(driverName)) { switch (driverName) { case self.INDEXEDDB: return new Promise(function (resolve, reject) { resolve(__webpack_require__(1)); }); case self.LOCALSTORAGE: return new Promise(function (resolve, reject) { resolve(__webpack_require__(2)); }); case self.WEBSQL: return new Promise(function (resolve, reject) { resolve(__webpack_require__(4)); }); } } else if (CustomDrivers[driverName]) { return Promise.resolve(CustomDrivers[driverName]); } return Promise.reject(new Error('Driver not found.')); })(); getDriverPromise.then(callback, errorCallback); return getDriverPromise; }; LocalForage.prototype.getSerializer = function getSerializer(callback) { var serializerPromise = new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }); if (callback && typeof callback === 'function') { serializerPromise.then(function (result) { callback(result); }); } return serializerPromise; }; LocalForage.prototype.ready = function ready(callback) { var self = this; var promise = self._driverSet.then(function () { if (self._ready === null) { self._ready = self._initDriver(); } return self._ready; }); promise.then(callback, callback); return promise; }; LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { var self = this; if (!isArray(drivers)) { drivers = [drivers]; } var supportedDrivers = this._getSupportedDrivers(drivers); function setDriverToConfig() { self._config.driver = self.driver(); } function initDriver(supportedDrivers) { return function () { var currentDriverIndex = 0; function driverPromiseLoop() { while (currentDriverIndex < supportedDrivers.length) { var driverName = supportedDrivers[currentDriverIndex]; currentDriverIndex++; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._extend(driver); setDriverToConfig(); self._ready = self._initStorage(self._config); return self._ready; })['catch'](driverPromiseLoop); } setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise.reject(error); return self._driverSet; } return driverPromiseLoop(); }; } // There might be a driver initialization in progress // so wait for it to finish in order to avoid a possible // race condition to set _dbInfo var oldDriverSetDone = this._driverSet !== null ? this._driverSet['catch'](function () { return Promise.resolve(); }) : Promise.resolve(); this._driverSet = oldDriverSetDone.then(function () { var driverName = supportedDrivers[0]; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._driver = driver._driver; setDriverToConfig(); self._wrapLibraryMethodsWithReady(); self._initDriver = initDriver(supportedDrivers); }); })['catch'](function () { setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise.reject(error); return self._driverSet; }); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function supports(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { var supportedDrivers = []; for (var i = 0, len = drivers.length; i < len; i++) { var driverName = drivers[i]; if (this.supports(driverName)) { supportedDrivers.push(driverName); } } return supportedDrivers; }; LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0; i < LibraryMethods.length; i++) { callWhenReady(this, LibraryMethods[i]); } }; LocalForage.prototype.createInstance = function createInstance(options) { return new LocalForage(options); }; return LocalForage; })(); var localForage = new LocalForage(); exports['default'] = localForage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 1 */ /***/ function(module, exports) { // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; var supportsBlobs; var dbContexts; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (e) { if (e.name !== 'TypeError') { throw e; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Transform a binary string to an array buffer, because otherwise // weird stuff happens when you try to work with the binary string directly. // It is known. // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) function _binStringToArrayBuffer(bin) { var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; } // Fetch a blob using ajax. This reveals bugs in Chrome < 43. // For details on all this junk: // https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme function _blobAjax(url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.withCredentials = true; xhr.responseType = 'arraybuffer'; xhr.onreadystatechange = function () { if (xhr.readyState !== 4) { return; } if (xhr.status === 200) { return resolve({ response: xhr.response, type: xhr.getResponseHeader('Content-Type') }); } reject({ status: xhr.status, response: xhr.response }); }; xhr.send(); }); } // // Detect blob support. Chrome didn't support it until version 38. // In version 37 they had a broken version where PNGs (and possibly // other binary types) aren't stored correctly, because when you fetch // them, the content type is always null. // // Furthermore, they have some outstanding bugs where blobs occasionally // are read by FileReader as null, or by ajax as 404s. // // Sadly we use the 404 bug to detect the FileReader bug, so if they // get fixed independently and released in different versions of Chrome, // then the bug could come back. So it's worthwhile to watch these issues: // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 // function _checkBlobSupportWithoutCaching(idb) { return new Promise(function (resolve, reject) { var blob = _createBlob([''], { type: 'image/png' }); var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); txn.oncomplete = function () { // have to do it in a separate transaction, else the correct // content type is always returned var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); var getBlobReq = blobTxn.objectStore(DETECT_BLOB_SUPPORT_STORE).get('key'); getBlobReq.onerror = reject; getBlobReq.onsuccess = function (e) { var storedBlob = e.target.result; var url = URL.createObjectURL(storedBlob); _blobAjax(url).then(function (res) { resolve(!!(res && res.type === 'image/png')); }, function () { resolve(false); }).then(function () { URL.revokeObjectURL(url); }); }; }; })['catch'](function () { return false; // error, so assume unsupported }); } function _checkBlobSupport(idb) { if (typeof supportsBlobs === 'boolean') { return Promise.resolve(supportsBlobs); } return _checkBlobSupportWithoutCaching(idb).then(function (value) { supportsBlobs = value; return supportsBlobs; }); } // encode a blob for indexeddb engines that don't support blobs function _encodeBlob(blob) { return new Promise(function (resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function (e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); } // decode an encoded blob function _decodeBlob(encodedBlob) { var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); return _createBlob([arrayBuff], { type: encodedBlob.type }); } // is this one of our fancy encoded blobs? function _isEncodedBlob(value) { return value && value.__local_forage_encoded_blob; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } // Initialize a singleton container for all running localForages. if (!dbContexts) { dbContexts = {}; } // Get the current context of the database; var dbContext = dbContexts[dbInfo.name]; // ...or create a new context. if (!dbContext) { dbContext = { // Running localForages sharing a database. forages: [], // Shared database. db: null }; // Register the new context in the global container. dbContexts[dbInfo.name] = dbContext; } // Register itself as a running localForage in the current context. dbContext.forages.push(this); // Create an array of readiness of the related localForages. var readyPromises = []; function ignoreErrors() { // Don't handle errors here, // just makes sure related localForages aren't pending. return Promise.resolve(); } for (var j = 0; j < dbContext.forages.length; j++) { var forage = dbContext.forages[j]; if (forage !== this) { // Don't wait for itself... readyPromises.push(forage.ready()['catch'](ignoreErrors)); } } // Take a snapshot of the related localForages. var forages = dbContext.forages.slice(0); // Initialize the connection process only when // all the related localForages aren't pending. return Promise.all(readyPromises).then(function () { dbInfo.db = dbContext.db; // Get the connection or open a new one without upgrade. return _getOriginalConnection(dbInfo); }).then(function (db) { dbInfo.db = db; if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { // Reopen the database for upgrading. return _getUpgradedConnection(dbInfo); } return db; }).then(function (db) { dbInfo.db = dbContext.db = db; self._dbInfo = dbInfo; // Share the final connection amongst related localForages. for (var k in forages) { var forage = forages[k]; if (forage !== self) { // Self is already up-to-date. forage._dbInfo.db = dbInfo.db; forage._dbInfo.version = dbInfo.version; } } }); } function _getOriginalConnection(dbInfo) { return _getConnection(dbInfo, false); } function _getUpgradedConnection(dbInfo) { return _getConnection(dbInfo, true); } function _getConnection(dbInfo, upgradeNeeded) { return new Promise(function (resolve, reject) { if (dbInfo.db) { if (upgradeNeeded) { dbInfo.db.close(); } else { return resolve(dbInfo.db); } } var dbArgs = [dbInfo.name]; if (upgradeNeeded) { dbArgs.push(dbInfo.version); } var openreq = indexedDB.open.apply(indexedDB, dbArgs); if (upgradeNeeded) { openreq.onupgradeneeded = function (e) { var db = openreq.result; try { db.createObjectStore(dbInfo.storeName); if (e.oldVersion <= 1) { // Added when support for blob shims was added db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); } } catch (ex) { if (ex.name === 'ConstraintError') { globalObject.console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); } else { throw ex; } } }; } openreq.onerror = function () { reject(openreq.error); }; openreq.onsuccess = function () { resolve(openreq.result); }; }); } function _isUpgradeNeeded(dbInfo, defaultVersion) { if (!dbInfo.db) { return true; } var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); var isDowngrade = dbInfo.version < dbInfo.db.version; var isUpgrade = dbInfo.version > dbInfo.db.version; if (isDowngrade) { // If the version is not the default one // then warn for impossible downgrade. if (dbInfo.version !== defaultVersion) { globalObject.console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.'); } // Align the versions to prevent errors. dbInfo.version = dbInfo.db.version; } if (isUpgrade || isNewStore) { // If the store is new then increment the version (if needed). // This will trigger an "upgradeneeded" event which is required // for creating a store. if (isNewStore) { var incVersion = dbInfo.db.version + 1; if (incVersion > dbInfo.version) { dbInfo.version = incVersion; } } return true; } return false; } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function () { var value = req.result; if (value === undefined) { value = null; } if (_isEncodedBlob(value)) { value = _decodeBlob(value); } resolve(value); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Iterate over all items stored in database. function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function () { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); if (result !== void 0) { resolve(result); } else { cursor['continue'](); } } else { resolve(); } }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { var dbInfo; self.ready().then(function () { dbInfo = self._dbInfo; return _checkBlobSupport(dbInfo.db); }).then(function (blobSupport) { if (!blobSupport && value instanceof Blob) { return _encodeBlob(value); } return value; }).then(function (value) { var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } var req = store.put(value, key); transaction.oncomplete = function () { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `['delete']()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store['delete'](key); transaction.oncomplete = function () { resolve(); }; transaction.onerror = function () { reject(req.error); }; // The request will be also be aborted if we've exceeded our storage // space. transaction.onabort = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); var req = store.clear(); transaction.oncomplete = function () { resolve(); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.count(); req.onsuccess = function () { resolve(req.result); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { if (n < 0) { resolve(null); return; } self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var advanced = false; var req = store.openCursor(); req.onsuccess = function () { var cursor = req.result; if (!cursor) { // this means there weren't enough keys resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. resolve(cursor.key); } } }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var keys = []; req.onsuccess = function () { var cursor = req.result; if (!cursor) { resolve(keys); return; } keys.push(cursor.key); cursor['continue'](); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = asyncStorage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { // If IndexedDB isn't available, we'll fall back to localStorage. // Note that this will have considerable performance and storage // side-effects (all data will be serialized on save and only data that // can be converted to a string via `JSON.stringify()` will be saved). 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // If localStorage isn't available, we get outta here! // This should be inside a try catch if (!this.localStorage || !('setItem' in this.localStorage)) { return; } // Initialize localStorage and create a variable to use throughout // the code. localStorage = this.localStorage; } catch (e) { return; } // Config the localStorage backend, using options set in the config. function _initStorage(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = dbInfo.name + '/'; if (dbInfo.storeName !== self._defaultConfig.storeName) { dbInfo.keyPrefix += dbInfo.storeName + '/'; } self._dbInfo = dbInfo; return new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }).then(function (lib) { dbInfo.serializer = lib; return Promise.resolve(); }); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear(callback) { var self = this; var promise = self.ready().then(function () { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = dbInfo.serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate(iterator, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var keyPrefix = dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; // We use a dedicated iterator instead of the `i` variable below // so other keys we fetch in localStorage aren't counted in // the `iterationNumber` argument passed to the `iterate()` // callback. // // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 var iterationNumber = 1; for (var i = 0; i < length; i++) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) !== 0) { continue; } var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = dbInfo.serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); if (value !== void 0) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key(n, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length(callback) { var self = this; var promise = self.keys().then(function (keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise(function (resolve, reject) { var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { try { localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage, // Default API, from Gaia/localStorage. iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = localStorageWrapper; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; (function () { 'use strict'; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var BLOB_TYPE_PREFIX = '~~local_forage_type~'; var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // Get out of our habit of using `window` inline, at least. var globalObject = this; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (err) { if (err.name !== 'TypeError') { throw err; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueString === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function () { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return _createBlob([buffer], { type: blobType }); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i += 4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); /*jslint bitwise: true */ bytes[p++] = encoded1 << 2 | encoded2 >> 4; bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if (bytes.length % 3 === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; exports['default'] = localforageSerializer; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; var openDatabase = this.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; } } var dbInfoPromise = new Promise(function (resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return self.setDriver(self.LOCALSTORAGE).then(function () { return self._initStorage(options); }).then(resolve)['catch'](reject); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function (t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () { self._dbInfo = dbInfo; resolve(); }, function (t, error) { reject(error); }); }); }); return new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }).then(function (lib) { dbInfo.serializer = lib; return dbInfoPromise; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = dbInfo.serializer.deserialize(result); } resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = dbInfo.serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void 0) { resolve(result); return; } } resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { dbInfo.db.transaction(function (t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () { resolve(originalValue); }, function (t, error) { reject(error); }); }, function (sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. reject(sqlError); } }); } }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () { resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { var result = results.rows.item(0).c; resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = webSQLStorage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ } /******/ ]) }); ; }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":76}],78:[function(_dereq_,module,exports){ // Top level file is just a mixin of submodules & constants 'use strict'; var assign = _dereq_('./lib/utils/common').assign; var deflate = _dereq_('./lib/deflate'); var inflate = _dereq_('./lib/inflate'); var constants = _dereq_('./lib/zlib/constants'); var pako = {}; assign(pako, deflate, inflate, constants); module.exports = pako; },{"./lib/deflate":79,"./lib/inflate":80,"./lib/utils/common":81,"./lib/zlib/constants":84}],79:[function(_dereq_,module,exports){ 'use strict'; var zlib_deflate = _dereq_('./zlib/deflate.js'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var msg = _dereq_('./zlib/messages'); var zstream = _dereq_('./zlib/zstream'); var toString = Object.prototype.toString; /* Public constants ==========================================================*/ /* ===========================================================================*/ var Z_NO_FLUSH = 0; var Z_FINISH = 4; var Z_OK = 0; var Z_STREAM_END = 1; var Z_SYNC_FLUSH = 2; var Z_DEFAULT_COMPRESSION = -1; var Z_DEFAULT_STRATEGY = 0; var Z_DEFLATED = 8; /* ===========================================================================*/ /** * class Deflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[deflate]], * [[deflateRaw]] and [[gzip]]. **/ /* internal * Deflate.chunks -> Array * * Chunks of output data, if [[Deflate#onData]] not overriden. **/ /** * Deflate.result -> Uint8Array|Array * * Compressed result, generated by default [[Deflate#onData]] * and [[Deflate#onEnd]] handlers. Filled after you push last chunk * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Deflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Deflate.err -> Number * * Error code after deflate finished. 0 (Z_OK) on success. * You will not need it in real life, because deflate errors * are possible only on wrong options or bad `onData` / `onEnd` * custom handlers. **/ /** * Deflate.msg -> String * * Error message, if [[Deflate.err]] != 0 **/ /** * new Deflate(options) * - options (Object): zlib deflate options. * * Creates new deflator instance with specified params. Throws exception * on bad params. Supported options: * * - `level` * - `windowBits` * - `memLevel` * - `strategy` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw deflate * - `gzip` (Boolean) - create gzip wrapper * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * - `header` (Object) - custom header for gzip * - `text` (Boolean) - true if compressed data believed to be text * - `time` (Number) - modification time, unix timestamp * - `os` (Number) - operation system code * - `extra` (Array) - array of bytes with extra data (max 65536) * - `name` (String) - file name (binary string) * - `comment` (String) - comment (binary string) * - `hcrc` (Boolean) - true if header crc should be added * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var deflate = new pako.Deflate({ level: 3}); * * deflate.push(chunk1, false); * deflate.push(chunk2, true); // true -> last chunk * * if (deflate.err) { throw new Error(deflate.err); } * * console.log(deflate.result); * ``` **/ var Deflate = function(options) { this.options = utils.assign({ level: Z_DEFAULT_COMPRESSION, method: Z_DEFLATED, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: Z_DEFAULT_STRATEGY, to: '' }, options || {}); var opt = this.options; if (opt.raw && (opt.windowBits > 0)) { opt.windowBits = -opt.windowBits; } else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { opt.windowBits += 16; } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = zlib_deflate.deflateInit2( this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy ); if (status !== Z_OK) { throw new Error(msg[status]); } if (opt.header) { zlib_deflate.deflateSetHeader(this.strm, opt.header); } }; /** * Deflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be * converted to utf8 byte sequence. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with * new compressed chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the compression context. * * On fail call [[Deflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * array format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Deflate.prototype.push = function(data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // If we need to compress text, change encoding to utf8. strm.input = strings.string2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ if (status !== Z_STREAM_END && status !== Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { if (this.options.to === 'string') { this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); // Finalize on the last chunk. if (_mode === Z_FINISH) { status = zlib_deflate.deflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === Z_SYNC_FLUSH) { this.onEnd(Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Deflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Deflate.prototype.onData = function(chunk) { this.chunks.push(chunk); }; /** * Deflate#onEnd(status) -> Void * - status (Number): deflate status. 0 (Z_OK) on success, * other if not. * * Called once after you tell deflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Deflate.prototype.onEnd = function(status) { // On success - join if (status === Z_OK) { if (this.options.to === 'string') { this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * deflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * Compress `data` with deflate alrorythm and `options`. * * Supported options are: * * - level * - windowBits * - memLevel * - strategy * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * * ##### Example: * * ```javascript * var pako = require('pako') * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); * * console.log(pako.deflate(data)); * ``` **/ function deflate(input, options) { var deflator = new Deflate(options); deflator.push(input, true); // That will never happens, if you don't cheat with options :) if (deflator.err) { throw deflator.msg; } return deflator.result; } /** * deflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function deflateRaw(input, options) { options = options || {}; options.raw = true; return deflate(input, options); } /** * gzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but create gzip wrapper instead of * deflate one. **/ function gzip(input, options) { options = options || {}; options.gzip = true; return deflate(input, options); } exports.Deflate = Deflate; exports.deflate = deflate; exports.deflateRaw = deflateRaw; exports.gzip = gzip; },{"./utils/common":81,"./utils/strings":82,"./zlib/deflate.js":86,"./zlib/messages":91,"./zlib/zstream":93}],80:[function(_dereq_,module,exports){ 'use strict'; var zlib_inflate = _dereq_('./zlib/inflate.js'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var c = _dereq_('./zlib/constants'); var msg = _dereq_('./zlib/messages'); var zstream = _dereq_('./zlib/zstream'); var gzheader = _dereq_('./zlib/gzheader'); var toString = Object.prototype.toString; /** * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[inflate]] * and [[inflateRaw]]. **/ /* internal * inflate.chunks -> Array * * Chunks of output data, if [[Inflate#onData]] not overriden. **/ /** * Inflate.result -> Uint8Array|Array|String * * Uncompressed result, generated by default [[Inflate#onData]] * and [[Inflate#onEnd]] handlers. Filled after you push last chunk * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Inflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Inflate.err -> Number * * Error code after inflate finished. 0 (Z_OK) on success. * Should be checked if broken data possible. **/ /** * Inflate.msg -> String * * Error message, if [[Inflate.err]] != 0 **/ /** * new Inflate(options) * - options (Object): zlib inflate options. * * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * * - `windowBits` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw inflate * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * By default, when no options set, autodetect deflate/gzip data format via * wrapper header. * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var inflate = new pako.Inflate({ level: 3}); * * inflate.push(chunk1, false); * inflate.push(chunk2, true); // true -> last chunk * * if (inflate.err) { throw new Error(inflate.err); } * * console.log(inflate.result); * ``` **/ var Inflate = function(options) { this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if ((opt.windowBits >= 0) && (opt.windowBits < 16) && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if ((opt.windowBits > 15) && (opt.windowBits < 48)) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = zlib_inflate.inflateInit2( this.strm, opt.windowBits ); if (status !== c.Z_OK) { throw new Error(msg[status]); } this.header = new gzheader(); zlib_inflate.inflateGetHeader(this.strm, this.header); }; /** * Inflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with * new output chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the decompression context. * * On fail call [[Inflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Inflate.prototype.push = function(data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; var next_out_utf8, tail, utf8str; // Flag to properly process Z_BUF_ERROR on testing inflate call // when we check that all output data was flushed. var allowBufError = false; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // Only binary strings can be decompressed on practice strm.input = strings.binstring2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ if (status === c.Z_BUF_ERROR && allowBufError === true) { status = c.Z_OK; allowBufError = false; } if (status !== c.Z_STREAM_END && status !== c.Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.next_out) { if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { if (this.options.to === 'string') { next_out_utf8 = strings.utf8border(strm.output, strm.next_out); tail = strm.next_out - next_out_utf8; utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail strm.next_out = tail; strm.avail_out = chunkSize - tail; if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } this.onData(utf8str); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } // When no more input data, we should check that internal inflate buffers // are flushed. The only way to do it when avail_out = 0 - run one more // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. // Here we set flag to process this error properly. // // NOTE. Deflate does not return error in this case and does not needs such // logic. if (strm.avail_in === 0 && strm.avail_out === 0) { allowBufError = true; } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); if (status === c.Z_STREAM_END) { _mode = c.Z_FINISH; } // Finalize on the last chunk. if (_mode === c.Z_FINISH) { status = zlib_inflate.inflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === c.Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === c.Z_SYNC_FLUSH) { this.onEnd(c.Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Inflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Inflate.prototype.onData = function(chunk) { this.chunks.push(chunk); }; /** * Inflate#onEnd(status) -> Void * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * * Called either after you tell inflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Inflate.prototype.onEnd = function(status) { // On success - join if (status === c.Z_OK) { if (this.options.to === 'string') { // Glue & convert here, until we teach pako to send // utf8 alligned strings to onData this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * inflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Decompress `data` with inflate/ungzip and `options`. Autodetect * format via wrapper header by default. That's why we don't provide * separate `ungzip` method. * * Supported options are: * * - windowBits * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * * ##### Example: * * ```javascript * var pako = require('pako') * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) * , output; * * try { * output = pako.inflate(input); * } catch (err) * console.log(err); * } * ``` **/ function inflate(input, options) { var inflator = new Inflate(options); inflator.push(input, true); // That will never happens, if you don't cheat with options :) if (inflator.err) { throw inflator.msg; } return inflator.result; } /** * inflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function inflateRaw(input, options) { options = options || {}; options.raw = true; return inflate(input, options); } /** * ungzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Just shortcut to [[inflate]], because it autodetects format * by header.content. Done for convenience. **/ exports.Inflate = Inflate; exports.inflate = inflate; exports.inflateRaw = inflateRaw; exports.ungzip = inflate; },{"./utils/common":81,"./utils/strings":82,"./zlib/constants":84,"./zlib/gzheader":87,"./zlib/inflate.js":89,"./zlib/messages":91,"./zlib/zstream":93}],81:[function(_dereq_,module,exports){ 'use strict'; var TYPED_OK = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Int32Array !== 'undefined'); exports.assign = function (obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1); while (sources.length) { var source = sources.shift(); if (!source) { continue; } if (typeof source !== 'object') { throw new TypeError(source + 'must be non-object'); } for (var p in source) { if (source.hasOwnProperty(p)) { obj[p] = source[p]; } } } return obj; }; // reduce buffer size, avoiding mem copy exports.shrinkBuf = function (buf, size) { if (buf.length === size) { return buf; } if (buf.subarray) { return buf.subarray(0, size); } buf.length = size; return buf; }; var fnTyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { if (src.subarray && dest.subarray) { dest.set(src.subarray(src_offs, src_offs+len), dest_offs); return; } // Fallback to ordinary array for (var i=0; i<len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function(chunks) { var i, l, len, pos, chunk, result; // calculate data length len = 0; for (i=0, l=chunks.length; i<l; i++) { len += chunks[i].length; } // join chunks result = new Uint8Array(len); pos = 0; for (i=0, l=chunks.length; i<l; i++) { chunk = chunks[i]; result.set(chunk, pos); pos += chunk.length; } return result; } }; var fnUntyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { for (var i=0; i<len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function(chunks) { return [].concat.apply([], chunks); } }; // Enable/Disable typed arrays use, for testing // exports.setTyped = function (on) { if (on) { exports.Buf8 = Uint8Array; exports.Buf16 = Uint16Array; exports.Buf32 = Int32Array; exports.assign(exports, fnTyped); } else { exports.Buf8 = Array; exports.Buf16 = Array; exports.Buf32 = Array; exports.assign(exports, fnUntyped); } }; exports.setTyped(TYPED_OK); },{}],82:[function(_dereq_,module,exports){ // String encode/decode helpers 'use strict'; var utils = _dereq_('./common'); // Quick check if we can use fast array to bin string conversion // // - apply(Array) can fail on Android 2.2 // - apply(Uint8Array) can fail on iOS 5.1 Safary // var STR_APPLY_OK = true; var STR_APPLY_UIA_OK = true; try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; } try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; } // Table with utf8 lengths (calculated by first byte of sequence) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff var _utf8len = new utils.Buf8(256); for (var q=0; q<256; q++) { _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); } _utf8len[254]=_utf8len[254]=1; // Invalid sequence start // convert string to array (typed, when possible) exports.string2buf = function (str) { var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } // allocate buffer buf = new utils.Buf8(buf_len); // convert for (i=0, m_pos = 0; i < buf_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } if (c < 0x80) { /* one byte */ buf[i++] = c; } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | (c >>> 6); buf[i++] = 0x80 | (c & 0x3f); } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | (c >>> 12); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } else { /* four bytes */ buf[i++] = 0xf0 | (c >>> 18); buf[i++] = 0x80 | (c >>> 12 & 0x3f); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } } return buf; }; // Helper (used in 2 places) function buf2binstring(buf, len) { // use fallback for big arrays to avoid stack overflow if (len < 65537) { if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); } } var result = ''; for (var i=0; i < len; i++) { result += String.fromCharCode(buf[i]); } return result; } // Convert byte array to binary string exports.buf2binstring = function(buf) { return buf2binstring(buf, buf.length); }; // Convert binary string (typed, when possible) exports.binstring2buf = function(str) { var buf = new utils.Buf8(str.length); for (var i=0, len=buf.length; i < len; i++) { buf[i] = str.charCodeAt(i); } return buf; }; // convert array to string exports.buf2string = function (buf, max) { var i, out, c, c_len; var len = max || buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. var utf16buf = new Array(len*2); for (out=0, i=0; i<len;) { c = buf[i++]; // quick process ascii if (c < 0x80) { utf16buf[out++] = c; continue; } c_len = _utf8len[c]; // skip 5 & 6 byte codes if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } // apply mask on first byte c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest while (c_len > 1 && i < len) { c = (c << 6) | (buf[i++] & 0x3f); c_len--; } // terminated by end of string? if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } if (c < 0x10000) { utf16buf[out++] = c; } else { c -= 0x10000; utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); utf16buf[out++] = 0xdc00 | (c & 0x3ff); } } return buf2binstring(utf16buf, out); }; // Calculate max possible position in utf8 buffer, // that will not break sequence. If that's not possible // - (very small limits) return max size as is. // // buf[] - utf8 bytes array // max - length limit (mandatory); exports.utf8border = function(buf, max) { var pos; max = max || buf.length; if (max > buf.length) { max = buf.length; } // go back from last position, until start of sequence found pos = max-1; while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } // Fuckup - very small and broken sequence, // return max, because we should return something anyway. if (pos < 0) { return max; } // If we came to start of buffer - that means vuffer is too small, // return max too. if (pos === 0) { return max; } return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; },{"./common":81}],83:[function(_dereq_,module,exports){ 'use strict'; // Note: adler32 takes 12% for level 0 and 2% for level 6. // It doesn't worth to make additional optimizationa as in original. // Small size is preferable. function adler32(adler, buf, len, pos) { var s1 = (adler & 0xffff) |0, s2 = ((adler >>> 16) & 0xffff) |0, n = 0; while (len !== 0) { // Set limit ~ twice less than 5552, to keep // s2 in 31-bits, because we force signed ints. // in other case %= will fail. n = len > 2000 ? 2000 : len; len -= n; do { s1 = (s1 + buf[pos++]) |0; s2 = (s2 + s1) |0; } while (--n); s1 %= 65521; s2 %= 65521; } return (s1 | (s2 << 16)) |0; } module.exports = adler32; },{}],84:[function(_dereq_,module,exports){ module.exports = { /* Allowed flush values; see deflate() and inflate() below for details */ 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, /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, //Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, //Z_VERSION_ERROR: -6, /* compression levels */ 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, /* Possible values of the data_type field (though see inflate()) */ Z_BINARY: 0, Z_TEXT: 1, //Z_ASCII: 1, // = Z_TEXT (deprecated) Z_UNKNOWN: 2, /* The deflate compression method */ Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type }; },{}],85:[function(_dereq_,module,exports){ 'use strict'; // Note: we can't get significant speed boost here. // So write code to minimize size - no pregenerated tables // and array tools dependencies. // Use ordinary array, since untyped makes no boost here function makeTable() { var c, table = []; for (var n =0; n < 256; n++) { c = n; for (var k =0; k < 8; k++) { c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } table[n] = c; } return table; } // Create table on load. Just 255 signed longs. Not a problem. var crcTable = makeTable(); function crc32(crc, buf, len, pos) { var t = crcTable, end = pos + len; crc = crc ^ (-1); for (var i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; },{}],86:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var trees = _dereq_('./trees'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var msg = _dereq_('./messages'); /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ var Z_NO_FLUSH = 0; var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; //var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; //var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; //var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* compression levels */ //var Z_NO_COMPRESSION = 0; //var Z_BEST_SPEED = 1; //var Z_BEST_COMPRESSION = 9; var Z_DEFAULT_COMPRESSION = -1; var Z_FILTERED = 1; var Z_HUFFMAN_ONLY = 2; var Z_RLE = 3; var Z_FIXED = 4; var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ //var Z_BINARY = 0; //var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /* The deflate compression method */ var Z_DEFLATED = 8; /*============================================================================*/ var MAX_MEM_LEVEL = 9; /* Maximum value for memLevel in deflateInit2 */ var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_MEM_LEVEL = 8; var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2*L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var MIN_MATCH = 3; var MAX_MATCH = 258; var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); var PRESET_DICT = 0x20; var INIT_STATE = 42; var EXTRA_STATE = 69; var NAME_STATE = 73; var COMMENT_STATE = 91; var HCRC_STATE = 103; var BUSY_STATE = 113; var FINISH_STATE = 666; var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ var BS_BLOCK_DONE = 2; /* block flush performed */ var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. function err(strm, errorCode) { strm.msg = msg[errorCode]; return errorCode; } function rank(f) { return ((f) << 1) - ((f) > 4 ? 9 : 0); } function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->output buffer and copying into it. * (See also read_buf()). */ function flush_pending(strm) { var s = strm.state; //_tr_flush_bits(s); var len = s.pending; if (len > strm.avail_out) { len = strm.avail_out; } if (len === 0) { return; } utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); strm.next_out += len; s.pending_out += len; strm.total_out += len; strm.avail_out -= len; s.pending -= len; if (s.pending === 0) { s.pending_out = 0; } } function flush_block_only (s, last) { trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); s.block_start = s.strstart; flush_pending(s.strm); } function put_byte(s, b) { s.pending_buf[s.pending++] = b; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ function putShortMSB(s, b) { // put_byte(s, (Byte)(b >> 8)); // put_byte(s, (Byte)(b & 0xff)); s.pending_buf[s.pending++] = (b >>> 8) & 0xff; s.pending_buf[s.pending++] = b & 0xff; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->input buffer and copying from it. * (See also flush_pending()). */ function read_buf(strm, buf, start, size) { var len = strm.avail_in; if (len > size) { len = size; } if (len === 0) { return 0; } strm.avail_in -= len; utils.arraySet(buf, strm.input, strm.next_in, len, start); if (strm.state.wrap === 1) { strm.adler = adler32(strm.adler, buf, len, start); } else if (strm.state.wrap === 2) { strm.adler = crc32(strm.adler, buf, len, start); } strm.next_in += len; strm.total_in += len; return len; } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ function longest_match(s, cur_match) { var chain_length = s.max_chain_length; /* max hash chain length */ var scan = s.strstart; /* current string */ var match; /* matched string */ var len; /* length of current match */ var best_len = s.prev_length; /* best match length so far */ var nice_match = s.nice_match; /* stop if match long enough */ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; var _win = s.window; // shortcut var wmask = s.w_mask; var prev = s.prev; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ var strend = s.strstart + MAX_MATCH; var scan_end1 = _win[scan + best_len - 1]; var scan_end = _win[scan + best_len]; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s.prev_length >= s.good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (nice_match > s.lookahead) { nice_match = s.lookahead; } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { // Assert(cur_match < s->strstart, "no future"); match = cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { continue; } /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2; match++; // Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { /*jshint noempty:false*/ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { s.match_start = cur_match; best_len = len; if (len >= nice_match) { break; } scan_end1 = _win[scan + best_len - 1]; scan_end = _win[scan + best_len]; } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); if (best_len <= s.lookahead) { return best_len; } return s.lookahead; } /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ function fill_window(s) { var _w_size = s.w_size; var p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = s.window_size - s.lookahead - s.strstart; // JS ints have 32 bit, block below not needed /* Deal with !@#$% 64K limit: */ //if (sizeof(int) <= 2) { // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { // more = wsize; // // } else if (more == (unsigned)(-1)) { // /* Very unlikely, but possible on 16 bit machine if // * strstart == 0 && lookahead == 1 (input done a byte at time) // */ // more--; // } //} /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { utils.arraySet(s.window, s.window, _w_size, _w_size, 0); s.match_start -= _w_size; s.strstart -= _w_size; /* we now have strstart >= MAX_DIST */ s.block_start -= _w_size; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s.hash_size; p = n; do { m = s.head[--p]; s.head[p] = (m >= _w_size ? m - _w_size : 0); } while (--n); n = _w_size; p = n; do { m = s.prev[--p]; s.prev[p] = (m >= _w_size ? m - _w_size : 0); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += _w_size; } if (s.strm.avail_in === 0) { break; } /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ //Assert(more >= 2, "more < 2"); n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); s.lookahead += n; /* Initialize the hash value now that we have some input: */ if (s.lookahead + s.insert >= MIN_MATCH) { str = s.strstart - s.insert; s.ins_h = s.window[str]; /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call update_hash() MIN_MATCH-3 more times //#endif while (s.insert) { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; s.insert--; if (s.lookahead + s.insert < MIN_MATCH) { break; } } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ // if (s.high_water < s.window_size) { // var curr = s.strstart + s.lookahead; // var init = 0; // // if (s.high_water < curr) { // /* Previous high water mark below current data -- zero WIN_INIT // * bytes or up to end of window, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->window + curr, (unsigned)init); // s->high_water = curr + init; // } // else if (s->high_water < (ulg)curr + WIN_INIT) { // /* High water mark at or above current data, but below current data // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up // * to end of window, whichever is less. // */ // init = (ulg)curr + WIN_INIT - s->high_water; // if (init > s->window_size - s->high_water) // init = s->window_size - s->high_water; // zmemzero(s->window + s->high_water, (unsigned)init); // s->high_water += init; // } // } // // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, // "not enough room for search"); } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ function deflate_stored(s, flush) { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ var max_block_size = 0xffff; if (max_block_size > s.pending_buf_size - 5) { max_block_size = s.pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s.lookahead <= 1) { //Assert(s->strstart < s->w_size+MAX_DIST(s) || // s->block_start >= (long)s->w_size, "slide too late"); // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || // s.block_start >= s.w_size)) { // throw new Error("slide too late"); // } fill_window(s); if (s.lookahead === 0 && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } //Assert(s->block_start >= 0L, "block gone"); // if (s.block_start < 0) throw new Error("block gone"); s.strstart += s.lookahead; s.lookahead = 0; /* Emit a stored block if pending_buf will be full: */ var max_start = s.block_start + max_block_size; if (s.strstart === 0 || s.strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s.lookahead = s.strstart - max_start; s.strstart = max_start; /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.strstart > s.block_start) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_NEED_MORE; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ function deflate_fast(s, flush) { var hash_head; /* head of the hash chain */ var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; /* flush the current block */ } } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ } if (s.match_length >= MIN_MATCH) { // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only /*** _tr_tally_dist(s, s.strstart - s.match_start, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { s.match_length--; /* string at strstart already in table */ do { s.strstart++; /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s.match_length !== 0); s.strstart++; } else { s.strstart += s.match_length; s.match_length = 0; s.ins_h = s.window[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call UPDATE_HASH() MIN_MATCH-3 more times //#endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s.window[s.strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1); if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ function deflate_slow(s, flush) { var hash_head; /* head of hash chain */ var bflush; /* set if current block must be flushed */ var max_insert; /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. */ s.prev_length = s.match_length; s.prev_match = s.match_start; s.match_length = MIN_MATCH-1; if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ if (s.match_length <= 5 && (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s.match_length = MIN_MATCH-1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { max_insert = s.strstart + s.lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ //check_match(s, s.strstart-1, s.prev_match, s.prev_length); /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH, bflush);***/ bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s.lookahead -= s.prev_length-1; s.prev_length -= 2; do { if (++s.strstart <= max_insert) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } } while (--s.prev_length !== 0); s.match_available = 0; s.match_length = MIN_MATCH-1; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } else if (s.match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); if (bflush) { /*** FLUSH_BLOCK_ONLY(s, 0) ***/ flush_block_only(s, false); /***/ } s.strstart++; s.lookahead--; if (s.strm.avail_out === 0) { return BS_NEED_MORE; } } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s.match_available = 1; s.strstart++; s.lookahead--; } } //Assert (flush != Z_NO_FLUSH, "no flush?"); if (s.match_available) { //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); s.match_available = 0; } s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ function deflate_rle(s, flush) { var bflush; /* set if current block must be flushed */ var prev; /* byte at distance one to match */ var scan, strend; /* scan goes up to strend for length of run */ var _win = s.window; for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s.lookahead <= MAX_MATCH) { fill_window(s); if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* See how many times the previous byte repeats */ s.match_length = 0; if (s.lookahead >= MIN_MATCH && s.strstart > 0) { scan = s.strstart - 1; prev = _win[scan]; if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { strend = s.strstart + MAX_MATCH; do { /*jshint noempty:false*/ } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); s.match_length = MAX_MATCH - (strend - scan); if (s.match_length > s.lookahead) { s.match_length = s.lookahead; } } //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s.match_length >= MIN_MATCH) { //check_match(s, s.strstart, s.strstart - 1, s.match_length); /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; s.strstart += s.match_length; s.match_length = 0; } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ function deflate_huff(s, flush) { var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s.lookahead === 0) { fill_window(s); if (s.lookahead === 0) { if (flush === Z_NO_FLUSH) { return BS_NEED_MORE; } break; /* flush the current block */ } } /* Output a literal byte */ s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ var Config = function (good_length, max_lazy, nice_length, max_chain, func) { this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; this.max_chain = max_chain; this.func = func; }; var configuration_table; configuration_table = [ /* good lazy nice chain */ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ new Config(4, 5, 16, 8, deflate_fast), /* 2 */ new Config(4, 6, 32, 32, deflate_fast), /* 3 */ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ new Config(8, 16, 32, 32, deflate_slow), /* 5 */ new Config(8, 16, 128, 128, deflate_slow), /* 6 */ new Config(8, 32, 128, 256, deflate_slow), /* 7 */ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ ]; /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ function lm_init(s) { s.window_size = 2 * s.w_size; /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); /* Set the default configuration parameters: */ s.max_lazy_match = configuration_table[s.level].max_lazy; s.good_match = configuration_table[s.level].good_length; s.nice_match = configuration_table[s.level].nice_length; s.max_chain_length = configuration_table[s.level].max_chain; s.strstart = 0; s.block_start = 0; s.lookahead = 0; s.insert = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; s.ins_h = 0; } function DeflateState() { this.strm = null; /* pointer back to this zlib stream */ this.status = 0; /* as the name implies */ this.pending_buf = null; /* output still pending */ this.pending_buf_size = 0; /* size of pending_buf */ this.pending_out = 0; /* next pending byte to output to the stream */ this.pending = 0; /* nb of bytes in the pending buffer */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.gzhead = null; /* gzip header information to write */ this.gzindex = 0; /* where in extra, name, or comment */ this.method = Z_DEFLATED; /* can only be DEFLATED */ this.last_flush = -1; /* value of flush param for previous deflate call */ this.w_size = 0; /* LZ77 window size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.window = null; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. */ this.window_size = 0; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ this.prev = null; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ this.head = null; /* Heads of the hash chains or NIL. */ this.ins_h = 0; /* hash index of string to be inserted */ this.hash_size = 0; /* number of elements in hash table */ this.hash_bits = 0; /* log2(hash_size) */ this.hash_mask = 0; /* hash_size-1 */ this.hash_shift = 0; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ this.block_start = 0; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ this.match_length = 0; /* length of best match */ this.prev_match = 0; /* previous match */ this.match_available = 0; /* set if previous match exists */ this.strstart = 0; /* start of string to insert */ this.match_start = 0; /* start of matching string */ this.lookahead = 0; /* number of valid bytes ahead in window */ this.prev_length = 0; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ this.max_chain_length = 0; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ this.max_lazy_match = 0; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ // That's alias to max_lazy_match, don't use directly //this.max_insert_length = 0; /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ this.level = 0; /* compression level (1..9) */ this.strategy = 0; /* favor or force Huffman coding*/ this.good_match = 0; /* Use a faster search when the previous match is longer than this */ this.nice_match = 0; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to suppress compiler warning */ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ // Use flat array of DOUBLE size, with interleaved fata, // because JS does not support effective this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2); this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2); zero(this.dyn_ltree); zero(this.dyn_dtree); zero(this.bl_tree); this.l_desc = null; /* desc. for literal tree */ this.d_desc = null; /* desc. for distance tree */ this.bl_desc = null; /* desc. for bit length tree */ //ush bl_count[MAX_BITS+1]; this.bl_count = new utils.Buf16(MAX_BITS+1); /* number of codes at each bit length for an optimal tree */ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */ zero(this.heap); this.heap_len = 0; /* number of elements in the heap */ this.heap_max = 0; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1]; zero(this.depth); /* Depth of each subtree used as tie breaker for trees of equal frequency */ this.l_buf = 0; /* buffer index for literals or lengths */ this.lit_bufsize = 0; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ this.last_lit = 0; /* running index in l_buf */ this.d_buf = 0; /* Buffer index for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ this.opt_len = 0; /* bit length of current block with optimal trees */ this.static_len = 0; /* bit length of current block with static trees */ this.matches = 0; /* number of string matches in current block */ this.insert = 0; /* bytes at end of window left to insert */ this.bi_buf = 0; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ this.bi_valid = 0; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ // Used for window memory init. We safely ignore it for JS. That makes // sense only for pointers and memory check tools. //this.high_water = 0; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } function deflateResetKeep(strm) { var s; if (!strm || !strm.state) { return err(strm, Z_STREAM_ERROR); } strm.total_in = strm.total_out = 0; strm.data_type = Z_UNKNOWN; s = strm.state; s.pending = 0; s.pending_out = 0; if (s.wrap < 0) { s.wrap = -s.wrap; /* was made negative by deflate(..., Z_FINISH); */ } s.status = (s.wrap ? INIT_STATE : BUSY_STATE); strm.adler = (s.wrap === 2) ? 0 // crc32(0, Z_NULL, 0) : 1; // adler32(0, Z_NULL, 0) s.last_flush = Z_NO_FLUSH; trees._tr_init(s); return Z_OK; } function deflateReset(strm) { var ret = deflateResetKeep(strm); if (ret === Z_OK) { lm_init(strm.state); } return ret; } function deflateSetHeader(strm, head) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } strm.state.gzhead = head; return Z_OK; } function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { if (!strm) { // === Z_NULL return Z_STREAM_ERROR; } var wrap = 1; if (level === Z_DEFAULT_COMPRESSION) { level = 6; } if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return err(strm, Z_STREAM_ERROR); } if (windowBits === 8) { windowBits = 9; } /* until 256-byte window bug fixed */ var s = new DeflateState(); strm.state = s; s.strm = strm; s.wrap = wrap; s.gzhead = null; s.w_bits = windowBits; s.w_size = 1 << s.w_bits; s.w_mask = s.w_size - 1; s.hash_bits = memLevel + 7; s.hash_size = 1 << s.hash_bits; s.hash_mask = s.hash_size - 1; s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); s.window = new utils.Buf8(s.w_size * 2); s.head = new utils.Buf16(s.hash_size); s.prev = new utils.Buf16(s.w_size); // Don't need mem init magic for JS. //s.high_water = 0; /* nothing written to s->window yet */ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ s.pending_buf_size = s.lit_bufsize * 4; s.pending_buf = new utils.Buf8(s.pending_buf_size); s.d_buf = s.lit_bufsize >> 1; s.l_buf = (1 + 2) * s.lit_bufsize; s.level = level; s.strategy = strategy; s.method = method; return deflateReset(strm); } function deflateInit(strm, level) { return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } function deflate(strm, flush) { var old_flush, s; var beg, val; // for gzip header write only if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; } s = strm.state; if (!strm.output || (!strm.input && strm.avail_in !== 0) || (s.status === FINISH_STATE && flush !== Z_FINISH)) { return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); } s.strm = strm; /* just in case */ old_flush = s.last_flush; s.last_flush = flush; /* Write the header */ if (s.status === INIT_STATE) { if (s.wrap === 2) { // GZIP header strm.adler = 0; //crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (!s.gzhead) { // s->gzhead == Z_NULL put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s.status = BUSY_STATE; } else { put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) ); put_byte(s, s.gzhead.time & 0xff); put_byte(s, (s.gzhead.time >> 8) & 0xff); put_byte(s, (s.gzhead.time >> 16) & 0xff); put_byte(s, (s.gzhead.time >> 24) & 0xff); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, s.gzhead.os & 0xff); if (s.gzhead.extra && s.gzhead.extra.length) { put_byte(s, s.gzhead.extra.length & 0xff); put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); } if (s.gzhead.hcrc) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); } s.gzindex = 0; s.status = EXTRA_STATE; } } else // DEFLATE header { var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; var level_flags = -1; if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { level_flags = 0; } else if (s.level < 6) { level_flags = 1; } else if (s.level === 6) { level_flags = 2; } else { level_flags = 3; } header |= (level_flags << 6); if (s.strstart !== 0) { header |= PRESET_DICT; } header += 31 - (header % 31); s.status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s.strstart !== 0) { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } strm.adler = 1; // adler32(0L, Z_NULL, 0); } } //#ifdef GZIP if (s.status === EXTRA_STATE) { if (s.gzhead.extra/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { break; } } put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); s.gzindex++; } if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (s.gzindex === s.gzhead.extra.length) { s.gzindex = 0; s.status = NAME_STATE; } } else { s.status = NAME_STATE; } } if (s.status === NAME_STATE) { if (s.gzhead.name/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.name.length) { val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.gzindex = 0; s.status = COMMENT_STATE; } } else { s.status = COMMENT_STATE; } } if (s.status === COMMENT_STATE) { if (s.gzhead.comment/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.comment.length) { val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.status = HCRC_STATE; } } else { s.status = HCRC_STATE; } } if (s.status === HCRC_STATE) { if (s.gzhead.hcrc) { if (s.pending + 2 > s.pending_buf_size) { flush_pending(strm); } if (s.pending + 2 <= s.pending_buf_size) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); strm.adler = 0; //crc32(0L, Z_NULL, 0); s.status = BUSY_STATE; } } else { s.status = BUSY_STATE; } } //#endif /* Flush as much pending output as possible */ if (s.pending !== 0) { flush_pending(strm); if (strm.avail_out === 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s.last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { return err(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s.status === FINISH_STATE && strm.avail_in !== 0) { return err(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm.avail_in !== 0 || s.lookahead !== 0 || (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : (s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush)); if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { s.status = FINISH_STATE; } if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate === BS_BLOCK_DONE) { if (flush === Z_PARTIAL_FLUSH) { trees._tr_align(s); } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ trees._tr_stored_block(s, 0, 0, false); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush === Z_FULL_FLUSH) { /*** CLEAR_HASH(s); ***/ /* forget history */ zero(s.head); // Fill with NIL (= 0); if (s.lookahead === 0) { s.strstart = 0; s.block_start = 0; s.insert = 0; } } } flush_pending(strm); if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } //Assert(strm->avail_out > 0, "bug2"); //if (strm.avail_out <= 0) { throw new Error("bug2");} if (flush !== Z_FINISH) { return Z_OK; } if (s.wrap <= 0) { return Z_STREAM_END; } /* Write the trailer */ if (s.wrap === 2) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); put_byte(s, (strm.adler >> 16) & 0xff); put_byte(s, (strm.adler >> 24) & 0xff); put_byte(s, strm.total_in & 0xff); put_byte(s, (strm.total_in >> 8) & 0xff); put_byte(s, (strm.total_in >> 16) & 0xff); put_byte(s, (strm.total_in >> 24) & 0xff); } else { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s.wrap > 0) { s.wrap = -s.wrap; } /* write the trailer only once! */ return s.pending !== 0 ? Z_OK : Z_STREAM_END; } function deflateEnd(strm) { var status; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } status = strm.state.status; if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE ) { return err(strm, Z_STREAM_ERROR); } strm.state = null; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; } /* ========================================================================= * Copy the source state to the destination state */ //function deflateCopy(dest, source) { // //} exports.deflateInit = deflateInit; exports.deflateInit2 = deflateInit2; exports.deflateReset = deflateReset; exports.deflateResetKeep = deflateResetKeep; exports.deflateSetHeader = deflateSetHeader; exports.deflate = deflate; exports.deflateEnd = deflateEnd; exports.deflateInfo = 'pako deflate (from Nodeca project)'; /* Not implemented exports.deflateBound = deflateBound; exports.deflateCopy = deflateCopy; exports.deflateSetDictionary = deflateSetDictionary; exports.deflateParams = deflateParams; exports.deflatePending = deflatePending; exports.deflatePrime = deflatePrime; exports.deflateTune = deflateTune; */ },{"../utils/common":81,"./adler32":83,"./crc32":85,"./messages":91,"./trees":92}],87:[function(_dereq_,module,exports){ 'use strict'; function GZheader() { /* true if compressed data believed to be text */ this.text = 0; /* modification time */ this.time = 0; /* extra flags (not used when writing a gzip file) */ this.xflags = 0; /* operating system */ this.os = 0; /* pointer to extra field or Z_NULL if none */ this.extra = null; /* extra field length (valid if extra != Z_NULL) */ this.extra_len = 0; // Actually, we don't need it in JS, // but leave for few code modifications // // Setup limits is not necessary because in js we should not preallocate memory // for inflate use constant limit in 65536 bytes // /* space at extra (only when reading header) */ // this.extra_max = 0; /* pointer to zero-terminated file name or Z_NULL */ this.name = ''; /* space at name (only when reading header) */ // this.name_max = 0; /* pointer to zero-terminated comment or Z_NULL */ this.comment = ''; /* space at comment (only when reading header) */ // this.comm_max = 0; /* true if there was or will be a header crc */ this.hcrc = 0; /* true when done reading gzip header (not used when writing a gzip file) */ this.done = false; } module.exports = GZheader; },{}],88:[function(_dereq_,module,exports){ 'use strict'; // See state defs from inflate.js var BAD = 30; /* got a data error -- remain here until reset */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state.mode === LEN strm.avail_in >= 6 strm.avail_out >= 258 start >= strm.avail_out state.bits < 8 On return, state.mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm.avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm.avail_out >= 258 for each loop to avoid checking for output space. */ module.exports = function inflate_fast(strm, start) { var state; var _in; /* local strm.input */ var last; /* have enough input while in < last */ var _out; /* local strm.output */ var beg; /* inflate()'s initial strm.output */ var end; /* while out < end, enough space available */ //#ifdef INFLATE_STRICT var dmax; /* maximum distance from zlib header */ //#endif var wsize; /* window size or zero if not using window */ var whave; /* valid bytes in the window */ var wnext; /* window write index */ // Use `s_window` instead `window`, avoid conflict with instrumentation tools var s_window; /* allocated sliding window, if wsize != 0 */ var hold; /* local strm.hold */ var bits; /* local strm.bits */ var lcode; /* local strm.lencode */ var dcode; /* local strm.distcode */ var lmask; /* mask for first level of length codes */ var dmask; /* mask for first level of distance codes */ var here; /* retrieved table entry */ var op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ var len; /* match length, unused bytes */ var dist; /* match distance */ var from; /* where to copy match from */ var from_source; var input, output; // JS specific, because we have no pointers /* copy state to local variables */ state = strm.state; //here = state.here; _in = strm.next_in; input = strm.input; last = _in + (strm.avail_in - 5); _out = strm.next_out; output = strm.output; beg = _out - (start - strm.avail_out); end = _out + (strm.avail_out - 257); //#ifdef INFLATE_STRICT dmax = state.dmax; //#endif wsize = state.wsize; whave = state.whave; wnext = state.wnext; s_window = state.window; hold = state.hold; bits = state.bits; lcode = state.lencode; dcode = state.distcode; lmask = (1 << state.lenbits) - 1; dmask = (1 << state.distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ top: do { if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = lcode[hold & lmask]; dolen: for (;;) { // Goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op === 0) { /* literal */ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); output[_out++] = here & 0xffff/*here.val*/; } else if (op & 16) { /* length base */ len = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += input[_in++] << bits; bits += 8; } len += hold & ((1 << op) - 1); hold >>>= op; bits -= op; } //Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = dcode[hold & dmask]; dodist: for (;;) { // goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op & 16) { /* distance base */ dist = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (bits < op) { hold += input[_in++] << bits; bits += 8; if (bits < op) { hold += input[_in++] << bits; bits += 8; } } dist += hold & ((1 << op) - 1); //#ifdef INFLATE_STRICT if (dist > dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } //#endif hold >>>= op; bits -= op; //Tracevv((stderr, "inflate: distance %u\n", dist)); op = _out - beg; /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // if (len <= op - whave) { // do { // output[_out++] = 0; // } while (--len); // continue top; // } // len -= op - whave; // do { // output[_out++] = 0; // } while (--op > whave); // if (op === 0) { // from = _out - dist; // do { // output[_out++] = output[from++]; // } while (--len); // continue top; // } //#endif } from = 0; // window index from_source = s_window; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } while (len > 2) { output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; len -= 3; } if (len) { output[_out++] = from_source[from++]; if (len > 1) { output[_out++] = from_source[from++]; } } } else { from = _out - dist; /* copy direct from output */ do { /* minimum length is three */ output[_out++] = output[from++]; output[_out++] = output[from++]; output[_out++] = output[from++]; len -= 3; } while (len > 2); if (len) { output[_out++] = output[from++]; if (len > 1) { output[_out++] = output[from++]; } } } } else if ((op & 64) === 0) { /* 2nd level distance code */ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dodist; } else { strm.msg = 'invalid distance code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } else if ((op & 64) === 0) { /* 2nd level length code */ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dolen; } else if (op & 32) { /* end-of-block */ //Tracevv((stderr, "inflate: end of block\n")); state.mode = TYPE; break top; } else { strm.msg = 'invalid literal/length code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } while (_in < last && _out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; _in -= len; bits -= len << 3; hold &= (1 << bits) - 1; /* update state and return */ strm.next_in = _in; strm.next_out = _out; strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); state.hold = hold; state.bits = bits; return; }; },{}],89:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var inflate_fast = _dereq_('./inffast'); var inflate_table = _dereq_('./inftrees'); var CODES = 0; var LENS = 1; var DISTS = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ //var Z_NO_FLUSH = 0; //var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; //var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* The deflate compression method */ var Z_DEFLATED = 8; /* STATES ====================================================================*/ /* ===========================================================================*/ var HEAD = 1; /* i: waiting for magic header */ var FLAGS = 2; /* i: waiting for method and flags (gzip) */ var TIME = 3; /* i: waiting for modification time (gzip) */ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ var EXLEN = 5; /* i: waiting for extra length (gzip) */ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ var NAME = 7; /* i: waiting for end of file name (gzip) */ var COMMENT = 8; /* i: waiting for end of comment (gzip) */ var HCRC = 9; /* i: waiting for header crc (gzip) */ var DICTID = 10; /* i: waiting for dictionary check value */ var DICT = 11; /* waiting for inflateSetDictionary() call */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ var STORED = 14; /* i: waiting for stored size (length and complement) */ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ var COPY = 16; /* i/o: waiting for input or output to copy stored block */ var TABLE = 17; /* i: waiting for dynamic block table lengths */ var LENLENS = 18; /* i: waiting for code length code lengths */ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ var LEN_ = 20; /* i: same as LEN below, but only first time in */ var LEN = 21; /* i: waiting for length/lit/eob code */ var LENEXT = 22; /* i: waiting for length extra bits */ var DIST = 23; /* i: waiting for distance code */ var DISTEXT = 24; /* i: waiting for distance extra bits */ var MATCH = 25; /* o: waiting for output space to copy string */ var LIT = 26; /* o: waiting for output space to write literal */ var CHECK = 27; /* i: waiting for 32-bit check value */ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ var DONE = 29; /* finished check, done -- remain here until reset */ var BAD = 30; /* got a data error -- remain here until reset */ var MEM = 31; /* got an inflate() memory error -- remain here until reset */ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_WBITS = MAX_WBITS; function ZSWAP32(q) { return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); } function InflateState() { this.mode = 0; /* current inflate mode */ this.last = false; /* true if processing last block */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.havedict = false; /* true if dictionary provided */ this.flags = 0; /* gzip header method and flags (0 if zlib) */ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ this.check = 0; /* protected copy of check value */ this.total = 0; /* protected copy of output count */ // TODO: may be {} this.head = null; /* where to save gzip header information */ /* sliding window */ this.wbits = 0; /* log base 2 of requested window size */ this.wsize = 0; /* window size or zero if not using window */ this.whave = 0; /* valid bytes in the window */ this.wnext = 0; /* window write index */ this.window = null; /* allocated sliding window, if needed */ /* bit accumulator */ this.hold = 0; /* input bit accumulator */ this.bits = 0; /* number of bits in "in" */ /* for string and stored block copying */ this.length = 0; /* literal or length of data to copy */ this.offset = 0; /* distance back to copy string from */ /* for table and code decoding */ this.extra = 0; /* extra bits needed */ /* fixed and dynamic code tables */ this.lencode = null; /* starting table for length/literal codes */ this.distcode = null; /* starting table for distance codes */ this.lenbits = 0; /* index bits for lencode */ this.distbits = 0; /* index bits for distcode */ /* dynamic table building */ this.ncode = 0; /* number of code length code lengths */ this.nlen = 0; /* number of length code lengths */ this.ndist = 0; /* number of distance code lengths */ this.have = 0; /* number of code lengths in lens[] */ this.next = null; /* next available space in codes[] */ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ this.work = new utils.Buf16(288); /* work area for code table building */ /* because we don't have pointers in js, we use lencode and distcode directly as buffers so we don't need codes */ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ this.distdyn = null; /* dynamic table for distance codes (JS specific) */ this.sane = 0; /* if false, allow invalid distance too far */ this.back = 0; /* bits back of last unprocessed length/lit */ this.was = 0; /* initial length of match */ } function inflateResetKeep(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; strm.total_in = strm.total_out = state.total = 0; strm.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ strm.adler = state.wrap & 1; } state.mode = HEAD; state.last = 0; state.havedict = 0; state.dmax = 32768; state.head = null/*Z_NULL*/; state.hold = 0; state.bits = 0; //state.lencode = state.distcode = state.next = state.codes; state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); state.sane = 1; state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; } function inflateReset(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); } function inflateReset2(strm, windowBits) { var wrap; var state; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; if (windowBits < 48) { windowBits &= 15; } } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.window !== null && state.wbits !== windowBits) { state.window = null; } /* update state and reset the rest of it */ state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); } function inflateInit2(strm, windowBits) { var ret; var state; if (!strm) { return Z_STREAM_ERROR; } //strm.msg = Z_NULL; /* in case we return an error */ state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null/*Z_NULL*/; ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null/*Z_NULL*/; } return ret; } function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ var virgin = true; var lenfix, distfix; // We have no pointers in JS, so keep tables separate function fixedtables(state) { /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { var sym; lenfix = new utils.Buf32(512); distfix = new utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9}); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5}); /* do this just once */ virgin = false; } state.lencode = lenfix; state.lenbits = 9; state.distcode = distfix; state.distbits = 5; } /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ function updatewindow(strm, src, end, copy) { var dist; var state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.window = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state.wsize) { utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0); state.wnext = 0; state.whave = state.wsize; } else { dist = state.wsize - state.wnext; if (dist > copy) { dist = copy; } //zmemcpy(state->window + state->wnext, end - copy, dist); utils.arraySet(state.window,src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->window, end - copy, copy); utils.arraySet(state.window,src, end - copy, copy, 0); state.wnext = copy; state.whave = state.wsize; } else { state.wnext += dist; if (state.wnext === state.wsize) { state.wnext = 0; } if (state.whave < state.wsize) { state.whave += dist; } } } return 0; } function inflate(strm, flush) { var state; var input, output; // input/output buffers var next; /* next input INDEX */ var put; /* next output INDEX */ var have, left; /* available input and output */ var hold; /* bit buffer */ var bits; /* bits in bit buffer */ var _in, _out; /* save starting available input and output */ var copy; /* number of stored or match bytes to copy */ var from; /* where to copy match bytes from */ var from_source; var here = 0; /* current decoding table entry */ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) //var last; /* parent table entry */ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) var len; /* length to copy for repeats, bits to drop */ var ret; /* return code */ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ var opts; var n; // temporary var for NEED_BITS var order = /* permutation of code lengths */ [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; if (!strm || !strm.state || !strm.output || (!strm.input && strm.avail_in !== 0)) { return Z_STREAM_ERROR; } state = strm.state; if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- _in = have; _out = left; ret = Z_OK; inf_leave: // goto emulation for (;;) { switch (state.mode) { case HEAD: if (state.wrap === 0) { state.mode = TYPEDO; break; } //=== NEEDBITS(16); while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ state.check = 0/*crc32(0L, Z_NULL, 0)*/; //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = FLAGS; break; } state.flags = 0; /* expect zlib header */ if (state.head) { state.head.done = false; } if (!(state.wrap & 1) || /* check if zlib header allowed */ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { strm.msg = 'incorrect header check'; state.mode = BAD; break; } if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// len = (hold & 0x0f)/*BITS(4)*/ + 8; if (state.wbits === 0) { state.wbits = len; } else if (len > state.wbits) { strm.msg = 'invalid window size'; state.mode = BAD; break; } state.dmax = 1 << len; //Tracev((stderr, "inflate: zlib header ok\n")); strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = hold & 0x200 ? DICTID : TYPE; //=== INITBITS(); hold = 0; bits = 0; //===// break; case FLAGS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.flags = hold; if ((state.flags & 0xff) !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } if (state.flags & 0xe000) { strm.msg = 'unknown header flags set'; state.mode = BAD; break; } if (state.head) { state.head.text = ((hold >> 8) & 1); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = TIME; /* falls through */ case TIME: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.time = hold; } if (state.flags & 0x0200) { //=== CRC4(state.check, hold) hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; hbuf[2] = (hold >>> 16) & 0xff; hbuf[3] = (hold >>> 24) & 0xff; state.check = crc32(state.check, hbuf, 4, 0); //=== } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = OS; /* falls through */ case OS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.xflags = (hold & 0xff); state.head.os = (hold >> 8); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = EXLEN; /* falls through */ case EXLEN: if (state.flags & 0x0400) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length = hold; if (state.head) { state.head.extra_len = hold; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// } else if (state.head) { state.head.extra = null/*Z_NULL*/; } state.mode = EXTRA; /* falls through */ case EXTRA: if (state.flags & 0x0400) { copy = state.length; if (copy > have) { copy = have; } if (copy) { if (state.head) { len = state.head.extra_len - state.length; if (!state.head.extra) { // Use untyped array for more conveniend processing later state.head.extra = new Array(state.head.extra_len); } utils.arraySet( state.head.extra, input, next, // extra field is limited to 65536 bytes // - no need for additional size check copy, /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ len ); //zmemcpy(state.head.extra + len, next, // len + copy > state.head.extra_max ? // state.head.extra_max - len : copy); } if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; state.length -= copy; } if (state.length) { break inf_leave; } } state.length = 0; state.mode = NAME; /* falls through */ case NAME: if (state.flags & 0x0800) { if (have === 0) { break inf_leave; } copy = 0; do { // TODO: 2 or 1 bytes? len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.name_max*/)) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.name = null; } state.length = 0; state.mode = COMMENT; /* falls through */ case COMMENT: if (state.flags & 0x1000) { if (have === 0) { break inf_leave; } copy = 0; do { len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.comm_max*/)) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.comment = null; } state.mode = HCRC; /* falls through */ case HCRC: if (state.flags & 0x0200) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.check & 0xffff)) { strm.msg = 'header crc mismatch'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// } if (state.head) { state.head.hcrc = ((state.flags >> 9) & 1); state.head.done = true; } strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/; state.mode = TYPE; break; case DICTID: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// strm.adler = state.check = ZSWAP32(hold); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = DICT; /* falls through */ case DICT: if (state.havedict === 0) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- return Z_NEED_DICT; } strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = TYPE; /* falls through */ case TYPE: if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } /* falls through */ case TYPEDO: if (state.last) { //--- BYTEBITS() ---// hold >>>= bits & 7; bits -= bits & 7; //---// state.mode = CHECK; break; } //=== NEEDBITS(3); */ while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.last = (hold & 0x01)/*BITS(1)*/; //--- DROPBITS(1) ---// hold >>>= 1; bits -= 1; //---// switch ((hold & 0x03)/*BITS(2)*/) { case 0: /* stored block */ //Tracev((stderr, "inflate: stored block%s\n", // state.last ? " (last)" : "")); state.mode = STORED; break; case 1: /* fixed block */ fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n", // state.last ? " (last)" : "")); state.mode = LEN_; /* decode codes */ if (flush === Z_TREES) { //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break inf_leave; } break; case 2: /* dynamic block */ //Tracev((stderr, "inflate: dynamic codes block%s\n", // state.last ? " (last)" : "")); state.mode = TABLE; break; case 3: strm.msg = 'invalid block type'; state.mode = BAD; } //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break; case STORED: //--- BYTEBITS() ---// /* go to byte boundary */ hold >>>= bits & 7; bits -= bits & 7; //---// //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { strm.msg = 'invalid stored block lengths'; state.mode = BAD; break; } state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n", // state.length)); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = COPY_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case COPY_: state.mode = COPY; /* falls through */ case COPY: copy = state.length; if (copy) { if (copy > have) { copy = have; } if (copy > left) { copy = left; } if (copy === 0) { break inf_leave; } //--- zmemcpy(put, next, copy); --- utils.arraySet(output, input, next, copy, put); //---// have -= copy; next += copy; left -= copy; put += copy; state.length -= copy; break; } //Tracev((stderr, "inflate: stored end\n")); state.mode = TYPE; break; case TABLE: //=== NEEDBITS(14); */ while (bits < 14) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// //#ifndef PKZIP_BUG_WORKAROUND if (state.nlen > 286 || state.ndist > 30) { strm.msg = 'too many length or distance symbols'; state.mode = BAD; break; } //#endif //Tracev((stderr, "inflate: table sizes ok\n")); state.have = 0; state.mode = LENLENS; /* falls through */ case LENLENS: while (state.have < state.ncode) { //=== NEEDBITS(3); while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } while (state.have < 19) { state.lens[order[state.have++]] = 0; } // We have separate tables & no pointers. 2 commented lines below not needed. //state.next = state.codes; //state.lencode = state.next; // Switch to use dynamic table state.lencode = state.lendyn; state.lenbits = 7; opts = {bits: state.lenbits}; ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); state.lenbits = opts.bits; if (ret) { strm.msg = 'invalid code lengths set'; state.mode = BAD; break; } //Tracev((stderr, "inflate: code lengths ok\n")); state.have = 0; state.mode = CODELENS; /* falls through */ case CODELENS: while (state.have < state.nlen + state.ndist) { for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_val < 16) { //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.lens[state.have++] = here_val; } else { if (here_val === 16) { //=== NEEDBITS(here.bits + 2); n = here_bits + 2; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// if (state.have === 0) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } len = state.lens[state.have - 1]; copy = 3 + (hold & 0x03);//BITS(2); //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// } else if (here_val === 17) { //=== NEEDBITS(here.bits + 3); n = here_bits + 3; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 3 + (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } else { //=== NEEDBITS(here.bits + 7); n = here_bits + 7; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 11 + (hold & 0x7f);//BITS(7); //--- DROPBITS(7) ---// hold >>>= 7; bits -= 7; //---// } if (state.have + copy > state.nlen + state.ndist) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } while (copy--) { state.lens[state.have++] = len; } } } /* handle error breaks in while */ if (state.mode === BAD) { break; } /* check for end-of-block code (better have one) */ if (state.lens[256] === 0) { strm.msg = 'invalid code -- missing end-of-block'; state.mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state.lenbits = 9; opts = {bits: state.lenbits}; ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.lenbits = opts.bits; // state.lencode = state.next; if (ret) { strm.msg = 'invalid literal/lengths set'; state.mode = BAD; break; } state.distbits = 6; //state.distcode.copy(state.codes); // Switch to use dynamic table state.distcode = state.distdyn; opts = {bits: state.distbits}; ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.distbits = opts.bits; // state.distcode = state.next; if (ret) { strm.msg = 'invalid distances set'; state.mode = BAD; break; } //Tracev((stderr, 'inflate: codes ok\n')); state.mode = LEN_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case LEN_: state.mode = LEN; /* falls through */ case LEN: if (have >= 6 && left >= 258) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- inflate_fast(strm, _out); //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- if (state.mode === TYPE) { state.back = -1; } break; } state.back = 0; for (;;) { here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_op && (here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.lencode[last_val + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; state.length = here_val; if (here_op === 0) { //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); state.mode = LIT; break; } if (here_op & 32) { //Tracevv((stderr, "inflate: end of block\n")); state.back = -1; state.mode = TYPE; break; } if (here_op & 64) { strm.msg = 'invalid literal/length code'; state.mode = BAD; break; } state.extra = here_op & 15; state.mode = LENEXT; /* falls through */ case LENEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //Tracevv((stderr, "inflate: length %u\n", state.length)); state.was = state.length; state.mode = DIST; /* falls through */ case DIST: for (;;) { here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if ((here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.distcode[last_val + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; if (here_op & 64) { strm.msg = 'invalid distance code'; state.mode = BAD; break; } state.offset = here_val; state.extra = (here_op) & 15; state.mode = DISTEXT; /* falls through */ case DISTEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //#ifdef INFLATE_STRICT if (state.offset > state.dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } //#endif //Tracevv((stderr, "inflate: distance %u\n", state.offset)); state.mode = MATCH; /* falls through */ case MATCH: if (left === 0) { break inf_leave; } copy = _out - left; if (state.offset > copy) { /* copy from window */ copy = state.offset - copy; if (copy > state.whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // Trace((stderr, "inflate.c too far\n")); // copy -= state.whave; // if (copy > state.length) { copy = state.length; } // if (copy > left) { copy = left; } // left -= copy; // state.length -= copy; // do { // output[put++] = 0; // } while (--copy); // if (state.length === 0) { state.mode = LEN; } // break; //#endif } if (copy > state.wnext) { copy -= state.wnext; from = state.wsize - copy; } else { from = state.wnext - copy; } if (copy > state.length) { copy = state.length; } from_source = state.window; } else { /* copy from output */ from_source = output; from = put - state.offset; copy = state.length; } if (copy > left) { copy = left; } left -= copy; state.length -= copy; do { output[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; } break; case LIT: if (left === 0) { break inf_leave; } output[put++] = state.length; left--; state.mode = LEN; break; case CHECK: if (state.wrap) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; // Use '|' insdead of '+' to make sure that result is signed hold |= input[next++] << bits; bits += 8; } //===// _out -= left; strm.total_out += _out; state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); } _out = left; // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) { strm.msg = 'incorrect data check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: check matches trailer\n")); } state.mode = LENGTH; /* falls through */ case LENGTH: if (state.wrap && state.flags) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.total & 0xffffffff)) { strm.msg = 'incorrect length check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: length matches trailer\n")); } state.mode = DONE; /* falls through */ case DONE: ret = Z_STREAM_END; break inf_leave; case BAD: ret = Z_DATA_ERROR; break inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* falls through */ default: return Z_STREAM_ERROR; } } // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH))) { if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { state.mode = MEM; return Z_MEM_ERROR; } } _in -= strm.avail_in; _out -= strm.avail_out; strm.total_in += _in; strm.total_out += _out; state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { ret = Z_BUF_ERROR; } return ret; } function inflateEnd(strm) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { return Z_STREAM_ERROR; } var state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; } function inflateGetHeader(strm, head) { var state; /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; } exports.inflateReset = inflateReset; exports.inflateReset2 = inflateReset2; exports.inflateResetKeep = inflateResetKeep; exports.inflateInit = inflateInit; exports.inflateInit2 = inflateInit2; exports.inflate = inflate; exports.inflateEnd = inflateEnd; exports.inflateGetHeader = inflateGetHeader; exports.inflateInfo = 'pako inflate (from Nodeca project)'; /* Not implemented exports.inflateCopy = inflateCopy; exports.inflateGetDictionary = inflateGetDictionary; exports.inflateMark = inflateMark; exports.inflatePrime = inflatePrime; exports.inflateSetDictionary = inflateSetDictionary; exports.inflateSync = inflateSync; exports.inflateSyncPoint = inflateSyncPoint; exports.inflateUndermine = inflateUndermine; */ },{"../utils/common":81,"./adler32":83,"./crc32":85,"./inffast":88,"./inftrees":90}],90:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var MAXBITS = 15; var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var CODES = 0; var LENS = 1; var DISTS = 2; var lbase = [ /* Length codes 257..285 base */ 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 ]; var lext = [ /* Length codes 257..285 extra */ 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 ]; var dbase = [ /* Distance codes 0..29 base */ 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 ]; var dext = [ /* Distance codes 0..29 extra */ 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 ]; module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { var bits = opts.bits; //here = opts.here; /* table entry for duplication */ var len = 0; /* a code's length in bits */ var sym = 0; /* index of code symbols */ var min = 0, max = 0; /* minimum and maximum code lengths */ var root = 0; /* number of index bits for root table */ var curr = 0; /* number of index bits for current table */ var drop = 0; /* code bits to drop for sub-table */ var left = 0; /* number of prefix codes available */ var used = 0; /* code entries in table used */ var huff = 0; /* Huffman code */ var incr; /* for incrementing code, index */ var fill; /* index for replicating entries */ var low; /* low bits for current root entry */ var mask; /* mask for low root bits */ var next; /* next available space in table */ var base = null; /* base value table to use */ var base_index = 0; // var shoextra; /* extra bits table to use */ var end; /* use base and extra for symbol > end */ var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */ var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */ var extra = null; var extra_index = 0; var here_bits, here_op, here_val; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) { count[len] = 0; } for (sym = 0; sym < codes; sym++) { count[lens[lens_index + sym]]++; } /* bound code lengths, force root to be within code lengths */ root = bits; for (max = MAXBITS; max >= 1; max--) { if (count[max] !== 0) { break; } } if (root > max) { root = max; } if (max === 0) { /* no symbols to code at all */ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ //table.bits[opts.table_index] = 1; //here.bits = (var char)1; //table.val[opts.table_index++] = 0; //here.val = (var short)0; table[table_index++] = (1 << 24) | (64 << 16) | 0; //table.op[opts.table_index] = 64; //table.bits[opts.table_index] = 1; //table.val[opts.table_index++] = 0; table[table_index++] = (1 << 24) | (64 << 16) | 0; opts.bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) { if (count[min] !== 0) { break; } } if (root < min) { root = min; } /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) { return -1; } /* over-subscribed */ } if (left > 0 && (type === CODES || max !== 1)) { return -1; /* incomplete set */ } /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + count[len]; } /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) { if (lens[lens_index + sym] !== 0) { work[offs[lens[lens_index + sym]]++] = sym; } } /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ // poor man optimization - use if-else instead of switch, // to avoid deopts in old v8 if (type === CODES) { base = extra = work; /* dummy value--not used */ end = 19; } else if (type === LENS) { base = lbase; base_index -= 257; extra = lext; extra_index -= 257; end = 256; } else { /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize opts for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = table_index; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = -1; /* trigger new sub-table when len > root */ used = 1 << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } var i=0; /* process all codes and make table entries */ for (;;) { i++; /* create table entry */ here_bits = len - drop; if (work[sym] < end) { here_op = 0; here_val = work[sym]; } else if (work[sym] > end) { here_op = extra[extra_index + work[sym]]; here_val = base[base_index + work[sym]]; } else { here_op = 32 + 64; /* end of block */ here_val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1 << (len - drop); fill = 1 << curr; min = fill; /* save offset to next table */ do { fill -= incr; table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; } while (fill !== 0); /* backwards increment the len-bit code huff */ incr = 1 << (len - 1); while (huff & incr) { incr >>= 1; } if (incr !== 0) { huff &= incr - 1; huff += incr; } else { huff = 0; } /* go to next symbol, update count, len */ sym++; if (--count[len] === 0) { if (len === max) { break; } len = lens[lens_index + work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) !== low) { /* if first time, transition to sub-tables */ if (drop === 0) { drop = root; } /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = 1 << curr; while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) { break; } curr++; left <<= 1; } /* check for enough space */ used += 1 << curr; if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* point entry in root table to sub-table */ low = huff & mask; /*table.op[low] = curr; table.bits[low] = root; table.val[low] = next - opts.table_index;*/ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff !== 0) { //table.op[next + huff] = 64; /* invalid code marker */ //table.bits[next + huff] = len - drop; //table.val[next + huff] = 0; table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; } /* set return parameters */ //opts.table_index += used; opts.bits = root; return 0; }; },{"../utils/common":81}],91:[function(_dereq_,module,exports){ 'use strict'; module.exports = { '2': 'need dictionary', /* Z_NEED_DICT 2 */ '1': 'stream end', /* Z_STREAM_END 1 */ '0': '', /* Z_OK 0 */ '-1': 'file error', /* Z_ERRNO (-1) */ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ '-3': 'data error', /* Z_DATA_ERROR (-3) */ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; },{}],92:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); /* Public constants ==========================================================*/ /* ===========================================================================*/ //var Z_FILTERED = 1; //var Z_HUFFMAN_ONLY = 2; //var Z_RLE = 3; var Z_FIXED = 4; //var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ var Z_BINARY = 0; var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /*============================================================================*/ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } // From zutil.h var STORED_BLOCK = 0; var STATIC_TREES = 1; var DYN_TREES = 2; /* The three kinds of block type */ var MIN_MATCH = 3; var MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h /* =========================================================================== * Internal compression state. */ var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2*L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var Buf_size = 16; /* size of bit buffer in bi_buf */ /* =========================================================================== * Constants */ var MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ var END_BLOCK = 256; /* end of block literal code */ var REP_3_6 = 16; /* repeat previous bit length 3-6 times (2 bits of repeat count) */ var REPZ_3_10 = 17; /* repeat a zero length 3-10 times (3 bits of repeat count) */ var REPZ_11_138 = 18; /* repeat a zero length 11-138 times (7 bits of repeat count) */ var extra_lbits = /* extra bits for each length code */ [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]; var extra_dbits = /* extra bits for each distance code */ [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]; var extra_blbits = /* extra bits for each bit length code */ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; var bl_order = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ // We pre-fill arrays with 0 to avoid uninitialized gaps var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 var static_ltree = new Array((L_CODES+2) * 2); zero(static_ltree); /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ var static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ var _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ var _length_code = new Array(MAX_MATCH-MIN_MATCH+1); zero(_length_code); /* length code for each normalized match length (0 == MIN_MATCH) */ var base_length = new Array(LENGTH_CODES); zero(base_length); /* First normalized length for each code (0 = MIN_MATCH) */ var base_dist = new Array(D_CODES); zero(base_dist); /* First normalized distance for each code (0 = distance of 1) */ var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) { this.static_tree = static_tree; /* static tree or NULL */ this.extra_bits = extra_bits; /* extra bits for each code or NULL */ this.extra_base = extra_base; /* base index for extra_bits */ this.elems = elems; /* max number of elements in the tree */ this.max_length = max_length; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects this.has_stree = static_tree && static_tree.length; }; var static_l_desc; var static_d_desc; var static_bl_desc; var TreeDesc = function(dyn_tree, stat_desc) { this.dyn_tree = dyn_tree; /* the dynamic tree */ this.max_code = 0; /* largest code with non zero frequency */ this.stat_desc = stat_desc; /* the corresponding static tree */ }; function d_code(dist) { return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; } /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ function put_short (s, w) { // put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += length; } } function send_code(s, c, tree) { send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ function bi_reverse(code, len) { var res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ function bi_flush(s) { if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; s.bi_valid = 0; } else if (s.bi_valid >= 8) { s.pending_buf[s.pending++] = s.bi_buf & 0xff; s.bi_buf >>= 8; s.bi_valid -= 8; } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ function gen_bitlen(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var max_code = desc.max_code; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var extra = desc.stat_desc.extra_bits; var base = desc.stat_desc.extra_base; var max_length = desc.stat_desc.max_length; var h; /* heap index */ var n, m; /* iterate over the tree elements */ var bits; /* bit length */ var xbits; /* extra bits */ var f; /* frequency */ var overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; } /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */ for (h = s.heap_max+1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n*2 + 1]/*.Len*/ = bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) { continue; } /* not a leaf node */ s.bl_count[bits]++; xbits = 0; if (n >= base) { xbits = extra[n-base]; } f = tree[n * 2]/*.Freq*/; s.opt_len += f * (bits + xbits); if (has_stree) { s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits); } } if (overflow === 0) { return; } // Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length-1; while (s.bl_count[bits] === 0) { bits--; } s.bl_count[bits]--; /* move one leaf down the tree */ s.bl_count[bits+1] += 2; /* move one overflow item as its brother */ s.bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > max_code) { continue; } if (tree[m*2 + 1]/*.Len*/ !== bits) { // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/; tree[m*2 + 1]/*.Len*/ = bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */ // int max_code; /* largest code with non zero frequency */ // ushf *bl_count; /* number of codes at each bit length */ { var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */ var code = 0; /* running code value */ var bits; /* bit index */ var n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits-1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { var len = tree[n*2 + 1]/*.Len*/; if (len === 0) { continue; } /* Now reverse the bits */ tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len); //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Initialize the various 'constant' tables. */ function tr_static_init() { var n; /* iterates over tree elements */ var bits; /* bit counter */ var length; /* length value */ var code; /* code value */ var dist; /* distance index */ var bl_count = new Array(MAX_BITS+1); /* number of codes at each bit length for an optimal tree */ // do check in _tr_init() //if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ /*#ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif*/ /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES-1; code++) { base_length[code] = length; for (n = 0; n < (1<<extra_lbits[code]); n++) { _length_code[length++] = code; } } //Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length-1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0 ; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1<<extra_dbits[code]); n++) { _dist_code[dist++] = code; } } //Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for (; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { _dist_code[256 + dist++] = code; } } //Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } n = 0; while (n <= 143) { static_ltree[n*2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } while (n <= 255) { static_ltree[n*2 + 1]/*.Len*/ = 9; n++; bl_count[9]++; } while (n <= 279) { static_ltree[n*2 + 1]/*.Len*/ = 7; n++; bl_count[7]++; } while (n <= 287) { static_ltree[n*2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes(static_ltree, L_CODES+1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n*2 + 1]/*.Len*/ = 5; static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5); } // Now data ready and we can init static trees static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS); static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); //static_init_done = true; } /* =========================================================================== * Initialize a new block. */ function init_block(s) { var n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; } for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; } for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; } s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1; s.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ function bi_windup(s) { if (s.bi_valid > 8) { put_short(s, s.bi_buf); } else if (s.bi_valid > 0) { //put_byte(s, (Byte)s->bi_buf); s.pending_buf[s.pending++] = s.bi_buf; } s.bi_buf = 0; s.bi_valid = 0; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ function copy_block(s, buf, len, header) //DeflateState *s; //charf *buf; /* the input data */ //unsigned len; /* its length */ //int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ if (header) { put_short(s, len); put_short(s, ~len); } // while (len--) { // put_byte(s, *buf++); // } utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); s.pending += len; } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ function smaller(tree, n, m, depth) { var _n2 = n*2; var _m2 = m*2; return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); } /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ function pqdownheap(s, tree, k) // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { var v = s.heap[k]; var j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if (j < s.heap_len && smaller(tree, s.heap[j+1], s.heap[j], s.depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s.heap[j], s.depth)) { break; } /* Exchange v with the smallest son */ s.heap[k] = s.heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s.heap[k] = v; } // inlined manually // var SMALLEST = 1; /* =========================================================================== * Send the block data compressed using the given Huffman trees */ function compress_block(s, ltree, dtree) // deflate_state *s; // const ct_data *ltree; /* literal tree */ // const ct_data *dtree; /* distance tree */ { var dist; /* distance of matched string */ var lc; /* match length or unmatched char (if dist == 0) */ var lx = 0; /* running index in l_buf */ var code; /* the code to send */ var extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]); lc = s.pending_buf[s.l_buf + lx]; lx++; if (dist === 0) { send_code(s, lc, ltree); /* send a literal byte */ //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code+LITERALS+1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra !== 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); //Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra !== 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, // "pendingBuf overflow"); } while (lx < s.last_lit); } send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ function build_tree(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var elems = desc.stat_desc.elems; var n, m; /* iterate over heap elements */ var max_code = -1; /* largest code with non zero frequency */ var node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2]/*.Freq*/ !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n*2 + 1]/*.Len*/ = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2]/*.Freq*/ = 1; s.depth[node] = 0; s.opt_len--; if (has_stree) { s.static_len -= stree[node*2 + 1]/*.Len*/; } /* node is 0 or 1 so it does not have extra bits */ } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { //pqremove(s, tree, n); /* n = node of least frequency */ /*** pqremove ***/ n = s.heap[1/*SMALLEST*/]; s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; pqdownheap(s, tree, 1/*SMALLEST*/); /***/ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ s.heap[--s.heap_max] = m; /* Create a new node father of n and m */ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node; /* and insert the new node in the heap */ s.heap[1/*SMALLEST*/] = node++; pqdownheap(s, tree, 1/*SMALLEST*/); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, desc); /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ function scan_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n+1)*2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { s.bl_tree[curlen * 2]/*.Freq*/ += count; } else if (curlen !== 0) { if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } s.bl_tree[REP_3_6*2]/*.Freq*/++; } else if (count <= 10) { s.bl_tree[REPZ_3_10*2]/*.Freq*/++; } else { s.bl_tree[REPZ_11_138*2]/*.Freq*/++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ function send_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n+1)*2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen !== prevlen) { send_code(s, curlen, s.bl_tree); count--; } //Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s.bl_tree); send_bits(s, count-3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s.bl_tree); send_bits(s, count-3, 3); } else { send_code(s, REPZ_11_138, s.bl_tree); send_bits(s, count-11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ function build_bl_tree(s) { var max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_dtree, s.d_desc.max_code); /* Build the bit length tree: */ build_tree(s, s.bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) { break; } } /* Update opt_len to include the bit length tree and counts */ s.opt_len += 3*(max_blindex+1) + 5+5+4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ function send_all_trees(s, lcodes, dcodes, blcodes) // deflate_state *s; // int lcodes, dcodes, blcodes; /* number of codes for each tree */ { var rank; /* index in bl_order */ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); //Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes-1, 5); send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3); } //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ function detect_data_type(s) { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ var black_mask = 0xf3ffc07f; var n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>>= 1) { if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) { return Z_BINARY; } } /* Check for textual ("white-listed") bytes. */ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { return Z_TEXT; } for (n = 32; n < LITERALS; n++) { if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { return Z_TEXT; } } /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } var static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ function _tr_init(s) { if (!static_init_done) { tr_static_init(); static_init_done = true; } s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); s.bi_buf = 0; s.bi_valid = 0; /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Send a stored block */ function _tr_stored_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */ copy_block(s, buf, stored_len, true); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ function _tr_align(s) { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ function _tr_flush_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block, or NULL if too old */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ var max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s.level > 0) { /* Check if the file is binary or text */ if (s.strm.data_type === Z_UNKNOWN) { s.strm.data_type = detect_data_type(s); } /* Construct the literal and distance trees */ build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s.opt_len+3+7) >>> 3; static_lenb = (s.static_len+3+7) >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, // s->last_lit)); if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } } else { // Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } if ((stored_len+4 <= opt_lenb) && (buf !== -1)) { /* 4: two words for the lengths */ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3); compress_block(s, static_ltree, static_dtree); } else { send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3); send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1); compress_block(s, s.dyn_ltree, s.dyn_dtree); } // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); } // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ function _tr_tally(s, dist, lc) // deflate_state *s; // unsigned dist; /* distance of matched string */ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { //var out_length, in_length, dcode; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; s.last_lit++; if (dist === 0) { /* lc is the unmatched char */ s.dyn_ltree[lc*2]/*.Freq*/++; } else { s.matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ //Assert((ush)dist < (ush)MAX_DIST(s) && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++; s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef TRUNCATE_BLOCK // /* Try to guess if it is profitable to stop the current block here */ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { // /* Compute an upper bound for the compressed length */ // out_length = s.last_lit*8; // in_length = s.strstart - s.block_start; // // for (dcode = 0; dcode < D_CODES; dcode++) { // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); // } // out_length >>>= 3; // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", // // s->last_lit, in_length, out_length, // // 100L - out_length*100L/in_length)); // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { // return true; // } // } //#endif return (s.last_lit === s.lit_bufsize-1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } exports._tr_init = _tr_init; exports._tr_stored_block = _tr_stored_block; exports._tr_flush_block = _tr_flush_block; exports._tr_tally = _tr_tally; exports._tr_align = _tr_align; },{"../utils/common":81}],93:[function(_dereq_,module,exports){ 'use strict'; function ZStream() { /* next input byte */ this.input = null; // JS specific, because we have no pointers this.next_in = 0; /* number of bytes available at input */ this.avail_in = 0; /* total number of input bytes read so far */ this.total_in = 0; /* next output byte should be put there */ this.output = null; // JS specific, because we have no pointers this.next_out = 0; /* remaining free space at output */ this.avail_out = 0; /* total number of bytes output so far */ this.total_out = 0; /* last error message, NULL if no error */ this.msg = ''/*Z_NULL*/; /* not visible by applications */ this.state = null; /* best guess about the data type: binary or text */ this.data_type = 2/*Z_UNKNOWN*/; /* adler32 value of the uncompressed data */ this.adler = 0; } module.exports = ZStream; },{}]},{},[1]);
client/containers/Post/index.js
abinavseelan/restobook
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import cn from 'classnames'; import styles from './index.scss'; import PostItem from '../../components/PostItem'; import Comment from '../../components/Comment'; import CommentCreator from '../../components/Creator'; import { updateNewCommentText, createNewComment, fetchPost, fetchComments, fetchReplies, updateNewReply, createNewReply, } from '../../actions/postActions'; class PostContainer extends Component { constructor(args) { super(args); this.handleCommentCreatorInputChange = this.handleCommentCreatorInputChange.bind(this); this.handleCreateComment = this.handleCreateComment.bind(this); this.handleReplyRequest = this.handleReplyRequest.bind(this); this.updateNewReply = this.updateNewReply.bind(this); this.createNewReply = this.createNewReply.bind(this); } componentWillMount() { const { post_id: postId } = this.props.match.params; this.props.dispatch(fetchPost(postId)); this.props.dispatch(fetchComments(postId)); } handleCommentCreatorInputChange(event) { if (event.target.name === 'comment') { this.props.dispatch(updateNewCommentText(event.target.value)); } } handleCreateComment(event) { const { post_id: postId } = this.props.match.params; event.preventDefault(); this.props.dispatch(createNewComment(postId)); } handleReplyRequest(commentId, event) { event.preventDefault(); this.props.dispatch(fetchReplies(commentId)); } updateNewReply(commentId, event) { if (event && event.target && event.target.value) { this.props.dispatch(updateNewReply(commentId, event.target.value)); } } createNewReply(commentId, text, event) { event.preventDefault(); this.props.dispatch(createNewReply(commentId, text)); } render() { const { post } = this.props.post; return ( <div className={styles.container}> <Link to="/" className={cn('mtb20 back')}>{'Go Back'}</Link> <div>{this.props.post.error}</div> <PostItem key={post.id} username={post.username} createdAt={post.created_at} text={post.text} /> <div className={styles.comments}> { this.props.post.comments .map(({ username, _id: id, created_at: createdAt, text, replies, newReplyText, replies_count: count, }) => ( <Comment key={id} id={id} count={count} username={username} createdAt={createdAt} text={text} handleReplyRequest={this.handleReplyRequest} replies={replies} newReplyText={newReplyText} updateNewReply={this.updateNewReply} createNewReply={this.createNewReply} /> )) } <div className={cn('mtb20')}> <CommentCreator name={'comment'} placeholder={'Comment on this thread'} btnText={'Comment'} handleInputChange={this.handleCommentCreatorInputChange} createHandler={this.handleCreateComment} value={this.props.post.newCommentText} /> </div> </div> </div> ); } } const mapStateToProps = state => ({ post: state.Post, }); export default connect(mapStateToProps)(PostContainer);
docs/pages/Tabs/index.js
collegepulse/material-react-components
import Grid, {GridItem} from '../../../src/Grid'; import Page from '../Page'; import Paper from '../../../src/Paper'; import React from 'react'; import SelectField from '../../../src/SelectField'; import Tabs, {Tab} from '../../../src/Tabs'; import TextField from '../../../src/TextField'; import Typography from '../../../src/Typography'; import Variables from '../../../src/variables'; class TabsDocs extends React.Component { constructor(props) { super(props); this.onControlPanel = this.onControlPanel.bind(this); this.onChange = this.onChange.bind(this); this.state = { barColor: Variables.$primary, indicatorColor: Variables.$accent, textColor: '#FFF', type: 'fixed', index: 0, tabsBaseline: 0, tabsFullWidth: 0, tabsScrollable: 0, tabsCentered: 0 }; } onControlPanel(key, value) { this.setState({[key]: value}); } onChange(e, index, key) { this.setState({ [key]: index }); } render() { return ( <Page componentName="Tabs" buildYourOwn={ <Tabs barColor={this.state.barColor} indicatorColor={this.state.indicatorColor} textColor={this.state.textColor} index={this.state.index} type={this.state.type} onChange={(e, index) => (this.onChange(e, index, 'index'))} style={{width: '100%'}} > <Tab label="Tab #0" /> <Tab label="Tab #1" /> <Tab label="Tab #2" /> </Tabs> } buildYourOwnControlPanel={[ <TextField onChange={e => (this.onControlPanel('barColor', e.target.value))} label="barColor" value={this.state.barColor} />, <TextField onChange={e => (this.onControlPanel('indicatorColor', e.target.value))} label="indicatorColor" value={this.state.indicatorColor} />, <TextField onChange={e => (this.onControlPanel('textColor', e.target.value))} label="textColor" value={this.state.textColor} />, <TextField type="number" onChange={e => (this.onControlPanel('index', Number(e.target.value)))} label="index" value={String(this.state.index)} />, <SelectField label="type" value={this.state.type} onChange={(e) => (this.onControlPanel('type', e.target.value))} > <option key="1" value="fixed">fixed</option> <option key="2" value="scrollable">scrollable</option> <option key="3" value="centered">centered</option> </SelectField> ]} examples={ <Grid gutter={16}> <GridItem xs={12}> <Typography component="p"> <Typography component="span" type="body2">Fixed </Typography> tabs (default) have equal width. </Typography> <Paper elevation={3}> <Tabs index={this.state.tabsBaseline} onChange={(e, index) => (this.onChange(e, index, 'tabsBaseline'))} > <Tab label="Tab #0" /> <Tab label="Tab #1" /> <Tab label="Tab #2" /> </Tabs> <div style={{padding: '10px'}}> Tab example with default styles. The tab index is {this.state.tabsBaseline}. </div> </Paper> </GridItem> <GridItem xs={12}> <Typography component="p"> <Typography component="span" type="body2">Scrollable </Typography> tabs have independently calculated widths. </Typography> <Paper elevation={3}> <Tabs index={this.state.tabsFullWidth} onChange={(e, index) => (this.onChange(e, index, 'tabsFullWidth'))} type="scrollable" > <Tab label="Tab #0" /> <Tab label="Tab #1" /> <Tab label="Tab #2" /> </Tabs> <div style={{padding: '10px'}}> Tab example with default styles. The tab index is {this.state.tabsFullWidth}. </div> </Paper> </GridItem> <GridItem xs={12} style={{maxWidth: '100%'}}> <Typography component="p"> <Typography component="span" type="body2">Scrollable </Typography> tabs have independently calculated widths. Overflow is visible upon scrolling. </Typography> <Paper elevation={3}> <Tabs barColor={'#f5f5f5'} indicatorColor={Variables.$orange700} textColor={'rgba(0, 0, 0, 0.54)'} index={this.state.tabsScrollable} onChange={(e, index) => (this.onChange(e, index, 'tabsScrollable'))} type="scrollable" > <Tab label="Tab #0 has a very wide label" /> <Tab label="Tab #1 is shorter" /> <Tab label="Tab #2 has a much, much, much, wider label" /> <Tab label="Tab #3 is a tab that is quite long" /> <Tab label="Tab #4 is yet another long tab" /> <Tab label="Tab #5 has some content" /> <Tab label="Tab #6 also has content" /> <Tab label="Tab #7" /> <Tab label="Tab #8" /> <Tab label="Tab #9" /> </Tabs> <div style={{padding: '10px'}}> These tabs use a custom bar color, ink bar color, and text color. The tab index is {this.state.tabsScrollable}. </div> </Paper> </GridItem> <GridItem xs={12}> <Typography component="p"> <Typography component="span" type="body2">Centered </Typography> tabs. </Typography> <Paper elevation={3}> <Tabs barColor={'#f5f5f5'} indicatorColor={Variables.$orange700} textColor={'rgba(0, 0, 0, 0.54)'} index={this.state.tabsCentered} onChange={(e, index) => (this.onChange(e, index, 'tabsCentered'))} type="centered" > <Tab label="Tab #0" /> <Tab label="Tab #1" /> <Tab label="Tab #2" /> </Tabs> <div style={{padding: '10px'}}> These tabs use a custom bar color, ink bar color, and text color. The tab index is {this.state.tabsCentered}. </div> </Paper> </GridItem> </Grid> } /> ); } } export default TabsDocs;
packages/flow-runtime-docs/src/components/InstallInstruction.js
codemix/flow-runtime
/* @flow */ import React, { Component } from 'react'; import {observable, computed} from 'mobx'; import {observer} from 'mobx-react'; type Props = { devPackageNames?: string[]; packageNames?: string[]; }; @observer export default class InstallInstruction extends Component<Props, void> { @observable showYarn: boolean = false; @computed get installCode (): string { const {devPackageNames, packageNames} = this.props; const output = []; if (this.showYarn) { if (packageNames) { output.push(...packageNames.map(name => `yarn add ${name}`)); } if (devPackageNames) { output.push(...devPackageNames.map(name => `yarn add --dev ${name}`)); } } else { if (packageNames) { output.push(...packageNames.map(name => `npm install ${name}`)); } if (devPackageNames) { output.push(...devPackageNames.map(name => `npm install --dev ${name}`)); } } return output.join('\n'); } handleClickNpm = (e: SyntheticMouseEvent) => { e.preventDefault(); this.showYarn = false; }; handleClickYarn = (e: SyntheticMouseEvent) => { e.preventDefault(); this.showYarn = true; }; render() { return ( <div> <p className="lead"> Install with {' '} {this.showYarn ? <a href="#" onClick={this.handleClickNpm}>npm</a> : 'npm'} {' or '} {this.showYarn ? 'yarn' : <a href="#" onClick={this.handleClickYarn}>yarn</a>}.</p> <pre>{this.installCode}</pre> </div> ); } }
components/__tests__/CodeSnippet-test.js
hellobrian/carbon-components-react
import React from 'react'; import CodeSnippet from '../CodeSnippet'; import { mount, shallow } from 'enzyme'; describe('Code Snippet', () => { describe('Renders as expected', () => { const snippet = shallow( <CodeSnippet className="some-class" type="terminal"> {'node -v'} </CodeSnippet>, ); it('should use the appropriate snippet class', () => { expect(snippet.hasClass('bx--snippet')).toEqual(true); expect(snippet.hasClass('bx--snippet--terminal')).toEqual(true); }); it('should render children as expected', () => { expect(snippet.find('.bx--snippet-container').length).toBe(1); }); it('should all for custom classes to be applied', () => { expect(snippet.hasClass('some-class')).toEqual(true); }); }); it('should expose a `ref` to the content through `wrappedContentRef`', () => { let mockRef; const wrappedContentRef = jest.fn(el => (mockRef = el)); const content = 'node -v'; mount( <CodeSnippet type="terminal" wrappedContentRef={wrappedContentRef}> {content} </CodeSnippet> ); expect(mockRef.textContent).toBe(content); expect(wrappedContentRef).toHaveBeenCalledTimes(1); }); });
src/index.js
cpojer/hextrapolate
/** * Copyright 2003-present Greg Hurrell. All rights reserved. * Licensed under the terms of the MIT license. * * @flow */ 'use strict'; import React from 'react'; import App from './App'; React.render(<App />, document.getElementById('root'));
docs/src/app/components/pages/components/TextField/ExampleSimple.js
ArcanisCz/material-ui
import React from 'react'; import TextField from 'material-ui/TextField'; const TextFieldExampleSimple = () => ( <div> <TextField hintText="Hint Text" /><br /> <br /> <TextField hintText="The hint text can be as long as you want, it will wrap." /><br /> <TextField id="text-field-default" defaultValue="Default Value" /><br /> <TextField hintText="Hint Text" floatingLabelText="Floating Label Text" /><br /> <TextField defaultValue="Default Value" floatingLabelText="Floating Label Text" /><br /> <TextField hintText="Hint Text" floatingLabelText="Fixed Floating Label Text" floatingLabelFixed={true} /><br /> <TextField hintText="Password Field" floatingLabelText="Password" type="password" /><br /> <TextField hintText="MultiLine with rows: 2 and rowsMax: 4" multiLine={true} rows={2} rowsMax={4} /><br /> <TextField hintText="Message Field" floatingLabelText="MultiLine and FloatingLabel" multiLine={true} rows={2} /><br /> <TextField hintText="Full width" fullWidth={true} /> </div> ); export default TextFieldExampleSimple;
webpack/scenes/ModuleStreams/ModuleStreamsTable.js
adamruzicka/katello
import React from 'react'; import PropTypes from 'prop-types'; import { translate as __ } from 'foremanReact/common/I18n'; import { Table } from '../../move_to_foreman/components/common/table'; import TableSchema from './ModuleStreamsTableSchema'; import { LoadingState } from '../../move_to_pf/LoadingState'; const ModuleStreamsTable = ({ moduleStreams, onPaginationChange }) => { const { loading, results, pagination, itemCount, } = moduleStreams; const emptyStateData = { header: __('No Module Streams found'), }; return ( <LoadingState loading={!results || loading} loadingText={__('Loading')} > <Table columns={TableSchema} rows={results} pagination={pagination} onPaginationChange={onPaginationChange} itemCount={itemCount} emptyState={emptyStateData} /> </LoadingState> ); }; ModuleStreamsTable.propTypes = { moduleStreams: PropTypes.shape({ loading: PropTypes.bool, results: PropTypes.array, pagination: PropTypes.shape({}), itemCount: PropTypes.number, }).isRequired, onPaginationChange: PropTypes.func.isRequired, }; export default ModuleStreamsTable;
admin-ui/src/views/appstore/Apps/AppsList.js
sbender9/signalk-server-node
import React from 'react' import { Button } from 'reactstrap' export default props => ( <ul className='icons-list'> {props.apps.map(app => ( <li key={app.name}> {mainIcon(app)} <div className='desc'> <a href={app.npmUrl}> <i className='icon-info' /> </a> <div className='title'> <b>{app.name}</b> </div> <small> {app.description} by {app.author} </small> </div> <div className='value'> <div className='small text-muted'>Version</div> <strong> {app.installedVersion || app.version} {app.installedVersion && app.version != app.installedVersion && ' \u27a1 ' + app.version} </strong> </div> <div className='actions'> {(!app.installedVersion || app.version != app.installedVersion) && ( <Button color='link' className='text-muted' onClick={installApp.bind(this, app.name, app.version)} > <i className='icon-cloud-download' /> </Button> )} </div> </li> ))} </ul> ) function mainIcon (app) { return ( <span> {app.isWebapp && <i className='icon-grid bg-primary' />} {app.isPlugin && <i className='icon-settings bg-success' />} </span> ) } function installApp (name, version) { fetch(`/appstore/install/${name}/${version}`, { method: 'POST', credentials: 'include' }) }
node_modules/semantic-ui-react/src/elements/Container/Container.js
SuperUncleCat/ServerMonitoring
import cx from 'classnames' import PropTypes from 'prop-types' import React from 'react' import { customPropTypes, getElementType, getUnhandledProps, META, SUI, useKeyOnly, useTextAlignProp, } from '../../lib' /** * A container limits content to a maximum width. */ function Container(props) { const { children, className, fluid, text, textAlign, } = props const classes = cx( 'ui', useKeyOnly(text, 'text'), useKeyOnly(fluid, 'fluid'), useTextAlignProp(textAlign), 'container', className, ) const rest = getUnhandledProps(Container, props) const ElementType = getElementType(Container, props) return <ElementType {...rest} className={classes}>{children}</ElementType> } Container._meta = { name: 'Container', type: META.TYPES.ELEMENT, } Container.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Container has no maximum width. */ fluid: PropTypes.bool, /** Reduce maximum width to more naturally accommodate text. */ text: PropTypes.bool, /** Align container text. */ textAlign: PropTypes.oneOf(SUI.TEXT_ALIGNMENTS), } export default Container
src/index.js
Software-Eng-THU-2015/pacific-rim
import React from 'react'; import ReactDOM from 'react-dom'; import { browserHistory, Router, Route, Link } from 'react-router'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import App from './App'; import Stats from './Home/Stats'; import About from './About'; import TagWrapper from './Tag/TagWrapper'; import Plan from './Plan/Plan'; import History from './history/history'; import Tree from './Tree/Tree' import Page from './Page'; import SparkLines from './Home/SparkLines'; const history = createBrowserHistory(); ReactDOM.render(( <Router history={history}> <Router path='/' component={App}> <Router path='about' component={About} /> <Router path='user/:id/chart' component={SparkLines} /> <Router path='user/:id/page' component={Page} /> <Router path='user/:id/stat' component={Stats} /> <Router path='user/:id/tag' component={TagWrapper} /> <Router path='user/:id/plan' component={Plan} /> <Router path='user/:id/tree' component={Tree} /> <Router path='user/:id/history' component={History} /> </Router> </Router> ), document.getElementById('root'));
ajax/libs/jquery-ui-bootstrap/0.5pre/js/jquery-1.8.3.min.js
js-data/cdnjs
/*! jQuery v1.8.3 jquery.com | jquery.org/license */ (function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r<i;r++)v.event.add(t,n,u[n][r])}o.data&&(o.data=v.extend({},o.data))}function Ot(e,t){var n;if(t.nodeType!==1)return;t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),n==="object"?(t.parentNode&&(t.outerHTML=e.outerHTML),v.support.html5Clone&&e.innerHTML&&!v.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):n==="input"&&Et.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):n==="option"?t.selected=e.defaultSelected:n==="input"||n==="textarea"?t.defaultValue=e.defaultValue:n==="script"&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(v.expando)}function Mt(e){return typeof e.getElementsByTagName!="undefined"?e.getElementsByTagName("*"):typeof e.querySelectorAll!="undefined"?e.querySelectorAll("*"):[]}function _t(e){Et.test(e.type)&&(e.defaultChecked=e.checked)}function Qt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Jt.length;while(i--){t=Jt[i]+n;if(t in e)return t}return r}function Gt(e,t){return e=t||e,v.css(e,"display")==="none"||!v.contains(e.ownerDocument,e)}function Yt(e,t){var n,r,i=[],s=0,o=e.length;for(;s<o;s++){n=e[s];if(!n.style)continue;i[s]=v._data(n,"olddisplay"),t?(!i[s]&&n.style.display==="none"&&(n.style.display=""),n.style.display===""&&Gt(n)&&(i[s]=v._data(n,"olddisplay",nn(n.nodeName)))):(r=Dt(n,"display"),!i[s]&&r!=="none"&&v._data(n,"olddisplay",r))}for(s=0;s<o;s++){n=e[s];if(!n.style)continue;if(!t||n.style.display==="none"||n.style.display==="")n.style.display=t?i[s]||"":"none"}return e}function Zt(e,t,n){var r=Rt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function en(e,t,n,r){var i=n===(r?"border":"content")?4:t==="width"?1:0,s=0;for(;i<4;i+=2)n==="margin"&&(s+=v.css(e,n+$t[i],!0)),r?(n==="content"&&(s-=parseFloat(Dt(e,"padding"+$t[i]))||0),n!=="margin"&&(s-=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0)):(s+=parseFloat(Dt(e,"padding"+$t[i]))||0,n!=="padding"&&(s+=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0));return s}function tn(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=!0,s=v.support.boxSizing&&v.css(e,"boxSizing")==="border-box";if(r<=0||r==null){r=Dt(e,t);if(r<0||r==null)r=e.style[t];if(Ut.test(r))return r;i=s&&(v.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+en(e,t,n||(s?"border":"content"),i)+"px"}function nn(e){if(Wt[e])return Wt[e];var t=v("<"+e+">").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write("<!doctype html><html><body>"),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u<a;u++)r=o[u],s=/^\+/.test(r),s&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[s?"unshift":"push"](n)}}function kn(e,n,r,i,s,o){s=s||n.dataTypes[0],o=o||{},o[s]=!0;var u,a=e[s],f=0,l=a?a.length:0,c=e===Sn;for(;f<l&&(c||!u);f++)u=a[f](n,r,i),typeof u=="string"&&(!c||o[u]?u=t:(n.dataTypes.unshift(u),u=kn(e,n,r,i,u,o)));return(c||!u)&&!o["*"]&&(u=kn(e,n,r,i,"*",o)),u}function Ln(e,n){var r,i,s=v.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((s[r]?e:i||(i={}))[r]=n[r]);i&&v.extend(!0,e,i)}function An(e,n,r){var i,s,o,u,a=e.contents,f=e.dataTypes,l=e.responseFields;for(s in l)s in r&&(n[l[s]]=r[s]);while(f[0]==="*")f.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(s in a)if(a[s]&&a[s].test(i)){f.unshift(s);break}if(f[0]in r)o=f[0];else{for(s in r){if(!f[0]||e.converters[s+" "+f[0]]){o=s;break}u||(u=s)}o=o||u}if(o)return o!==f[0]&&f.unshift(o),r[o]}function On(e,t){var n,r,i,s,o=e.dataTypes.slice(),u=o[0],a={},f=0;e.dataFilter&&(t=e.dataFilter(t,e.dataType));if(o[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=o[++f];)if(i!=="*"){if(u!=="*"&&u!==i){n=a[u+" "+i]||a["* "+i];if(!n)for(r in a){s=r.split(" ");if(s[1]===i){n=a[u+" "+s[0]]||a["* "+s[0]];if(n){n===!0?n=a[r]:a[r]!==!0&&(i=s[0],o.splice(f--,0,i));break}}}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(l){return{state:"parsererror",error:n?l:"No conversion from "+u+" to "+i}}}u=i}return{state:"success",data:t}}function Fn(){try{return new e.XMLHttpRequest}catch(t){}}function In(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function $n(){return setTimeout(function(){qn=t},0),qn=v.now()}function Jn(e,t){v.each(t,function(t,n){var r=(Vn[t]||[]).concat(Vn["*"]),i=0,s=r.length;for(;i<s;i++)if(r[i].call(e,t,n))return})}function Kn(e,t,n){var r,i=0,s=0,o=Xn.length,u=v.Deferred().always(function(){delete a.elem}),a=function(){var t=qn||$n(),n=Math.max(0,f.startTime+f.duration-t),r=n/f.duration||0,i=1-r,s=0,o=f.tweens.length;for(;s<o;s++)f.tweens[s].run(i);return u.notifyWith(e,[f,i,n]),i<1&&o?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:v.extend({},t),opts:v.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:qn||$n(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=v.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(i),i},stop:function(t){var n=0,r=t?f.tweens.length:0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;Qn(l,f.opts.specialEasing);for(;i<o;i++){r=Xn[i].call(f,e,l,f.opts);if(r)return r}return Jn(f,l),v.isFunction(f.opts.start)&&f.opts.start.call(e,f),v.fx.timer(v.extend(a,{anim:f,queue:f.opts.queue,elem:e})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function Qn(e,t){var n,r,i,s,o;for(n in e){r=v.camelCase(n),i=t[r],s=e[n],v.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=v.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function Gn(e,t,n){var r,i,s,o,u,a,f,l,c,h=this,p=e.style,d={},m=[],g=e.nodeType&&Gt(e);n.queue||(l=v._queueHooks(e,"fx"),l.unqueued==null&&(l.unqueued=0,c=l.empty.fire,l.empty.fire=function(){l.unqueued||c()}),l.unqueued++,h.always(function(){h.always(function(){l.unqueued--,v.queue(e,"fx").length||l.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],v.css(e,"display")==="inline"&&v.css(e,"float")==="none"&&(!v.support.inlineBlockNeedsLayout||nn(e.nodeName)==="inline"?p.display="inline-block":p.zoom=1)),n.overflow&&(p.overflow="hidden",v.support.shrinkWrapBlocks||h.done(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t){s=t[r];if(Un.exec(s)){delete t[r],a=a||s==="toggle";if(s===(g?"hide":"show"))continue;m.push(r)}}o=m.length;if(o){u=v._data(e,"fxshow")||v._data(e,"fxshow",{}),"hidden"in u&&(g=u.hidden),a&&(u.hidden=!g),g?v(e).show():h.done(function(){v(e).hide()}),h.done(function(){var t;v.removeData(e,"fxshow",!0);for(t in d)v.style(e,t,d[t])});for(r=0;r<o;r++)i=m[r],f=h.createTween(i,g?u[i]:0),d[i]=u[i]||v.style(e,i),i in u||(u[i]=f.start,g&&(f.end=f.start,f.start=i==="width"||i==="height"?1:0))}}function Yn(e,t,n,r,i){return new Yn.prototype.init(e,t,n,r,i)}function Zn(e,t){var n,r={height:e},i=0;t=t?1:0;for(;i<4;i+=2-t)n=$t[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function tr(e){return v.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:!1}var n,r,i=e.document,s=e.location,o=e.navigator,u=e.jQuery,a=e.$,f=Array.prototype.push,l=Array.prototype.slice,c=Array.prototype.indexOf,h=Object.prototype.toString,p=Object.prototype.hasOwnProperty,d=String.prototype.trim,v=function(e,t){return new v.fn.init(e,t,n)},m=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,g=/\S/,y=/\s+/,b=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,w=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a<f;a++)if((e=arguments[a])!=null)for(n in e){r=u[n],i=e[n];if(u===i)continue;l&&i&&(v.isPlainObject(i)||(s=v.isArray(i)))?(s?(s=!1,o=r&&v.isArray(r)?r:[]):o=r&&v.isPlainObject(r)?r:{},u[n]=v.extend(l,o,i)):i!==t&&(u[n]=i)}return u},v.extend({noConflict:function(t){return e.$===v&&(e.$=a),t&&e.jQuery===v&&(e.jQuery=u),v},isReady:!1,readyWait:1,holdReady:function(e){e?v.readyWait++:v.ready(!0)},ready:function(e){if(e===!0?--v.readyWait:v.isReady)return;if(!i.body)return setTimeout(v.ready,1);v.isReady=!0;if(e!==!0&&--v.readyWait>0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s<o;)if(n.apply(e[s++],r)===!1)break}else if(u){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;s<o;)if(n.call(e[s],s,e[s++])===!1)break;return e},trim:d&&!d.call("\ufeff\u00a0")?function(e){return e==null?"":d.call(e)}:function(e){return e==null?"":(e+"").replace(b,"")},makeArray:function(e,t){var n,r=t||[];return e!=null&&(n=v.type(e),e.length==null||n==="string"||n==="function"||n==="regexp"||v.isWindow(e)?f.call(r,e):v.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(c)return c.call(t,e,n);r=t.length,n=n?n<0?Math.max(0,r+n):n:0;for(;n<r;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,s=0;if(typeof r=="number")for(;s<r;s++)e[i++]=n[s];else while(n[s]!==t)e[i++]=n[s++];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length;n=!!n;for(;s<o;s++)r=!!t(e[s],s),n!==r&&i.push(e[s]);return i},map:function(e,n,r){var i,s,o=[],u=0,a=e.length,f=e instanceof v||a!==t&&typeof a=="number"&&(a>0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u<a;u++)i=n(e[u],u,r),i!=null&&(o[o.length]=i);else for(s in e)i=n(e[s],s,r),i!=null&&(o[o.length]=i);return o.concat.apply([],o)},guid:1,proxy:function(e,n){var r,i,s;return typeof n=="string"&&(r=e[n],n=e,e=r),v.isFunction(e)?(i=l.call(arguments,2),s=function(){return e.apply(n,i.concat(l.call(arguments)))},s.guid=e.guid=e.guid||v.guid++,s):t},access:function(e,n,r,i,s,o,u){var a,f=r==null,l=0,c=e.length;if(r&&typeof r=="object"){for(l in r)v.access(e,n,l,r[l],1,o,i);s=1}else if(i!==t){a=u===t&&v.isFunction(i),f&&(a?(a=n,n=function(e,t,n){return a.call(v(e),n)}):(n.call(e,i),n=null));if(n)for(;l<c;l++)n(e[l],r,a?i.call(e[l],l,n(e[l],r)):i,u);s=1}return s?e:f?n.call(e):c?n(e[0],r):o},now:function(){return(new Date).getTime()}}),v.ready.promise=function(t){if(!r){r=v.Deferred();if(i.readyState==="complete")setTimeout(v.ready,1);else if(i.addEventListener)i.addEventListener("DOMContentLoaded",A,!1),e.addEventListener("load",v.ready,!1);else{i.attachEvent("onreadystatechange",A),e.attachEvent("onload",v.ready);var n=!1;try{n=e.frameElement==null&&i.documentElement}catch(s){}n&&n.doScroll&&function o(){if(!v.isReady){try{n.doScroll("left")}catch(e){return setTimeout(o,50)}v.ready()}}()}}return r.promise(t)},v.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){O["[object "+t+"]"]=t.toLowerCase()}),n=v(i);var M={};v.Callbacks=function(e){e=typeof e=="string"?M[e]||_(e):v.extend({},e);var n,r,i,s,o,u,a=[],f=!e.once&&[],l=function(t){n=e.memory&&t,r=!0,u=s||0,s=0,o=a.length,i=!0;for(;a&&u<o;u++)if(a[u].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}i=!1,a&&(f?f.length&&l(f.shift()):n?a=[]:c.disable())},c={add:function(){if(a){var t=a.length;(function r(t){v.each(t,function(t,n){var i=v.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this},remove:function(){return a&&v.each(arguments,function(e,t){var n;while((n=v.inArray(t,a,n))>-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&v.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}}),v.support=function(){var t,n,r,s,o,u,a,f,l,c,h,p=i.createElement("div");p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i<s;i++)delete r[t[i]];if(!(n?B:v.isEmptyObject)(r))return}}if(!n){delete u[a].data;if(!B(u[a]))return}o?v.cleanData([e],!0):v.support.deleteExpando||u!=u.window?delete u[a]:u[a]=null},_data:function(e,t,n){return v.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&v.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),v.fn.extend({data:function(e,n){var r,i,s,o,u,a=this[0],f=0,l=null;if(e===t){if(this.length){l=v.data(a);if(a.nodeType===1&&!v._data(a,"parsedAttrs")){s=a.attributes;for(u=s.length;f<u;f++)o=s[f].name,o.indexOf("data-")||(o=v.camelCase(o.substring(5)),H(a,o,l[o]));v._data(a,"parsedAttrs",!0)}}return l}return typeof e=="object"?this.each(function(){v.data(this,e)}):(r=e.split(".",2),r[1]=r[1]?"."+r[1]:"",i=r[1]+"!",v.access(this,function(n){if(n===t)return l=this.triggerHandler("getData"+i,[r[0]]),l===t&&a&&(l=v.data(a,e),l=H(a,e,l)),l===t&&r[1]?this.data(r[0]):l;r[1]=n,this.each(function(){var t=v(this);t.triggerHandler("setData"+i,r),v.data(this,e,n),t.triggerHandler("changeData"+i,r)})},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length<r?v.queue(this[0],e):n===t?this:this.each(function(){var t=v.queue(this,e,n);v._queueHooks(this,e),e==="fx"&&t[0]!=="inprogress"&&v.dequeue(this,e)})},dequeue:function(e){return this.each(function(){v.dequeue(this,e)})},delay:function(e,t){return e=v.fx?v.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,s=v.Deferred(),o=this,u=this.length,a=function(){--i||s.resolveWith(o,[o])};typeof e!="string"&&(n=e,e=t),e=e||"fx";while(u--)r=v._data(o[u],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(a));return a(),s.promise(n)}});var j,F,I,q=/[\t\r\n]/g,R=/\r/g,U=/^(?:button|input)$/i,z=/^(?:button|input|object|select|textarea)$/i,W=/^a(?:rea|)$/i,X=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,V=v.support.getSetAttribute;v.fn.extend({attr:function(e,t){return v.access(this,v.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n<r;n++){i=this[n];if(i.nodeType===1)if(!i.className&&t.length===1)i.className=e;else{s=" "+i.className+" ";for(o=0,u=t.length;o<u;o++)s.indexOf(" "+t[o]+" ")<0&&(s+=t[o]+" ");i.className=v.trim(s)}}}return this},removeClass:function(e){var n,r,i,s,o,u,a;if(v.isFunction(e))return this.each(function(t){v(this).removeClass(e.call(this,t,this.className))});if(e&&typeof e=="string"||e===t){n=(e||"").split(y);for(u=0,a=this.length;u<a;u++){i=this[u];if(i.nodeType===1&&i.className){r=(" "+i.className+" ").replace(q," ");for(s=0,o=n.length;s<o;s++)while(r.indexOf(" "+n[s]+" ")>=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(q," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a<u;a++){n=r[a];if((n.selected||a===i)&&(v.support.optDisabled?!n.disabled:n.getAttribute("disabled")===null)&&(!n.parentNode.disabled||!v.nodeName(n.parentNode,"optgroup"))){t=v(n).val();if(s)return t;o.push(t)}}return o},set:function(e,t){var n=v.makeArray(t);return v(e).find("option").each(function(){this.selected=v.inArray(v(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o<r.length;o++)i=r[o],i&&(n=v.propFix[i]||i,s=X.test(i),s||v.attr(e,i,""),e.removeAttribute(V?i:n),s&&n in e&&(e[n]=!1))}},attrHooks:{type:{set:function(e,t){if(U.test(e.nodeName)&&e.parentNode)v.error("type property can't be changed");else if(!v.support.radioValue&&t==="radio"&&v.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return j&&v.nodeName(e,"button")?j.get(e,t):t in e?e.value:null},set:function(e,t,n){if(j&&v.nodeName(e,"button"))return j.set(e,t,n);e.value=t}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,s,o,u=e.nodeType;if(!e||u===3||u===8||u===2)return;return o=u!==1||!v.isXMLDoc(e),o&&(n=v.propFix[n]||n,s=v.propHooks[n]),r!==t?s&&"set"in s&&(i=s.set(e,r,n))!==t?i:e[n]=r:s&&"get"in s&&(i=s.get(e,n))!==null?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):z.test(e.nodeName)||W.test(e.nodeName)&&e.href?0:t}}}}),F={get:function(e,n){var r,i=v.prop(e,n);return i===!0||typeof i!="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?v.removeAttr(e,n):(r=v.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},V||(I={name:!0,id:!0,coords:!0},j=v.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(I[n]?r.value!=="":r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=i.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},v.each(["width","height"],function(e,t){v.attrHooks[t]=v.extend(v.attrHooks[t],{set:function(e,n){if(n==="")return e.setAttribute(t,"auto"),n}})}),v.attrHooks.contenteditable={get:j.get,set:function(e,t,n){t===""&&(t="false"),j.set(e,t,n)}}),v.support.hrefNormalized||v.each(["href","src","width","height"],function(e,n){v.attrHooks[n]=v.extend(v.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})}),v.support.style||(v.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=t+""}}),v.support.optSelected||(v.propHooks.selected=v.extend(v.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),v.support.enctype||(v.propFix.enctype="encoding"),v.support.checkOn||v.each(["radio","checkbox"],function(){v.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}}),v.each(["radio","checkbox"],function(){v.valHooks[this]=v.extend(v.valHooks[this],{set:function(e,t){if(v.isArray(t))return e.checked=v.inArray(v(e).val(),t)>=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f<n.length;f++){l=J.exec(n[f])||[],c=l[1],h=(l[2]||"").split(".").sort(),g=v.event.special[c]||{},c=(s?g.delegateType:g.bindType)||c,g=v.event.special[c]||{},p=v.extend({type:c,origType:l[1],data:i,handler:r,guid:r.guid,selector:s,needsContext:s&&v.expr.match.needsContext.test(s),namespace:h.join(".")},d),m=a[c];if(!m){m=a[c]=[],m.delegateCount=0;if(!g.setup||g.setup.call(e,i,h,u)===!1)e.addEventListener?e.addEventListener(c,u,!1):e.attachEvent&&e.attachEvent("on"+c,u)}g.add&&(g.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),s?m.splice(m.delegateCount++,0,p):m.push(p),v.event.global[c]=!0}e=null},global:{},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,m,g=v.hasData(e)&&v._data(e);if(!g||!(h=g.events))return;t=v.trim(Z(t||"")).split(" ");for(s=0;s<t.length;s++){o=J.exec(t[s])||[],u=a=o[1],f=o[2];if(!u){for(u in h)v.event.remove(e,u+t[s],n,r,!0);continue}p=v.event.special[u]||{},u=(r?p.delegateType:p.bindType)||u,d=h[u]||[],l=d.length,f=f?new RegExp("(^|\\.)"+f.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(c=0;c<d.length;c++)m=d[c],(i||a===m.origType)&&(!n||n.guid===m.guid)&&(!f||f.test(m.namespace))&&(!r||r===m.selector||r==="**"&&m.selector)&&(d.splice(c--,1),m.selector&&d.delegateCount--,p.remove&&p.remove.call(e,m));d.length===0&&l!==d.length&&((!p.teardown||p.teardown.call(e,f,g.handle)===!1)&&v.removeEvent(e,u,g.handle),delete h[u])}v.isEmptyObject(h)&&(delete g.handle,v.removeData(e,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,s,o){if(!s||s.nodeType!==3&&s.nodeType!==8){var u,a,f,l,c,h,p,d,m,g,y=n.type||n,b=[];if(Y.test(y+v.event.triggered))return;y.indexOf("!")>=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f<m.length&&!n.isPropagationStopped();f++)l=m[f][0],n.type=m[f][1],d=(v._data(l,"events")||{})[n.type]&&v._data(l,"handle"),d&&d.apply(l,r),d=h&&l[h],d&&v.acceptData(l)&&d.apply&&d.apply(l,r)===!1&&n.preventDefault();return n.type=y,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(s.ownerDocument,r)===!1)&&(y!=="click"||!v.nodeName(s,"a"))&&v.acceptData(s)&&h&&s[y]&&(y!=="focus"&&y!=="blur"||n.target.offsetWidth!==0)&&!v.isWindow(s)&&(c=s[h],c&&(s[h]=null),v.event.triggered=y,s[y](),v.event.triggered=t,c&&(s[h]=c)),n.result}return},dispatch:function(n){n=v.event.fix(n||e.event);var r,i,s,o,u,a,f,c,h,p,d=(v._data(this,"events")||{})[n.type]||[],m=d.delegateCount,g=l.call(arguments),y=!n.exclusive&&!n.namespace,b=v.event.special[n.type]||{},w=[];g[0]=n,n.delegateTarget=this;if(b.preDispatch&&b.preDispatch.call(this,n)===!1)return;if(m&&(!n.button||n.type!=="click"))for(s=n.target;s!=this;s=s.parentNode||this)if(s.disabled!==!0||n.type!=="click"){u={},f=[];for(r=0;r<m;r++)c=d[r],h=c.selector,u[h]===t&&(u[h]=c.needsContext?v(h,this).index(s)>=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r<w.length&&!n.isPropagationStopped();r++){a=w[r],n.currentTarget=a.elem;for(i=0;i<a.matches.length&&!n.isImmediatePropagationStopped();i++){c=a.matches[i];if(y||!n.namespace&&!c.namespace||n.namespace_re&&n.namespace_re.test(c.namespace))n.data=c.data,n.handleObj=c,o=((v.event.special[c.origType]||{}).handle||c.handler).apply(a.elem,g),o!==t&&(n.result=o,o===!1&&(n.preventDefault(),n.stopPropagation()))}}return b.postDispatch&&b.postDispatch.call(this,n),n.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return e.which==null&&(e.which=t.charCode!=null?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,s,o,u=n.button,a=n.fromElement;return e.pageX==null&&n.clientX!=null&&(r=e.target.ownerDocument||i,s=r.documentElement,o=r.body,e.pageX=n.clientX+(s&&s.scrollLeft||o&&o.scrollLeft||0)-(s&&s.clientLeft||o&&o.clientLeft||0),e.pageY=n.clientY+(s&&s.scrollTop||o&&o.scrollTop||0)-(s&&s.clientTop||o&&o.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?n.toElement:a),!e.which&&u!==t&&(e.which=u&1?1:u&2?3:u&4?2:0),e}},fix:function(e){if(e[v.expando])return e;var t,n,r=e,s=v.event.fixHooks[e.type]||{},o=s.props?this.props.concat(s.props):this.props;e=v.Event(r);for(t=o.length;t;)n=o[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||i),e.target.nodeType===3&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){v.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=v.extend(new v.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?v.event.trigger(i,null,t):v.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},v.event.handle=v.event.dispatch,v.removeEvent=i.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]=="undefined"&&(e[r]=null),e.detachEvent(r,n))},v.Event=function(e,t){if(!(this instanceof v.Event))return new v.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?tt:et):this.type=e,t&&v.extend(this,t),this.timeStamp=e&&e.timeStamp||v.now(),this[v.expando]=!0},v.Event.prototype={preventDefault:function(){this.isDefaultPrevented=tt;var e=this.originalEvent;if(!e)return;e.preventDefault?e.preventDefault():e.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=tt;var e=this.originalEvent;if(!e)return;e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=tt,this.stopPropagation()},isDefaultPrevented:et,isPropagationStopped:et,isImmediatePropagationStopped:et},v.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){v.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj,o=s.selector;if(!i||i!==r&&!v.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),v.support.submitBubbles||(v.event.special.submit={setup:function(){if(v.nodeName(this,"form"))return!1;v.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=v.nodeName(n,"input")||v.nodeName(n,"button")?n.form:t;r&&!v._data(r,"_submit_attached")&&(v.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),v._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&v.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){if(v.nodeName(this,"form"))return!1;v.event.remove(this,"._submit")}}),v.support.changeBubbles||(v.event.special.change={setup:function(){if($.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")v.event.add(this,"propertychange._change",function(e){e.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),v.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),v.event.simulate("change",this,e,!0)});return!1}v.event.add(this,"beforeactivate._change",function(e){var t=e.target;$.test(t.nodeName)&&!v._data(t,"_change_attached")&&(v.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&v.event.simulate("change",this.parentNode,e,!0)}),v._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;if(this!==t||e.isSimulated||e.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return e.handleObj.handler.apply(this,arguments)},teardown:function(){return v.event.remove(this,"._change"),!$.test(this.nodeName)}}),v.support.focusinBubbles||v.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){v.event.simulate(t,e.target,v.event.fix(e),!0)};v.event.special[t]={setup:function(){n++===0&&i.addEventListener(e,r,!0)},teardown:function(){--n===0&&i.removeEventListener(e,r,!0)}}}),v.fn.extend({on:function(e,n,r,i,s){var o,u;if(typeof e=="object"){typeof n!="string"&&(r=r||n,n=t);for(u in e)this.on(u,n,r,e[u],s);return this}r==null&&i==null?(i=n,r=n=t):i==null&&(typeof n=="string"?(i=r,r=t):(i=r,r=n,n=t));if(i===!1)i=et;else if(!i)return this;return s===1&&(o=i,i=function(e){return v().off(e),o.apply(this,arguments)},i.guid=o.guid||(o.guid=v.guid++)),this.each(function(){v.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,s;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,v(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if(typeof e=="object"){for(s in e)this.off(s,n,e[s]);return this}if(n===!1||typeof n=="function")r=n,n=t;return r===!1&&(r=et),this.each(function(){v.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},live:function(e,t,n){return v(this.context).on(e,this.selector,t,n),this},die:function(e,t){return v(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length===1?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){v.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0])return v.event.trigger(e,t,this[0],!0)},toggle:function(e){var t=arguments,n=e.guid||v.guid++,r=0,i=function(n){var i=(v._data(this,"lastToggle"+e.guid)||0)%r;return v._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};i.guid=n;while(r<t.length)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),v.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){v.fn[t]=function(e,n){return n==null&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u<a;u++)if(s=e[u])if(!n||n(s,r,i))o.push(s),f&&t.push(u);return o}function ct(e,t,n,r,i,s){return r&&!r[d]&&(r=ct(r)),i&&!i[d]&&(i=ct(i,s)),N(function(s,o,u,a){var f,l,c,h=[],p=[],d=o.length,v=s||dt(t||"*",u.nodeType?[u]:u,[]),m=e&&(s||!t)?lt(v,h,e,u,a):v,g=n?i||(s?e:d||r)?[]:o:m;n&&n(m,g,u,a);if(r){f=lt(g,p),r(f,[],u,a),l=f.length;while(l--)if(c=f[l])g[p[l]]=!(m[p[l]]=c)}if(s){if(i||e){if(i){f=[],l=g.length;while(l--)(c=g[l])&&f.push(m[l]=c);i(null,g=[],f,a)}l=g.length;while(l--)(c=g[l])&&(f=i?T.call(s,c):h[l])>-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a<s;a++)if(n=i.relative[e[a].type])h=[at(ft(h),n)];else{n=i.filter[e[a].type].apply(null,e[a].matches);if(n[d]){r=++a;for(;r<s;r++)if(i.relative[e[r].type])break;return ct(a>1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a<r&&ht(e.slice(a,r)),r<s&&ht(e=e.slice(r)),r<s&&e.join(""))}h.push(n)}return ft(h)}function pt(e,t){var r=t.length>0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r<i;r++)nt(e,t[r],n);return n}function vt(e,t,n,r,s){var o,u,f,l,c,h=ut(e),p=h.length;if(!r&&h.length===1){u=h[0]=h[0].slice(0);if(u.length>2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;t<n;t++)if(this[t]===e)return t;return-1},N=function(e,t){return e[d]=t==null||t,e},C=function(){var e={},t=[];return N(function(n,r){return t.push(n)>i.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="<a name='"+d+"'></a><div name='"+d+"'></div>",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:st(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:st(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}},f=y.compareDocumentPosition?function(e,t){return e===t?(l=!0,0):(!e.compareDocumentPosition||!t.compareDocumentPosition?e.compareDocumentPosition:e.compareDocumentPosition(t)&4)?-1:1}:function(e,t){if(e===t)return l=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],s=[],o=e.parentNode,u=t.parentNode,a=o;if(o===u)return ot(e,t);if(!o)return-1;if(!u)return 1;while(a)i.unshift(a),a=a.parentNode;a=u;while(a)s.unshift(a),a=a.parentNode;n=i.length,r=s.length;for(var f=0;f<n&&f<r;f++)if(i[f]!==s[f])return ot(i[f],s[f]);return f===n?ot(e,s[f],-1):ot(i[f],t,1)},[0,0].sort(f),h=!l,nt.uniqueSort=function(e){var t,n=[],r=1,i=0;l=h,e.sort(f);if(l){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e},nt.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},a=nt.compile=function(e,t){var n,r=[],i=[],s=A[d][e+" "];if(!s){t||(t=ut(e)),n=t.length;while(n--)s=ht(t[n]),s[d]?r.push(s):i.push(s);s=A(e,pt(i,r))}return s},g.querySelectorAll&&function(){var e,t=vt,n=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,i=[":focus"],s=[":active"],u=y.matchesSelector||y.mozMatchesSelector||y.webkitMatchesSelector||y.oMatchesSelector||y.msMatchesSelector;K(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t<n;t++)if(v.contains(u[t],this))return!0});o=this.pushStack("","find",e);for(t=0,n=this.length;t<n;t++){r=o.length,v.find(e,this[t],o);if(t>0)for(i=r;i<o.length;i++)for(s=0;s<r;s++)if(o[s]===o[i]){o.splice(i--,1);break}}return o},has:function(e){var t,n=v(e,this),r=n.length;return this.filter(function(){for(t=0;t<r;t++)if(v.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1),"not",e)},filter:function(e){return this.pushStack(ft(this,e,!0),"filter",e)},is:function(e){return!!e&&(typeof e=="string"?st.test(e)?v(e,this.context).index(this[0])>=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r<i;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&n.nodeType!==11){if(o?o.index(n)>-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/<tbody/i,gt=/<|&#?\w+;/,yt=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,wt=new RegExp("<(?:"+ct+")[\\s/>]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Nt={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X<div>","</div>"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1></$2>");try{for(;r<i;r++)n=this[r]||{},n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(s){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return ut(this[0])?this.length?this.pushStack(v(v.isFunction(e)?e():e),"replaceWith",e):this:v.isFunction(e)?this.each(function(t){var n=v(this),r=n.html();n.replaceWith(e.call(this,t,r))}):(typeof e!="string"&&(e=v(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;v(this).remove(),t?v(t).before(e):v(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,s,o,u,a=0,f=e[0],l=[],c=this.length;if(!v.support.checkClone&&c>1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a<c;a++)r.call(n&&v.nodeName(this[a],"table")?Lt(this[a],"tbody"):this[a],a===u?o:v.clone(o,!0,!0))}o=s=null,l.length&&v.each(l,function(e,t){t.src?v.ajax?v.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):v.error("no ajax"):v.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Tt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),v.buildFragment=function(e,n,r){var s,o,u,a=e[0];return n=n||i,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,e.length===1&&typeof a=="string"&&a.length<512&&n===i&&a.charAt(0)==="<"&&!bt.test(a)&&(v.support.checkClone||!St.test(a))&&(v.support.html5Clone||!wt.test(a))&&(o=!0,s=v.fragments[a],u=s!==t),s||(s=n.createDocumentFragment(),v.clean(e,n,s,r),o&&(v.fragments[a]=u&&s)),{fragment:s,cacheable:o}},v.fragments={},v.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){v.fn[e]=function(n){var r,i=0,s=[],o=v(n),u=o.length,a=this.length===1&&this[0].parentNode;if((a==null||a&&a.nodeType===11&&a.childNodes.length===1)&&u===1)return o[t](this[0]),this;for(;i<u;i++)r=(i>0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1></$2>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]==="<table>"&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("<div>").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],Vn[n]=Vn[n]||[],Vn[n].unshift(t)},prefilter:function(e,t){t?Xn.unshift(e):Xn.push(e)}}),v.Tween=Yn,Yn.prototype={constructor:Yn,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(v.cssNumber[n]?"":"px")},cur:function(){var e=Yn.propHooks[this.prop];return e&&e.get?e.get(this):Yn.propHooks._default.get(this)},run:function(e){var t,n=Yn.propHooks[this.prop];return this.options.duration?this.pos=t=v.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Yn.propHooks._default.set(this),this}},Yn.prototype.init.prototype=Yn.prototype,Yn.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=v.css(e.elem,e.prop,!1,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){v.fx.step[e.prop]?v.fx.step[e.prop](e):e.elem.style&&(e.elem.style[v.cssProps[e.prop]]!=null||v.cssHooks[e.prop])?v.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Yn.propHooks.scrollTop=Yn.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},v.each(["toggle","show","hide"],function(e,t){var n=v.fn[t];v.fn[t]=function(r,i,s){return r==null||typeof r=="boolean"||!e&&v.isFunction(r)&&v.isFunction(i)?n.apply(this,arguments):this.animate(Zn(t,!0),r,i,s)}}),v.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Gt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=v.isEmptyObject(e),s=v.speed(t,n,r),o=function(){var t=Kn(this,v.extend({},e),s);i&&t.stop(!0)};return i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return typeof e!="string"&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=e!=null&&e+"queueHooks",s=v.timers,o=v._data(this);if(n)o[n]&&o[n].stop&&i(o[n]);else for(n in o)o[n]&&o[n].stop&&Wn.test(n)&&i(o[n]);for(n=s.length;n--;)s[n].elem===this&&(e==null||s[n].queue===e)&&(s[n].anim.stop(r),t=!1,s.splice(n,1));(t||!r)&&v.dequeue(this,e)})}}),v.each({slideDown:Zn("show"),slideUp:Zn("hide"),slideToggle:Zn("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){v.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),v.speed=function(e,t,n){var r=e&&typeof e=="object"?v.extend({},e):{complete:n||!n&&t||v.isFunction(e)&&e,duration:e,easing:n&&t||t&&!v.isFunction(t)&&t};r.duration=v.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in v.fx.speeds?v.fx.speeds[r.duration]:v.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){v.isFunction(r.old)&&r.old.call(this),r.queue&&v.dequeue(this,r.queue)},r},v.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},v.timers=[],v.fx=Yn.prototype.init,v.fx.tick=function(){var e,n=v.timers,r=0;qn=v.now();for(;r<n.length;r++)e=n[r],!e()&&n[r]===e&&n.splice(r--,1);n.length||v.fx.stop(),qn=t},v.fx.timer=function(e){e()&&v.timers.push(e)&&!Rn&&(Rn=setInterval(v.fx.tick,v.fx.interval))},v.fx.interval=13,v.fx.stop=function(){clearInterval(Rn),Rn=null},v.fx.speeds={slow:600,fast:200,_default:400},v.fx.step={},v.expr&&v.expr.filters&&(v.expr.filters.animated=function(e){return v.grep(v.timers,function(t){return e===t.elem}).length});var er=/^(?:body|html)$/i;v.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){v.offset.setOffset(this,e,t)});var n,r,i,s,o,u,a,f={top:0,left:0},l=this[0],c=l&&l.ownerDocument;if(!c)return;return(r=c.body)===l?v.offset.bodyOffset(l):(n=c.documentElement,v.contains(n,l)?(typeof l.getBoundingClientRect!="undefined"&&(f=l.getBoundingClientRect()),i=tr(c),s=n.clientTop||r.clientTop||0,o=n.clientLeft||r.clientLeft||0,u=i.pageYOffset||n.scrollTop,a=i.pageXOffset||n.scrollLeft,{top:f.top+u-s,left:f.left+a-o}):f)},v.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return v.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(v.css(e,"marginTop"))||0,n+=parseFloat(v.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=v.css(e,"position");r==="static"&&(e.style.position="relative");var i=v(e),s=i.offset(),o=v.css(e,"top"),u=v.css(e,"left"),a=(r==="absolute"||r==="fixed")&&v.inArray("auto",[o,u])>-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window);
react/features/e2ee/components/E2EELabel.js
bgrozev/jitsi-meet
// @flow import Tooltip from '@atlaskit/tooltip'; import React, { Component } from 'react'; import { translate } from '../../base/i18n'; import { Icon, IconE2EE } from '../../base/icons'; import { CircularLabel } from '../../base/label'; import { connect } from '../../base/redux'; import { _mapStateToProps, type Props } from './AbstractE2EELabel'; /** * React {@code Component} for displaying a label when everyone has E2EE enabled in a conferene. * * @extends Component */ class E2EELabel extends Component<Props> { /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { if (!this.props._showLabel) { return null; } // eslint-disable-next-line react/jsx-max-props-per-line const icon = <Icon size = { 22 } src = { IconE2EE } />; return ( <Tooltip content = { this.props.t('e2ee.labelToolTip') } position = { 'left' }> <CircularLabel className = 'e2ee' label = { icon } /> </Tooltip> ); } } export default translate(connect(_mapStateToProps)(E2EELabel));
react-ebay-network-aware-code-splitting/src/index.js
GoogleChromeLabs/adaptive-loading
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
examples/auth-with-shared-root/components/Login.js
brenoc/react-router
import React from 'react' import { History } from 'react-router' import auth from '../utils/auth.js' const Login = React.createClass({ mixins: [ History ], getInitialState() { return { error: false } }, handleSubmit(event) { event.preventDefault() const email = this.refs.email.value const pass = this.refs.pass.value auth.login(email, pass, (loggedIn) => { if (!loggedIn) return this.setState({ error: true }) const { location } = this.props if (location.state && location.state.nextPathname) { this.history.replaceState(null, location.state.nextPathname) } else { this.history.replaceState(null, '/') } }) }, render() { return ( <form onSubmit={this.handleSubmit}> <label><input ref="email" placeholder="email" defaultValue="[email protected]" /></label> <label><input ref="pass" placeholder="password" /></label> (hint: password1)<br /> <button type="submit">login</button> {this.state.error && ( <p>Bad login information</p> )} </form> ) } }) export default Login
ajax/libs/onsen/1.3.7/js/onsenui.min.js
dada0423/cdnjs
/*! onsenui - v1.3.7 - 2015-07-27 */ !function(){function getAttributes(element){return Node_get_attributes.call(element)}function setAttribute(element,attribute,value){try{Element_setAttribute.call(element,attribute,value)}catch(e){}}function removeAttribute(element,attribute){Element_removeAttribute.call(element,attribute)}function childNodes(element){return Node_get_childNodes.call(element)}function empty(element){for(;element.childNodes.length;)element.removeChild(element.lastChild)}function insertAdjacentHTML(element,position,html){HTMLElement_insertAdjacentHTMLPropertyDescriptor.value.call(element,position,html)}function inUnsafeMode(){var isUnsafe=!0;try{detectionDiv.innerHTML="<test/>"}catch(ex){isUnsafe=!1}return isUnsafe}function cleanse(html,targetElement){function cleanseAttributes(element){var attributes=getAttributes(element);if(attributes&&attributes.length){for(var events,i=0,len=attributes.length;len>i;i++){var attribute=attributes[i],name=attribute.name;"o"!==name[0]&&"O"!==name[0]||"n"!==name[1]&&"N"!==name[1]||(events=events||[],events.push({name:attribute.name,value:attribute.value}))}if(events)for(var i=0,len=events.length;len>i;i++){var attribute=events[i];removeAttribute(element,attribute.name),setAttribute(element,"x-"+attribute.name,attribute.value)}}for(var children=childNodes(element),i=0,len=children.length;len>i;i++)cleanseAttributes(children[i])}var cleaner=document.implementation.createHTMLDocument("cleaner");empty(cleaner.documentElement),MSApp.execUnsafeLocalFunction(function(){insertAdjacentHTML(cleaner.documentElement,"afterbegin",html)});var scripts=cleaner.documentElement.querySelectorAll("script");Array.prototype.forEach.call(scripts,function(script){switch(script.type.toLowerCase()){case"":script.type="text/inert";break;case"text/javascript":case"text/ecmascript":case"text/x-javascript":case"text/jscript":case"text/livescript":case"text/javascript1.1":case"text/javascript1.2":case"text/javascript1.3":script.type="text/inert-"+script.type.slice("text/".length);break;case"application/javascript":case"application/ecmascript":case"application/x-javascript":script.type="application/inert-"+script.type.slice("application/".length)}}),cleanseAttributes(cleaner.documentElement);var cleanedNodes=[];return"HTML"===targetElement.tagName?cleanedNodes=Array.prototype.slice.call(document.adoptNode(cleaner.documentElement).childNodes):(cleaner.head&&(cleanedNodes=cleanedNodes.concat(Array.prototype.slice.call(document.adoptNode(cleaner.head).childNodes))),cleaner.body&&(cleanedNodes=cleanedNodes.concat(Array.prototype.slice.call(document.adoptNode(cleaner.body).childNodes)))),cleanedNodes}function cleansePropertySetter(property,setter){var propertyDescriptor=Object.getOwnPropertyDescriptor(HTMLElement.prototype,property),originalSetter=propertyDescriptor.set;Object.defineProperty(HTMLElement.prototype,property,{get:propertyDescriptor.get,set:function(value){if(window.WinJS&&window.WinJS._execUnsafe&&inUnsafeMode())originalSetter.call(this,value);else{var that=this,nodes=cleanse(value,that);MSApp.execUnsafeLocalFunction(function(){setter(propertyDescriptor,that,nodes)})}},enumerable:propertyDescriptor.enumerable,configurable:propertyDescriptor.configurable})}if(window.MSApp&&MSApp.execUnsafeLocalFunction){var Element_setAttribute=Object.getOwnPropertyDescriptor(Element.prototype,"setAttribute").value,Element_removeAttribute=Object.getOwnPropertyDescriptor(Element.prototype,"removeAttribute").value,HTMLElement_insertAdjacentHTMLPropertyDescriptor=Object.getOwnPropertyDescriptor(HTMLElement.prototype,"insertAdjacentHTML"),Node_get_attributes=Object.getOwnPropertyDescriptor(Node.prototype,"attributes").get,Node_get_childNodes=Object.getOwnPropertyDescriptor(Node.prototype,"childNodes").get,detectionDiv=document.createElement("div");cleansePropertySetter("innerHTML",function(propertyDescriptor,target,elements){empty(target);for(var i=0,len=elements.length;len>i;i++)target.appendChild(elements[i])}),cleansePropertySetter("outerHTML",function(propertyDescriptor,target,elements){for(var i=0,len=elements.length;len>i;i++)target.insertAdjacentElement("afterend",elements[i]);target.parentNode.removeChild(target)})}}(),function(){var initializing=!1,fnTest=/xyz/.test(function(){xyz})?/\b_super\b/:/.*/;this.Class=function(){},Class.extend=function(prop){function Class(){!initializing&&this.init&&this.init.apply(this,arguments)}var _super=this.prototype;initializing=!0;var prototype=new this;initializing=!1;for(var name in prop)prototype[name]="function"==typeof prop[name]&&"function"==typeof _super[name]&&fnTest.test(prop[name])?function(name,fn){return function(){var tmp=this._super;this._super=_super[name];var ret=fn.apply(this,arguments);return this._super=tmp,ret}}(name,prop[name]):prop[name];return Class.prototype=prototype,Class.prototype.constructor=Class,Class.extend=arguments.callee,Class}}(),function(){"use strict";function FastClick(layer,options){function bind(method,context){return function(){return method.apply(context,arguments)}}var oldOnClick;if(options=options||{},this.trackingClick=!1,this.trackingClickStart=0,this.targetElement=null,this.touchStartX=0,this.touchStartY=0,this.lastTouchIdentifier=0,this.touchBoundary=options.touchBoundary||10,this.layer=layer,this.tapDelay=options.tapDelay||200,this.tapTimeout=options.tapTimeout||700,!FastClick.notNeeded(layer)){for(var methods=["onMouse","onClick","onTouchStart","onTouchMove","onTouchEnd","onTouchCancel"],context=this,i=0,l=methods.length;l>i;i++)context[methods[i]]=bind(context[methods[i]],context);deviceIsAndroid&&(layer.addEventListener("mouseover",this.onMouse,!0),layer.addEventListener("mousedown",this.onMouse,!0),layer.addEventListener("mouseup",this.onMouse,!0)),layer.addEventListener("click",this.onClick,!0),layer.addEventListener("touchstart",this.onTouchStart,!1),layer.addEventListener("touchmove",this.onTouchMove,!1),layer.addEventListener("touchend",this.onTouchEnd,!1),layer.addEventListener("touchcancel",this.onTouchCancel,!1),Event.prototype.stopImmediatePropagation||(layer.removeEventListener=function(type,callback,capture){var rmv=Node.prototype.removeEventListener;"click"===type?rmv.call(layer,type,callback.hijacked||callback,capture):rmv.call(layer,type,callback,capture)},layer.addEventListener=function(type,callback,capture){var adv=Node.prototype.addEventListener;"click"===type?adv.call(layer,type,callback.hijacked||(callback.hijacked=function(event){event.propagationStopped||callback(event)}),capture):adv.call(layer,type,callback,capture)}),"function"==typeof layer.onclick&&(oldOnClick=layer.onclick,layer.addEventListener("click",function(event){oldOnClick(event)},!1),layer.onclick=null)}}var deviceIsWindowsPhone=navigator.userAgent.indexOf("Windows Phone")>=0,deviceIsAndroid=navigator.userAgent.indexOf("Android")>0&&!deviceIsWindowsPhone,deviceIsIOS=/iP(ad|hone|od)/.test(navigator.userAgent)&&!deviceIsWindowsPhone,deviceIsIOS4=deviceIsIOS&&/OS 4_\d(_\d)?/.test(navigator.userAgent),deviceIsIOSWithBadTarget=deviceIsIOS&&/OS [6-7]_\d/.test(navigator.userAgent),deviceIsBlackBerry10=navigator.userAgent.indexOf("BB10")>0;FastClick.prototype.needsClick=function(target){switch(target.nodeName.toLowerCase()){case"button":case"select":case"textarea":if(target.disabled)return!0;break;case"input":if(deviceIsIOS&&"file"===target.type||target.disabled)return!0;break;case"label":case"iframe":case"video":return!0}return/\bneedsclick\b/.test(target.className)},FastClick.prototype.needsFocus=function(target){switch(target.nodeName.toLowerCase()){case"textarea":return!0;case"select":return!deviceIsAndroid;case"input":switch(target.type){case"button":case"checkbox":case"file":case"image":case"radio":case"submit":return!1}return!target.disabled&&!target.readOnly;default:return/\bneedsfocus\b/.test(target.className)}},FastClick.prototype.sendClick=function(targetElement,event){var clickEvent,touch;document.activeElement&&document.activeElement!==targetElement&&document.activeElement.blur(),touch=event.changedTouches[0],clickEvent=document.createEvent("MouseEvents"),clickEvent.initMouseEvent(this.determineEventType(targetElement),!0,!0,window,1,touch.screenX,touch.screenY,touch.clientX,touch.clientY,!1,!1,!1,!1,0,null),clickEvent.forwardedTouchEvent=!0,targetElement.dispatchEvent(clickEvent)},FastClick.prototype.determineEventType=function(targetElement){return deviceIsAndroid&&"select"===targetElement.tagName.toLowerCase()?"mousedown":"click"},FastClick.prototype.focus=function(targetElement){var length;deviceIsIOS&&targetElement.setSelectionRange&&0!==targetElement.type.indexOf("date")&&"time"!==targetElement.type&&"month"!==targetElement.type?(length=targetElement.value.length,targetElement.setSelectionRange(length,length)):targetElement.focus()},FastClick.prototype.updateScrollParent=function(targetElement){var scrollParent,parentElement;if(scrollParent=targetElement.fastClickScrollParent,!scrollParent||!scrollParent.contains(targetElement)){parentElement=targetElement;do{if(parentElement.scrollHeight>parentElement.offsetHeight){scrollParent=parentElement,targetElement.fastClickScrollParent=parentElement;break}parentElement=parentElement.parentElement}while(parentElement)}scrollParent&&(scrollParent.fastClickLastScrollTop=scrollParent.scrollTop)},FastClick.prototype.getTargetElementFromEventTarget=function(eventTarget){return eventTarget.nodeType===Node.TEXT_NODE?eventTarget.parentNode:eventTarget},FastClick.prototype.onTouchStart=function(event){var targetElement,touch,selection;if(event.targetTouches.length>1)return!0;if(targetElement=this.getTargetElementFromEventTarget(event.target),touch=event.targetTouches[0],deviceIsIOS){if(selection=window.getSelection(),selection.rangeCount&&!selection.isCollapsed)return!0;if(!deviceIsIOS4){if(touch.identifier&&touch.identifier===this.lastTouchIdentifier)return event.preventDefault(),!1;this.lastTouchIdentifier=touch.identifier,this.updateScrollParent(targetElement)}}return this.trackingClick=!0,this.trackingClickStart=event.timeStamp,this.targetElement=targetElement,this.touchStartX=touch.pageX,this.touchStartY=touch.pageY,event.timeStamp-this.lastClickTime<this.tapDelay&&event.preventDefault(),!0},FastClick.prototype.touchHasMoved=function(event){var touch=event.changedTouches[0],boundary=this.touchBoundary;return Math.abs(touch.pageX-this.touchStartX)>boundary||Math.abs(touch.pageY-this.touchStartY)>boundary?!0:!1},FastClick.prototype.onTouchMove=function(event){return this.trackingClick?((this.targetElement!==this.getTargetElementFromEventTarget(event.target)||this.touchHasMoved(event))&&(this.trackingClick=!1,this.targetElement=null),!0):!0},FastClick.prototype.findControl=function(labelElement){return void 0!==labelElement.control?labelElement.control:labelElement.htmlFor?document.getElementById(labelElement.htmlFor):labelElement.querySelector("button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea")},FastClick.prototype.onTouchEnd=function(event){var forElement,trackingClickStart,targetTagName,scrollParent,touch,targetElement=this.targetElement;if(!this.trackingClick)return!0;if(event.timeStamp-this.lastClickTime<this.tapDelay)return this.cancelNextClick=!0,!0;if(event.timeStamp-this.trackingClickStart>this.tapTimeout)return!0;if(this.cancelNextClick=!1,this.lastClickTime=event.timeStamp,trackingClickStart=this.trackingClickStart,this.trackingClick=!1,this.trackingClickStart=0,deviceIsIOSWithBadTarget&&(touch=event.changedTouches[0],targetElement=document.elementFromPoint(touch.pageX-window.pageXOffset,touch.pageY-window.pageYOffset)||targetElement,targetElement.fastClickScrollParent=this.targetElement.fastClickScrollParent),targetTagName=targetElement.tagName.toLowerCase(),"label"===targetTagName){if(forElement=this.findControl(targetElement)){if(this.focus(targetElement),deviceIsAndroid)return!1;targetElement=forElement}}else if(this.needsFocus(targetElement))return event.timeStamp-trackingClickStart>100||deviceIsIOS&&window.top!==window&&"input"===targetTagName?(this.targetElement=null,!1):(this.focus(targetElement),this.sendClick(targetElement,event),deviceIsIOS&&"select"===targetTagName||(this.targetElement=null,event.preventDefault()),!1);return deviceIsIOS&&!deviceIsIOS4&&(scrollParent=targetElement.fastClickScrollParent,scrollParent&&scrollParent.fastClickLastScrollTop!==scrollParent.scrollTop)?!0:(this.needsClick(targetElement)||(event.preventDefault(),this.sendClick(targetElement,event)),!1)},FastClick.prototype.onTouchCancel=function(){this.trackingClick=!1,this.targetElement=null},FastClick.prototype.onMouse=function(event){return this.targetElement?event.forwardedTouchEvent?!0:event.cancelable&&(!this.needsClick(this.targetElement)||this.cancelNextClick)?(event.stopImmediatePropagation?event.stopImmediatePropagation():event.propagationStopped=!0,event.stopPropagation(),event.preventDefault(),!1):!0:!0},FastClick.prototype.onClick=function(event){var permitted;return this.trackingClick?(this.targetElement=null,this.trackingClick=!1,!0):"submit"===event.target.type&&0===event.detail?!0:(permitted=this.onMouse(event),permitted||(this.targetElement=null),permitted)},FastClick.prototype.destroy=function(){var layer=this.layer;deviceIsAndroid&&(layer.removeEventListener("mouseover",this.onMouse,!0),layer.removeEventListener("mousedown",this.onMouse,!0),layer.removeEventListener("mouseup",this.onMouse,!0)),layer.removeEventListener("click",this.onClick,!0),layer.removeEventListener("touchstart",this.onTouchStart,!1),layer.removeEventListener("touchmove",this.onTouchMove,!1),layer.removeEventListener("touchend",this.onTouchEnd,!1),layer.removeEventListener("touchcancel",this.onTouchCancel,!1)},FastClick.notNeeded=function(layer){var metaViewport,chromeVersion,blackberryVersion,firefoxVersion;if("undefined"==typeof window.ontouchstart)return!0;if(chromeVersion=+(/Chrome\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1]){if(!deviceIsAndroid)return!0;if(metaViewport=document.querySelector("meta[name=viewport]")){if(-1!==metaViewport.content.indexOf("user-scalable=no"))return!0;if(chromeVersion>31&&document.documentElement.scrollWidth<=window.outerWidth)return!0}}if(deviceIsBlackBerry10&&(blackberryVersion=navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/),blackberryVersion[1]>=10&&blackberryVersion[2]>=3&&(metaViewport=document.querySelector("meta[name=viewport]")))){if(-1!==metaViewport.content.indexOf("user-scalable=no"))return!0;if(document.documentElement.scrollWidth<=window.outerWidth)return!0}return"none"===layer.style.msTouchAction||"manipulation"===layer.style.touchAction?!0:(firefoxVersion=+(/Firefox\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1],firefoxVersion>=27&&(metaViewport=document.querySelector("meta[name=viewport]"),metaViewport&&(-1!==metaViewport.content.indexOf("user-scalable=no")||document.documentElement.scrollWidth<=window.outerWidth))?!0:"none"===layer.style.touchAction||"manipulation"===layer.style.touchAction?!0:!1)},FastClick.attach=function(layer,options){return new FastClick(layer,options)},"function"==typeof define&&"object"==typeof define.amd&&define.amd?define(function(){return FastClick}):"undefined"!=typeof module&&module.exports?(module.exports=FastClick.attach,module.exports.FastClick=FastClick):window.FastClick=FastClick}(),function(window,undefined){"use strict";function setup(){Hammer.READY||(Event.determineEventTypes(),Utils.each(Hammer.gestures,function(gesture){Detection.register(gesture)}),Event.onTouch(Hammer.DOCUMENT,EVENT_MOVE,Detection.detect),Event.onTouch(Hammer.DOCUMENT,EVENT_END,Detection.detect),Hammer.READY=!0)}var Hammer=function Hammer(element,options){return new Hammer.Instance(element,options||{})};Hammer.VERSION="1.1.3",Hammer.defaults={behavior:{userSelect:"none",touchAction:"pan-y",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}},Hammer.DOCUMENT=document,Hammer.HAS_POINTEREVENTS=navigator.pointerEnabled||navigator.msPointerEnabled,Hammer.HAS_TOUCHEVENTS="ontouchstart"in window,Hammer.IS_MOBILE=/mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent),Hammer.NO_MOUSEEVENTS=Hammer.HAS_TOUCHEVENTS&&Hammer.IS_MOBILE||Hammer.HAS_POINTEREVENTS,Hammer.CALCULATE_INTERVAL=25;var EVENT_TYPES={},DIRECTION_DOWN=Hammer.DIRECTION_DOWN="down",DIRECTION_LEFT=Hammer.DIRECTION_LEFT="left",DIRECTION_UP=Hammer.DIRECTION_UP="up",DIRECTION_RIGHT=Hammer.DIRECTION_RIGHT="right",POINTER_MOUSE=Hammer.POINTER_MOUSE="mouse",POINTER_TOUCH=Hammer.POINTER_TOUCH="touch",POINTER_PEN=Hammer.POINTER_PEN="pen",EVENT_START=Hammer.EVENT_START="start",EVENT_MOVE=Hammer.EVENT_MOVE="move",EVENT_END=Hammer.EVENT_END="end",EVENT_RELEASE=Hammer.EVENT_RELEASE="release",EVENT_TOUCH=Hammer.EVENT_TOUCH="touch";Hammer.READY=!1,Hammer.plugins=Hammer.plugins||{},Hammer.gestures=Hammer.gestures||{};var Utils=Hammer.utils={extend:function(dest,src,merge){for(var key in src)!src.hasOwnProperty(key)||dest[key]!==undefined&&merge||(dest[key]=src[key]);return dest},on:function(element,type,handler){element.addEventListener(type,handler,!1)},off:function(element,type,handler){element.removeEventListener(type,handler,!1)},each:function(obj,iterator,context){var i,len;if("forEach"in obj)obj.forEach(iterator,context);else if(obj.length!==undefined){for(i=0,len=obj.length;len>i;i++)if(iterator.call(context,obj[i],i,obj)===!1)return}else for(i in obj)if(obj.hasOwnProperty(i)&&iterator.call(context,obj[i],i,obj)===!1)return},inStr:function(src,find){return src.indexOf(find)>-1},inArray:function(src,find){if(src.indexOf){var index=src.indexOf(find);return-1===index?!1:index}for(var i=0,len=src.length;len>i;i++)if(src[i]===find)return i;return!1},toArray:function(obj){return Array.prototype.slice.call(obj,0)},hasParent:function(node,parent){for(;node;){if(node==parent)return!0;node=node.parentNode}return!1},getCenter:function(touches){var pageX=[],pageY=[],clientX=[],clientY=[],min=Math.min,max=Math.max;return 1===touches.length?{pageX:touches[0].pageX,pageY:touches[0].pageY,clientX:touches[0].clientX,clientY:touches[0].clientY}:(Utils.each(touches,function(touch){pageX.push(touch.pageX),pageY.push(touch.pageY),clientX.push(touch.clientX),clientY.push(touch.clientY)}),{pageX:(min.apply(Math,pageX)+max.apply(Math,pageX))/2,pageY:(min.apply(Math,pageY)+max.apply(Math,pageY))/2,clientX:(min.apply(Math,clientX)+max.apply(Math,clientX))/2,clientY:(min.apply(Math,clientY)+max.apply(Math,clientY))/2})},getVelocity:function(deltaTime,deltaX,deltaY){return{x:Math.abs(deltaX/deltaTime)||0,y:Math.abs(deltaY/deltaTime)||0}},getAngle:function(touch1,touch2){var x=touch2.clientX-touch1.clientX,y=touch2.clientY-touch1.clientY;return 180*Math.atan2(y,x)/Math.PI},getDirection:function(touch1,touch2){var x=Math.abs(touch1.clientX-touch2.clientX),y=Math.abs(touch1.clientY-touch2.clientY);return x>=y?touch1.clientX-touch2.clientX>0?DIRECTION_LEFT:DIRECTION_RIGHT:touch1.clientY-touch2.clientY>0?DIRECTION_UP:DIRECTION_DOWN},getDistance:function(touch1,touch2){var x=touch2.clientX-touch1.clientX,y=touch2.clientY-touch1.clientY;return Math.sqrt(x*x+y*y)},getScale:function(start,end){return start.length>=2&&end.length>=2?this.getDistance(end[0],end[1])/this.getDistance(start[0],start[1]):1},getRotation:function(start,end){return start.length>=2&&end.length>=2?this.getAngle(end[1],end[0])-this.getAngle(start[1],start[0]):0},isVertical:function(direction){return direction==DIRECTION_UP||direction==DIRECTION_DOWN},setPrefixedCss:function(element,prop,value,toggle){var prefixes=["","Webkit","Moz","O","ms"];prop=Utils.toCamelCase(prop);for(var i=0;i<prefixes.length;i++){var p=prop;if(prefixes[i]&&(p=prefixes[i]+p.slice(0,1).toUpperCase()+p.slice(1)),p in element.style){element.style[p]=(null==toggle||toggle)&&value||"";break}}},toggleBehavior:function(element,props,toggle){if(props&&element&&element.style){Utils.each(props,function(value,prop){Utils.setPrefixedCss(element,prop,value,toggle)});var falseFn=toggle&&function(){return!1};"none"==props.userSelect&&(element.onselectstart=falseFn),"none"==props.userDrag&&(element.ondragstart=falseFn)}},toCamelCase:function(str){return str.replace(/[_-]([a-z])/g,function(s){return s[1].toUpperCase()})}},Event=Hammer.event={preventMouseEvents:!1,started:!1,shouldDetect:!1,on:function(element,type,handler,hook){var types=type.split(" ");Utils.each(types,function(type){Utils.on(element,type,handler),hook&&hook(type)})},off:function(element,type,handler,hook){var types=type.split(" ");Utils.each(types,function(type){Utils.off(element,type,handler),hook&&hook(type)})},onTouch:function(element,eventType,handler){var self=this,onTouchHandler=function(ev){var triggerType,srcType=ev.type.toLowerCase(),isPointer=Hammer.HAS_POINTEREVENTS,isMouse=Utils.inStr(srcType,"mouse");isMouse&&self.preventMouseEvents||(isMouse&&eventType==EVENT_START&&0===ev.button?(self.preventMouseEvents=!1,self.shouldDetect=!0):isPointer&&eventType==EVENT_START?self.shouldDetect=1===ev.buttons||PointerEvent.matchType(POINTER_TOUCH,ev):isMouse||eventType!=EVENT_START||(self.preventMouseEvents=!0,self.shouldDetect=!0),isPointer&&eventType!=EVENT_END&&PointerEvent.updatePointer(eventType,ev),self.shouldDetect&&(triggerType=self.doDetect.call(self,ev,eventType,element,handler)),triggerType==EVENT_END&&(self.preventMouseEvents=!1,self.shouldDetect=!1,PointerEvent.reset()),isPointer&&eventType==EVENT_END&&PointerEvent.updatePointer(eventType,ev))};return this.on(element,EVENT_TYPES[eventType],onTouchHandler),onTouchHandler},doDetect:function(ev,eventType,element,handler){var touchList=this.getTouchList(ev,eventType),touchListLength=touchList.length,triggerType=eventType,triggerChange=touchList.trigger,changedLength=touchListLength;eventType==EVENT_START?triggerChange=EVENT_TOUCH:eventType==EVENT_END&&(triggerChange=EVENT_RELEASE,changedLength=touchList.length-(ev.changedTouches?ev.changedTouches.length:1)),changedLength>0&&this.started&&(triggerType=EVENT_MOVE),this.started=!0;var evData=this.collectEventData(element,triggerType,touchList,ev);return eventType!=EVENT_END&&handler.call(Detection,evData),triggerChange&&(evData.changedLength=changedLength,evData.eventType=triggerChange,handler.call(Detection,evData),evData.eventType=triggerType,delete evData.changedLength),triggerType==EVENT_END&&(handler.call(Detection,evData),this.started=!1),triggerType},determineEventTypes:function(){var types;return types=Hammer.HAS_POINTEREVENTS?window.PointerEvent?["pointerdown","pointermove","pointerup pointercancel lostpointercapture"]:["MSPointerDown","MSPointerMove","MSPointerUp MSPointerCancel MSLostPointerCapture"]:Hammer.NO_MOUSEEVENTS?["touchstart","touchmove","touchend touchcancel"]:["touchstart mousedown","touchmove mousemove","touchend touchcancel mouseup"],EVENT_TYPES[EVENT_START]=types[0],EVENT_TYPES[EVENT_MOVE]=types[1],EVENT_TYPES[EVENT_END]=types[2],EVENT_TYPES},getTouchList:function(ev,eventType){if(Hammer.HAS_POINTEREVENTS)return PointerEvent.getTouchList();if(ev.touches){if(eventType==EVENT_MOVE)return ev.touches;var identifiers=[],concat=[].concat(Utils.toArray(ev.touches),Utils.toArray(ev.changedTouches)),touchList=[];return Utils.each(concat,function(touch){Utils.inArray(identifiers,touch.identifier)===!1&&touchList.push(touch),identifiers.push(touch.identifier)}),touchList}return ev.identifier=1,[ev]},collectEventData:function(element,eventType,touches,ev){var pointerType=POINTER_TOUCH;return Utils.inStr(ev.type,"mouse")||PointerEvent.matchType(POINTER_MOUSE,ev)?pointerType=POINTER_MOUSE:PointerEvent.matchType(POINTER_PEN,ev)&&(pointerType=POINTER_PEN),{center:Utils.getCenter(touches),timeStamp:Date.now(),target:ev.target,touches:touches,eventType:eventType,pointerType:pointerType,srcEvent:ev,preventDefault:function(){var srcEvent=this.srcEvent;srcEvent.preventManipulation&&srcEvent.preventManipulation(),srcEvent.preventDefault&&srcEvent.preventDefault()},stopPropagation:function(){this.srcEvent.stopPropagation()},stopDetect:function(){return Detection.stopDetect()}}}},PointerEvent=Hammer.PointerEvent={pointers:{},getTouchList:function(){var touchlist=[];return Utils.each(this.pointers,function(pointer){touchlist.push(pointer)}),touchlist},updatePointer:function(eventType,pointerEvent){eventType==EVENT_END||eventType!=EVENT_END&&1!==pointerEvent.buttons?delete this.pointers[pointerEvent.pointerId]:(pointerEvent.identifier=pointerEvent.pointerId,this.pointers[pointerEvent.pointerId]=pointerEvent)},matchType:function(pointerType,ev){if(!ev.pointerType)return!1;var pt=ev.pointerType,types={};return types[POINTER_MOUSE]=pt===(ev.MSPOINTER_TYPE_MOUSE||POINTER_MOUSE),types[POINTER_TOUCH]=pt===(ev.MSPOINTER_TYPE_TOUCH||POINTER_TOUCH),types[POINTER_PEN]=pt===(ev.MSPOINTER_TYPE_PEN||POINTER_PEN),types[pointerType]},reset:function(){this.pointers={}}},Detection=Hammer.detection={gestures:[],current:null,previous:null,stopped:!1,startDetect:function(inst,eventData){this.current||(this.stopped=!1,this.current={inst:inst,startEvent:Utils.extend({},eventData),lastEvent:!1,lastCalcEvent:!1,futureCalcEvent:!1,lastCalcData:{},name:""},this.detect(eventData))},detect:function(eventData){if(this.current&&!this.stopped){eventData=this.extendEventData(eventData);var inst=this.current.inst,instOptions=inst.options;return Utils.each(this.gestures,function(gesture){!this.stopped&&inst.enabled&&instOptions[gesture.name]&&gesture.handler.call(gesture,eventData,inst)},this),this.current&&(this.current.lastEvent=eventData),eventData.eventType==EVENT_END&&this.stopDetect(),eventData}},stopDetect:function(){this.previous=Utils.extend({},this.current),this.current=null,this.stopped=!0},getCalculatedData:function(ev,center,deltaTime,deltaX,deltaY){var cur=this.current,recalc=!1,calcEv=cur.lastCalcEvent,calcData=cur.lastCalcData;calcEv&&ev.timeStamp-calcEv.timeStamp>Hammer.CALCULATE_INTERVAL&&(center=calcEv.center,deltaTime=ev.timeStamp-calcEv.timeStamp,deltaX=ev.center.clientX-calcEv.center.clientX,deltaY=ev.center.clientY-calcEv.center.clientY,recalc=!0),(ev.eventType==EVENT_TOUCH||ev.eventType==EVENT_RELEASE)&&(cur.futureCalcEvent=ev),(!cur.lastCalcEvent||recalc)&&(calcData.velocity=Utils.getVelocity(deltaTime,deltaX,deltaY),calcData.angle=Utils.getAngle(center,ev.center),calcData.direction=Utils.getDirection(center,ev.center),cur.lastCalcEvent=cur.futureCalcEvent||ev,cur.futureCalcEvent=ev),ev.velocityX=calcData.velocity.x,ev.velocityY=calcData.velocity.y,ev.interimAngle=calcData.angle,ev.interimDirection=calcData.direction},extendEventData:function(ev){var cur=this.current,startEv=cur.startEvent,lastEv=cur.lastEvent||startEv;(ev.eventType==EVENT_TOUCH||ev.eventType==EVENT_RELEASE)&&(startEv.touches=[],Utils.each(ev.touches,function(touch){startEv.touches.push({clientX:touch.clientX,clientY:touch.clientY})}));var deltaTime=ev.timeStamp-startEv.timeStamp,deltaX=ev.center.clientX-startEv.center.clientX,deltaY=ev.center.clientY-startEv.center.clientY;return this.getCalculatedData(ev,lastEv.center,deltaTime,deltaX,deltaY),Utils.extend(ev,{startEvent:startEv,deltaTime:deltaTime,deltaX:deltaX,deltaY:deltaY,distance:Utils.getDistance(startEv.center,ev.center),angle:Utils.getAngle(startEv.center,ev.center),direction:Utils.getDirection(startEv.center,ev.center),scale:Utils.getScale(startEv.touches,ev.touches),rotation:Utils.getRotation(startEv.touches,ev.touches)}),ev},register:function(gesture){var options=gesture.defaults||{};return options[gesture.name]===undefined&&(options[gesture.name]=!0),Utils.extend(Hammer.defaults,options,!0),gesture.index=gesture.index||1e3,this.gestures.push(gesture),this.gestures.sort(function(a,b){return a.index<b.index?-1:a.index>b.index?1:0}),this.gestures}};Hammer.Instance=function(element,options){var self=this;setup(),this.element=element,this.enabled=!0,Utils.each(options,function(value,name){delete options[name],options[Utils.toCamelCase(name)]=value}),this.options=Utils.extend(Utils.extend({},Hammer.defaults),options||{}),this.options.behavior&&Utils.toggleBehavior(this.element,this.options.behavior,!0),this.eventStartHandler=Event.onTouch(element,EVENT_START,function(ev){self.enabled&&ev.eventType==EVENT_START?Detection.startDetect(self,ev):ev.eventType==EVENT_TOUCH&&Detection.detect(ev)}),this.eventHandlers=[]},Hammer.Instance.prototype={on:function(gestures,handler){var self=this;return Event.on(self.element,gestures,handler,function(type){self.eventHandlers.push({gesture:type,handler:handler})}),self},off:function(gestures,handler){var self=this;return Event.off(self.element,gestures,handler,function(type){var index=Utils.inArray({gesture:type,handler:handler});index!==!1&&self.eventHandlers.splice(index,1)}),self},trigger:function(gesture,eventData){eventData||(eventData={});var event=Hammer.DOCUMENT.createEvent("Event");event.initEvent(gesture,!0,!0),event.gesture=eventData;var element=this.element;return Utils.hasParent(eventData.target,element)&&(element=eventData.target),element.dispatchEvent(event),this},enable:function(state){return this.enabled=state,this},dispose:function(){var i,eh;for(Utils.toggleBehavior(this.element,this.options.behavior,!1),i=-1;eh=this.eventHandlers[++i];)Utils.off(this.element,eh.gesture,eh.handler);return this.eventHandlers=[],Event.off(this.element,EVENT_TYPES[EVENT_START],this.eventStartHandler),null}},function(name){function dragGesture(ev,inst){var cur=Detection.current;if(!(inst.options.dragMaxTouches>0&&ev.touches.length>inst.options.dragMaxTouches))switch(ev.eventType){case EVENT_START:triggered=!1;break;case EVENT_MOVE:if(ev.distance<inst.options.dragMinDistance&&cur.name!=name)return;var startCenter=cur.startEvent.center;if(cur.name!=name&&(cur.name=name,inst.options.dragDistanceCorrection&&ev.distance>0)){var factor=Math.abs(inst.options.dragMinDistance/ev.distance);startCenter.pageX+=ev.deltaX*factor,startCenter.pageY+=ev.deltaY*factor,startCenter.clientX+=ev.deltaX*factor,startCenter.clientY+=ev.deltaY*factor,ev=Detection.extendEventData(ev)}(cur.lastEvent.dragLockToAxis||inst.options.dragLockToAxis&&inst.options.dragLockMinDistance<=ev.distance)&&(ev.dragLockToAxis=!0);var lastDirection=cur.lastEvent.direction;ev.dragLockToAxis&&lastDirection!==ev.direction&&(ev.direction=Utils.isVertical(lastDirection)?ev.deltaY<0?DIRECTION_UP:DIRECTION_DOWN:ev.deltaX<0?DIRECTION_LEFT:DIRECTION_RIGHT),triggered||(inst.trigger(name+"start",ev),triggered=!0),inst.trigger(name,ev),inst.trigger(name+ev.direction,ev);var isVertical=Utils.isVertical(ev.direction);(inst.options.dragBlockVertical&&isVertical||inst.options.dragBlockHorizontal&&!isVertical)&&ev.preventDefault();break;case EVENT_RELEASE:triggered&&ev.changedLength<=inst.options.dragMaxTouches&&(inst.trigger(name+"end",ev),triggered=!1);break;case EVENT_END:triggered=!1}}var triggered=!1;Hammer.gestures.Drag={name:name,index:50,handler:dragGesture,defaults:{dragMinDistance:10,dragDistanceCorrection:!0,dragMaxTouches:1,dragBlockHorizontal:!1,dragBlockVertical:!1,dragLockToAxis:!1,dragLockMinDistance:25}}}("drag"),Hammer.gestures.Gesture={name:"gesture",index:1337,handler:function(ev,inst){inst.trigger(this.name,ev)}},function(name){function holdGesture(ev,inst){var options=inst.options,current=Detection.current;switch(ev.eventType){case EVENT_START:clearTimeout(timer),current.name=name,timer=setTimeout(function(){current&&current.name==name&&inst.trigger(name,ev)},options.holdTimeout);break;case EVENT_MOVE:ev.distance>options.holdThreshold&&clearTimeout(timer);break;case EVENT_RELEASE:clearTimeout(timer)}}var timer;Hammer.gestures.Hold={name:name,index:10,defaults:{holdTimeout:500,holdThreshold:2},handler:holdGesture}}("hold"),Hammer.gestures.Release={name:"release",index:1/0,handler:function(ev,inst){ev.eventType==EVENT_RELEASE&&inst.trigger(this.name,ev)}},Hammer.gestures.Swipe={name:"swipe",index:40,defaults:{swipeMinTouches:1,swipeMaxTouches:1,swipeVelocityX:.6,swipeVelocityY:.6},handler:function(ev,inst){if(ev.eventType==EVENT_RELEASE){var touches=ev.touches.length,options=inst.options;if(touches<options.swipeMinTouches||touches>options.swipeMaxTouches)return; (ev.velocityX>options.swipeVelocityX||ev.velocityY>options.swipeVelocityY)&&(inst.trigger(this.name,ev),inst.trigger(this.name+ev.direction,ev))}}},function(name){function tapGesture(ev,inst){var sincePrev,didDoubleTap,options=inst.options,current=Detection.current,prev=Detection.previous;switch(ev.eventType){case EVENT_START:hasMoved=!1;break;case EVENT_MOVE:hasMoved=hasMoved||ev.distance>options.tapMaxDistance;break;case EVENT_END:!Utils.inStr(ev.srcEvent.type,"cancel")&&ev.deltaTime<options.tapMaxTime&&!hasMoved&&(sincePrev=prev&&prev.lastEvent&&ev.timeStamp-prev.lastEvent.timeStamp,didDoubleTap=!1,prev&&prev.name==name&&sincePrev&&sincePrev<options.doubleTapInterval&&ev.distance<options.doubleTapDistance&&(inst.trigger("doubletap",ev),didDoubleTap=!0),(!didDoubleTap||options.tapAlways)&&(current.name=name,inst.trigger(current.name,ev)))}}var hasMoved=!1;Hammer.gestures.Tap={name:name,index:100,handler:tapGesture,defaults:{tapMaxTime:250,tapMaxDistance:10,tapAlways:!0,doubleTapDistance:20,doubleTapInterval:300}}}("tap"),Hammer.gestures.Touch={name:"touch",index:-(1/0),defaults:{preventDefault:!1,preventMouse:!1},handler:function(ev,inst){return inst.options.preventMouse&&ev.pointerType==POINTER_MOUSE?void ev.stopDetect():(inst.options.preventDefault&&ev.preventDefault(),void(ev.eventType==EVENT_TOUCH&&inst.trigger("touch",ev)))}},function(name){function transformGesture(ev,inst){switch(ev.eventType){case EVENT_START:triggered=!1;break;case EVENT_MOVE:if(ev.touches.length<2)return;var scaleThreshold=Math.abs(1-ev.scale),rotationThreshold=Math.abs(ev.rotation);if(scaleThreshold<inst.options.transformMinScale&&rotationThreshold<inst.options.transformMinRotation)return;Detection.current.name=name,triggered||(inst.trigger(name+"start",ev),triggered=!0),inst.trigger(name,ev),rotationThreshold>inst.options.transformMinRotation&&inst.trigger("rotate",ev),scaleThreshold>inst.options.transformMinScale&&(inst.trigger("pinch",ev),inst.trigger("pinch"+(ev.scale<1?"in":"out"),ev));break;case EVENT_RELEASE:triggered&&ev.changedLength<2&&(inst.trigger(name+"end",ev),triggered=!1)}}var triggered=!1;Hammer.gestures.Transform={name:name,index:45,defaults:{transformMinScale:.01,transformMinRotation:1},handler:transformGesture}}("transform"),"function"==typeof define&&define.amd?define(function(){return Hammer}):"undefined"!=typeof module&&module.exports?module.exports=Hammer:window.Hammer=Hammer}(window);var IScroll=function(window,document,Math){function IScroll(el,options){this.wrapper="string"==typeof el?document.querySelector(el):el,this.scroller=this.wrapper.children[0],this.scrollerStyle=this.scroller.style,this.options={startX:0,startY:0,scrollY:!0,directionLockThreshold:5,momentum:!0,bounce:!0,bounceTime:600,bounceEasing:"",preventDefault:!0,preventDefaultException:{tagName:/^(INPUT|TEXTAREA|BUTTON|SELECT)$/},HWCompositing:!0,useTransition:!0,useTransform:!0};for(var i in options)this.options[i]=options[i];this.translateZ=this.options.HWCompositing&&utils.hasPerspective?" translateZ(0)":"",this.options.useTransition=utils.hasTransition&&this.options.useTransition,this.options.useTransform=utils.hasTransform&&this.options.useTransform,this.options.eventPassthrough=this.options.eventPassthrough===!0?"vertical":this.options.eventPassthrough,this.options.preventDefault=!this.options.eventPassthrough&&this.options.preventDefault,this.options.scrollY="vertical"==this.options.eventPassthrough?!1:this.options.scrollY,this.options.scrollX="horizontal"==this.options.eventPassthrough?!1:this.options.scrollX,this.options.freeScroll=this.options.freeScroll&&!this.options.eventPassthrough,this.options.directionLockThreshold=this.options.eventPassthrough?0:this.options.directionLockThreshold,this.options.bounceEasing="string"==typeof this.options.bounceEasing?utils.ease[this.options.bounceEasing]||utils.ease.circular:this.options.bounceEasing,this.options.resizePolling=void 0===this.options.resizePolling?60:this.options.resizePolling,this.options.tap===!0&&(this.options.tap="tap"),this.x=0,this.y=0,this.directionX=0,this.directionY=0,this._events={},this._init(),this.refresh(),this.scrollTo(this.options.startX,this.options.startY),this.enable()}var rAF=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){window.setTimeout(callback,1e3/60)},utils=function(){function _prefixStyle(style){return _vendor===!1?!1:""===_vendor?style:_vendor+style.charAt(0).toUpperCase()+style.substr(1)}var me={},_elementStyle=document.createElement("div").style,_vendor=function(){for(var transform,vendors=["t","webkitT","MozT","msT","OT"],i=0,l=vendors.length;l>i;i++)if(transform=vendors[i]+"ransform",transform in _elementStyle)return vendors[i].substr(0,vendors[i].length-1);return!1}();me.getTime=Date.now||function(){return(new Date).getTime()},me.extend=function(target,obj){for(var i in obj)target[i]=obj[i]},me.addEvent=function(el,type,fn,capture){el.addEventListener(type,fn,!!capture)},me.removeEvent=function(el,type,fn,capture){el.removeEventListener(type,fn,!!capture)},me.momentum=function(current,start,time,lowerMargin,wrapperSize){var destination,duration,distance=current-start,speed=Math.abs(distance)/time,deceleration=6e-4;return destination=current+speed*speed/(2*deceleration)*(0>distance?-1:1),duration=speed/deceleration,lowerMargin>destination?(destination=wrapperSize?lowerMargin-wrapperSize/2.5*(speed/8):lowerMargin,distance=Math.abs(destination-current),duration=distance/speed):destination>0&&(destination=wrapperSize?wrapperSize/2.5*(speed/8):0,distance=Math.abs(current)+destination,duration=distance/speed),{destination:Math.round(destination),duration:duration}};var _transform=_prefixStyle("transform");return me.extend(me,{hasTransform:_transform!==!1,hasPerspective:_prefixStyle("perspective")in _elementStyle,hasTouch:"ontouchstart"in window,hasPointer:navigator.msPointerEnabled,hasTransition:_prefixStyle("transition")in _elementStyle}),me.isAndroidBrowser=/Android/.test(window.navigator.appVersion)&&/Version\/\d/.test(window.navigator.appVersion),me.extend(me.style={},{transform:_transform,transitionTimingFunction:_prefixStyle("transitionTimingFunction"),transitionDuration:_prefixStyle("transitionDuration"),transformOrigin:_prefixStyle("transformOrigin")}),me.hasClass=function(e,c){var re=new RegExp("(^|\\s)"+c+"(\\s|$)");return re.test(e.className)},me.addClass=function(e,c){if(!me.hasClass(e,c)){var newclass=e.className.split(" ");newclass.push(c),e.className=newclass.join(" ")}},me.removeClass=function(e,c){if(me.hasClass(e,c)){var re=new RegExp("(^|\\s)"+c+"(\\s|$)","g");e.className=e.className.replace(re," ")}},me.offset=function(el){for(var left=-el.offsetLeft,top=-el.offsetTop;el=el.offsetParent;)left-=el.offsetLeft,top-=el.offsetTop;return{left:left,top:top}},me.preventDefaultException=function(el,exceptions){for(var i in exceptions)if(exceptions[i].test(el[i]))return!0;return!1},me.extend(me.eventType={},{touchstart:1,touchmove:1,touchend:1,mousedown:2,mousemove:2,mouseup:2,MSPointerDown:3,MSPointerMove:3,MSPointerUp:3}),me.extend(me.ease={},{quadratic:{style:"cubic-bezier(0.25, 0.46, 0.45, 0.94)",fn:function(k){return k*(2-k)}},circular:{style:"cubic-bezier(0.1, 0.57, 0.1, 1)",fn:function(k){return Math.sqrt(1- --k*k)}},back:{style:"cubic-bezier(0.175, 0.885, 0.32, 1.275)",fn:function(k){var b=4;return(k-=1)*k*((b+1)*k+b)+1}},bounce:{style:"",fn:function(k){return(k/=1)<1/2.75?7.5625*k*k:2/2.75>k?7.5625*(k-=1.5/2.75)*k+.75:2.5/2.75>k?7.5625*(k-=2.25/2.75)*k+.9375:7.5625*(k-=2.625/2.75)*k+.984375}},elastic:{style:"",fn:function(k){var f=.22,e=.4;return 0===k?0:1==k?1:e*Math.pow(2,-10*k)*Math.sin(2*(k-f/4)*Math.PI/f)+1}}}),me.tap=function(e,eventName){var ev=document.createEvent("Event");ev.initEvent(eventName,!0,!0),ev.pageX=e.pageX,ev.pageY=e.pageY,e.target.dispatchEvent(ev)},me.click=function(e){var ev,target=e.target;"SELECT"!=target.tagName&&"INPUT"!=target.tagName&&"TEXTAREA"!=target.tagName&&(ev=document.createEvent("MouseEvents"),ev.initMouseEvent("click",!0,!0,e.view,1,target.screenX,target.screenY,target.clientX,target.clientY,e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,0,null),ev._constructed=!0,target.dispatchEvent(ev))},me}();return IScroll.prototype={version:"5.0.6",_init:function(){this._initEvents()},destroy:function(){this._initEvents(!0),this._execEvent("destroy")},_transitionEnd:function(e){e.target==this.scroller&&(this._transitionTime(0),this.resetPosition(this.options.bounceTime)||this._execEvent("scrollEnd"))},_start:function(e){if(!(1!=utils.eventType[e.type]&&0!==e.button||!this.enabled||this.initiated&&utils.eventType[e.type]!==this.initiated)){!this.options.preventDefault||utils.isAndroidBrowser||utils.preventDefaultException(e.target,this.options.preventDefaultException)||e.preventDefault();var pos,point=e.touches?e.touches[0]:e;this.initiated=utils.eventType[e.type],this.moved=!1,this.distX=0,this.distY=0,this.directionX=0,this.directionY=0,this.directionLocked=0,this._transitionTime(),this.isAnimating=!1,this.startTime=utils.getTime(),this.options.useTransition&&this.isInTransition&&(pos=this.getComputedPosition(),this._translate(Math.round(pos.x),Math.round(pos.y)),this._execEvent("scrollEnd"),this.isInTransition=!1),this.startX=this.x,this.startY=this.y,this.absStartX=this.x,this.absStartY=this.y,this.pointX=point.pageX,this.pointY=point.pageY,this._execEvent("beforeScrollStart")}},_move:function(e){if(this.enabled&&utils.eventType[e.type]===this.initiated){this.options.preventDefault&&e.preventDefault();var newX,newY,absDistX,absDistY,point=e.touches?e.touches[0]:e,deltaX=point.pageX-this.pointX,deltaY=point.pageY-this.pointY,timestamp=utils.getTime();if(this.pointX=point.pageX,this.pointY=point.pageY,this.distX+=deltaX,this.distY+=deltaY,absDistX=Math.abs(this.distX),absDistY=Math.abs(this.distY),!(timestamp-this.endTime>300&&10>absDistX&&10>absDistY)){if(this.directionLocked||this.options.freeScroll||(this.directionLocked=absDistX>absDistY+this.options.directionLockThreshold?"h":absDistY>=absDistX+this.options.directionLockThreshold?"v":"n"),"h"==this.directionLocked){if("vertical"==this.options.eventPassthrough)e.preventDefault();else if("horizontal"==this.options.eventPassthrough)return void(this.initiated=!1);deltaY=0}else if("v"==this.directionLocked){if("horizontal"==this.options.eventPassthrough)e.preventDefault();else if("vertical"==this.options.eventPassthrough)return void(this.initiated=!1);deltaX=0}deltaX=this.hasHorizontalScroll?deltaX:0,deltaY=this.hasVerticalScroll?deltaY:0,newX=this.x+deltaX,newY=this.y+deltaY,(newX>0||newX<this.maxScrollX)&&(newX=this.options.bounce?this.x+deltaX/3:newX>0?0:this.maxScrollX),(newY>0||newY<this.maxScrollY)&&(newY=this.options.bounce?this.y+deltaY/3:newY>0?0:this.maxScrollY),this.directionX=deltaX>0?-1:0>deltaX?1:0,this.directionY=deltaY>0?-1:0>deltaY?1:0,this.moved||this._execEvent("scrollStart"),this.moved=!0,this._translate(newX,newY),timestamp-this.startTime>300&&(this.startTime=timestamp,this.startX=this.x,this.startY=this.y)}}},_end:function(e){if(this.enabled&&utils.eventType[e.type]===this.initiated){this.options.preventDefault&&!utils.preventDefaultException(e.target,this.options.preventDefaultException)&&e.preventDefault();var momentumX,momentumY,duration=(e.changedTouches?e.changedTouches[0]:e,utils.getTime()-this.startTime),newX=Math.round(this.x),newY=Math.round(this.y),distanceX=Math.abs(newX-this.startX),distanceY=Math.abs(newY-this.startY),time=0,easing="";if(this.scrollTo(newX,newY),this.isInTransition=0,this.initiated=0,this.endTime=utils.getTime(),!this.resetPosition(this.options.bounceTime))return this.moved?this._events.flick&&200>duration&&100>distanceX&&100>distanceY?void this._execEvent("flick"):(this.options.momentum&&300>duration&&(momentumX=this.hasHorizontalScroll?utils.momentum(this.x,this.startX,duration,this.maxScrollX,this.options.bounce?this.wrapperWidth:0):{destination:newX,duration:0},momentumY=this.hasVerticalScroll?utils.momentum(this.y,this.startY,duration,this.maxScrollY,this.options.bounce?this.wrapperHeight:0):{destination:newY,duration:0},newX=momentumX.destination,newY=momentumY.destination,time=Math.max(momentumX.duration,momentumY.duration),this.isInTransition=1),newX!=this.x||newY!=this.y?((newX>0||newX<this.maxScrollX||newY>0||newY<this.maxScrollY)&&(easing=utils.ease.quadratic),void this.scrollTo(newX,newY,time,easing)):void this._execEvent("scrollEnd")):(this.options.tap&&utils.tap(e,this.options.tap),void(this.options.click&&utils.click(e)))}},_resize:function(){var that=this;clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout(function(){that.refresh()},this.options.resizePolling)},resetPosition:function(time){var x=this.x,y=this.y;return time=time||0,!this.hasHorizontalScroll||this.x>0?x=0:this.x<this.maxScrollX&&(x=this.maxScrollX),!this.hasVerticalScroll||this.y>0?y=0:this.y<this.maxScrollY&&(y=this.maxScrollY),x==this.x&&y==this.y?!1:(this.scrollTo(x,y,time,this.options.bounceEasing),!0)},disable:function(){this.enabled=!1},enable:function(){this.enabled=!0},refresh:function(){this.wrapper.offsetHeight;this.wrapperWidth=this.wrapper.clientWidth,this.wrapperHeight=this.wrapper.clientHeight,this.scrollerWidth=this.scroller.offsetWidth,this.scrollerHeight=this.scroller.offsetHeight,this.maxScrollX=this.wrapperWidth-this.scrollerWidth,this.maxScrollY=this.wrapperHeight-this.scrollerHeight,this.hasHorizontalScroll=this.options.scrollX&&this.maxScrollX<0,this.hasVerticalScroll=this.options.scrollY&&this.maxScrollY<0,this.hasHorizontalScroll||(this.maxScrollX=0,this.scrollerWidth=this.wrapperWidth),this.hasVerticalScroll||(this.maxScrollY=0,this.scrollerHeight=this.wrapperHeight),this.endTime=0,this.directionX=0,this.directionY=0,this.wrapperOffset=utils.offset(this.wrapper),this._execEvent("refresh"),this.resetPosition()},on:function(type,fn){this._events[type]||(this._events[type]=[]),this._events[type].push(fn)},_execEvent:function(type){if(this._events[type]){var i=0,l=this._events[type].length;if(l)for(;l>i;i++)this._events[type][i].call(this)}},scrollBy:function(x,y,time,easing){x=this.x+x,y=this.y+y,time=time||0,this.scrollTo(x,y,time,easing)},scrollTo:function(x,y,time,easing){easing=easing||utils.ease.circular,!time||this.options.useTransition&&easing.style?(this._transitionTimingFunction(easing.style),this._transitionTime(time),this._translate(x,y)):this._animate(x,y,time,easing.fn)},scrollToElement:function(el,time,offsetX,offsetY,easing){if(el=el.nodeType?el:this.scroller.querySelector(el)){var pos=utils.offset(el);pos.left-=this.wrapperOffset.left,pos.top-=this.wrapperOffset.top,offsetX===!0&&(offsetX=Math.round(el.offsetWidth/2-this.wrapper.offsetWidth/2)),offsetY===!0&&(offsetY=Math.round(el.offsetHeight/2-this.wrapper.offsetHeight/2)),pos.left-=offsetX||0,pos.top-=offsetY||0,pos.left=pos.left>0?0:pos.left<this.maxScrollX?this.maxScrollX:pos.left,pos.top=pos.top>0?0:pos.top<this.maxScrollY?this.maxScrollY:pos.top,time=void 0===time||null===time||"auto"===time?Math.max(Math.abs(this.x-pos.left),Math.abs(this.y-pos.top)):time,this.scrollTo(pos.left,pos.top,time,easing)}},_transitionTime:function(time){time=time||0,this.scrollerStyle[utils.style.transitionDuration]=time+"ms"},_transitionTimingFunction:function(easing){this.scrollerStyle[utils.style.transitionTimingFunction]=easing},_translate:function(x,y){this.options.useTransform?this.scrollerStyle[utils.style.transform]="translate("+x+"px,"+y+"px)"+this.translateZ:(x=Math.round(x),y=Math.round(y),this.scrollerStyle.left=x+"px",this.scrollerStyle.top=y+"px"),this.x=x,this.y=y},_initEvents:function(remove){var eventType=remove?utils.removeEvent:utils.addEvent,target=this.options.bindToWrapper?this.wrapper:window;eventType(window,"orientationchange",this),eventType(window,"resize",this),this.options.click&&eventType(this.wrapper,"click",this,!0),this.options.disableMouse||(eventType(this.wrapper,"mousedown",this),eventType(target,"mousemove",this),eventType(target,"mousecancel",this),eventType(target,"mouseup",this)),utils.hasPointer&&!this.options.disablePointer&&(eventType(this.wrapper,"MSPointerDown",this),eventType(target,"MSPointerMove",this),eventType(target,"MSPointerCancel",this),eventType(target,"MSPointerUp",this)),utils.hasTouch&&!this.options.disableTouch&&(eventType(this.wrapper,"touchstart",this),eventType(target,"touchmove",this),eventType(target,"touchcancel",this),eventType(target,"touchend",this)),eventType(this.scroller,"transitionend",this),eventType(this.scroller,"webkitTransitionEnd",this),eventType(this.scroller,"oTransitionEnd",this),eventType(this.scroller,"MSTransitionEnd",this)},getComputedPosition:function(){var x,y,matrix=window.getComputedStyle(this.scroller,null);return this.options.useTransform?(matrix=matrix[utils.style.transform].split(")")[0].split(", "),x=+(matrix[12]||matrix[4]),y=+(matrix[13]||matrix[5])):(x=+matrix.left.replace(/[^-\d]/g,""),y=+matrix.top.replace(/[^-\d]/g,"")),{x:x,y:y}},_animate:function(destX,destY,duration,easingFn){function step(){var newX,newY,easing,now=utils.getTime();return now>=destTime?(that.isAnimating=!1,that._translate(destX,destY),void(that.resetPosition(that.options.bounceTime)||that._execEvent("scrollEnd"))):(now=(now-startTime)/duration,easing=easingFn(now),newX=(destX-startX)*easing+startX,newY=(destY-startY)*easing+startY,that._translate(newX,newY),void(that.isAnimating&&rAF(step)))}var that=this,startX=this.x,startY=this.y,startTime=utils.getTime(),destTime=startTime+duration;this.isAnimating=!0,step()},handleEvent:function(e){switch(e.type){case"touchstart":case"MSPointerDown":case"mousedown":this._start(e);break;case"touchmove":case"MSPointerMove":case"mousemove":this._move(e);break;case"touchend":case"MSPointerUp":case"mouseup":case"touchcancel":case"MSPointerCancel":case"mousecancel":this._end(e);break;case"orientationchange":case"resize":this._resize();break;case"transitionend":case"webkitTransitionEnd":case"oTransitionEnd":case"MSTransitionEnd":this._transitionEnd(e);break;case"DOMMouseScroll":case"mousewheel":this._wheel(e);break;case"keydown":this._key(e);break;case"click":e._constructed||(e.preventDefault(),e.stopPropagation())}}},IScroll.ease=utils.ease,IScroll}(window,document,Math),MicroEvent=function(){};MicroEvent.prototype={on:function(event,fct){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fct)},once:function(event,fct){var self=this,wrapper=function(){return self.off(event,wrapper),fct.apply(null,arguments)};this.on(event,wrapper)},off:function(event,fct){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fct),1)},emit:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},MicroEvent.mixin=function(destObject){for(var props=["on","once","off","emit"],i=0;i<props.length;i++)"function"==typeof destObject?destObject.prototype[props[i]]=MicroEvent.prototype[props[i]]:destObject[props[i]]=MicroEvent.prototype[props[i]]},"undefined"!=typeof module&&"exports"in module&&(module.exports=MicroEvent),window.Modernizr=function(window,document,undefined){function setCss(str){mStyle.cssText=str}function is(obj,type){return typeof obj===type}function contains(str,substr){return!!~(""+str).indexOf(substr)}function testProps(props,prefixed){for(var i in props){var prop=props[i];if(!contains(prop,"-")&&mStyle[prop]!==undefined)return"pfx"==prefixed?prop:!0}return!1}function testDOMProps(props,obj,elem){for(var i in props){var item=obj[props[i]];if(item!==undefined)return elem===!1?props[i]:is(item,"function")?item.bind(elem||obj):item}return!1}function testPropsAll(prop,prefixed,elem){var ucProp=prop.charAt(0).toUpperCase()+prop.slice(1),props=(prop+" "+cssomPrefixes.join(ucProp+" ")+ucProp).split(" ");return is(prefixed,"string")||is(prefixed,"undefined")?testProps(props,prefixed):(props=(prop+" "+domPrefixes.join(ucProp+" ")+ucProp).split(" "),testDOMProps(props,prefixed,elem))}var inputElem,featureName,hasOwnProp,version="2.6.2",Modernizr={},enableClasses=!0,docElement=document.documentElement,mod="modernizr",modElem=document.createElement(mod),mStyle=modElem.style,prefixes=({}.toString," -webkit- -moz- -o- -ms- ".split(" ")),omPrefixes="Webkit Moz O ms",cssomPrefixes=omPrefixes.split(" "),domPrefixes=omPrefixes.toLowerCase().split(" "),ns={svg:"http://www.w3.org/2000/svg"},tests={},classes=[],slice=classes.slice,injectElementWithStyles=function(rule,callback,nodes,testnames){var style,ret,node,docOverflow,div=document.createElement("div"),body=document.body,fakeBody=body||document.createElement("body");if(parseInt(nodes,10))for(;nodes--;)node=document.createElement("div"),node.id=testnames?testnames[nodes]:mod+(nodes+1),div.appendChild(node);return style=["&#173;",'<style id="s',mod,'">',rule,"</style>"].join(""),div.id=mod,(body?div:fakeBody).innerHTML+=style,fakeBody.appendChild(div),body||(fakeBody.style.background="",fakeBody.style.overflow="hidden",docOverflow=docElement.style.overflow,docElement.style.overflow="hidden",docElement.appendChild(fakeBody)),ret=callback(div,rule),body?div.parentNode.removeChild(div):(fakeBody.parentNode.removeChild(fakeBody),docElement.style.overflow=docOverflow),!!ret},_hasOwnProperty={}.hasOwnProperty;hasOwnProp=is(_hasOwnProperty,"undefined")||is(_hasOwnProperty.call,"undefined")?function(object,property){return property in object&&is(object.constructor.prototype[property],"undefined")}:function(object,property){return _hasOwnProperty.call(object,property)},Function.prototype.bind||(Function.prototype.bind=function(that){var target=this;if("function"!=typeof target)throw new TypeError;var args=slice.call(arguments,1),bound=function(){if(this instanceof bound){var F=function(){};F.prototype=target.prototype;var self=new F,result=target.apply(self,args.concat(slice.call(arguments)));return Object(result)===result?result:self}return target.apply(that,args.concat(slice.call(arguments)))};return bound}),tests.canvas=function(){var elem=document.createElement("canvas");return!(!elem.getContext||!elem.getContext("2d"))},tests.borderradius=function(){return testPropsAll("borderRadius")},tests.boxshadow=function(){return testPropsAll("boxShadow")},tests.cssanimations=function(){return testPropsAll("animationName")},tests.csstransforms=function(){return!!testPropsAll("transform")},tests.csstransforms3d=function(){var ret=!!testPropsAll("perspective");return ret&&"webkitPerspective"in docElement.style&&injectElementWithStyles("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(node,rule){ret=9===node.offsetLeft&&3===node.offsetHeight}),ret},tests.csstransitions=function(){return testPropsAll("transition")},tests.svg=function(){return!!document.createElementNS&&!!document.createElementNS(ns.svg,"svg").createSVGRect};for(var feature in tests)hasOwnProp(tests,feature)&&(featureName=feature.toLowerCase(),Modernizr[featureName]=tests[feature](),classes.push((Modernizr[featureName]?"":"no-")+featureName));return Modernizr.addTest=function(feature,test){if("object"==typeof feature)for(var key in feature)hasOwnProp(feature,key)&&Modernizr.addTest(key,feature[key]);else{if(feature=feature.toLowerCase(),Modernizr[feature]!==undefined)return Modernizr;test="function"==typeof test?test():test,"undefined"!=typeof enableClasses&&enableClasses&&(docElement.className+=" "+(test?"":"no-")+feature),Modernizr[feature]=test}return Modernizr},setCss(""),modElem=inputElem=null,function(window,document){function addStyleSheet(ownerDocument,cssText){var p=ownerDocument.createElement("p"),parent=ownerDocument.getElementsByTagName("head")[0]||ownerDocument.documentElement;return p.innerHTML="x<style>"+cssText+"</style>",parent.insertBefore(p.lastChild,parent.firstChild)}function getElements(){var elements=html5.elements;return"string"==typeof elements?elements.split(" "):elements}function getExpandoData(ownerDocument){var data=expandoData[ownerDocument[expando]];return data||(data={},expanID++,ownerDocument[expando]=expanID,expandoData[expanID]=data),data}function createElement(nodeName,ownerDocument,data){if(ownerDocument||(ownerDocument=document),supportsUnknownElements)return ownerDocument.createElement(nodeName);data||(data=getExpandoData(ownerDocument));var node;return node=data.cache[nodeName]?data.cache[nodeName].cloneNode():saveClones.test(nodeName)?(data.cache[nodeName]=data.createElem(nodeName)).cloneNode():data.createElem(nodeName),node.canHaveChildren&&!reSkip.test(nodeName)?data.frag.appendChild(node):node}function createDocumentFragment(ownerDocument,data){if(ownerDocument||(ownerDocument=document),supportsUnknownElements)return ownerDocument.createDocumentFragment();data=data||getExpandoData(ownerDocument);for(var clone=data.frag.cloneNode(),i=0,elems=getElements(),l=elems.length;l>i;i++)clone.createElement(elems[i]);return clone}function shivMethods(ownerDocument,data){data.cache||(data.cache={},data.createElem=ownerDocument.createElement,data.createFrag=ownerDocument.createDocumentFragment,data.frag=data.createFrag()),ownerDocument.createElement=function(nodeName){return html5.shivMethods?createElement(nodeName,ownerDocument,data):data.createElem(nodeName)},ownerDocument.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+getElements().join().replace(/\w+/g,function(nodeName){return data.createElem(nodeName),data.frag.createElement(nodeName),'c("'+nodeName+'")'})+");return n}")(html5,data.frag)}function shivDocument(ownerDocument){ownerDocument||(ownerDocument=document);var data=getExpandoData(ownerDocument);return!html5.shivCSS||supportsHtml5Styles||data.hasCSS||(data.hasCSS=!!addStyleSheet(ownerDocument,"article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")),supportsUnknownElements||shivMethods(ownerDocument,data),ownerDocument}var supportsHtml5Styles,supportsUnknownElements,options=window.html5||{},reSkip=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,saveClones=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,expando="_html5shiv",expanID=0,expandoData={};!function(){try{var a=document.createElement("a");a.innerHTML="<xyz></xyz>",supportsHtml5Styles="hidden"in a,supportsUnknownElements=1==a.childNodes.length||function(){document.createElement("a");var frag=document.createDocumentFragment();return"undefined"==typeof frag.cloneNode||"undefined"==typeof frag.createDocumentFragment||"undefined"==typeof frag.createElement}()}catch(e){supportsHtml5Styles=!0,supportsUnknownElements=!0}}();var html5={elements:options.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:options.shivCSS!==!1,supportsUnknownElements:supportsUnknownElements,shivMethods:options.shivMethods!==!1,type:"default",shivDocument:shivDocument,createElement:createElement,createDocumentFragment:createDocumentFragment};window.html5=html5,shivDocument(document)}(this,document),Modernizr._version=version,Modernizr._prefixes=prefixes,Modernizr._domPrefixes=domPrefixes,Modernizr._cssomPrefixes=cssomPrefixes,Modernizr.testProp=function(prop){return testProps([prop])},Modernizr.testAllProps=testPropsAll,Modernizr.testStyles=injectElementWithStyles,docElement.className=docElement.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(enableClasses?" js "+classes.join(" "):""),Modernizr}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var A,B,l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}};B=function(a){function b(a){var e,f,g,a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a};for(f=0;d>f;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;b>f;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var c,b=0;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var m,n,h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var l,o,k=b.createElement("script"),e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var j,e=b.createElement("link"),c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))},function(global,undefined){"use strict";function addFromSetImmediateArguments(args){return tasksByHandle[nextHandle]=partiallyApplied.apply(undefined,args),nextHandle++}function partiallyApplied(handler){var args=[].slice.call(arguments,1);return function(){"function"==typeof handler?handler.apply(undefined,args):new Function(""+handler)()}}function runIfPresent(handle){if(currentlyRunningATask)setTimeout(partiallyApplied(runIfPresent,handle),0); else{var task=tasksByHandle[handle];if(task){currentlyRunningATask=!0;try{task()}finally{clearImmediate(handle),currentlyRunningATask=!1}}}}function clearImmediate(handle){delete tasksByHandle[handle]}function installNextTickImplementation(){setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return process.nextTick(partiallyApplied(runIfPresent,handle)),handle}}function canUsePostMessage(){if(global.postMessage&&!global.importScripts){var postMessageIsAsynchronous=!0,oldOnMessage=global.onmessage;return global.onmessage=function(){postMessageIsAsynchronous=!1},global.postMessage("","*"),global.onmessage=oldOnMessage,postMessageIsAsynchronous}}function installPostMessageImplementation(){var messagePrefix="setImmediate$"+Math.random()+"$",onGlobalMessage=function(event){event.source===global&&"string"==typeof event.data&&0===event.data.indexOf(messagePrefix)&&runIfPresent(+event.data.slice(messagePrefix.length))};global.addEventListener?global.addEventListener("message",onGlobalMessage,!1):global.attachEvent("onmessage",onGlobalMessage),setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return global.postMessage(messagePrefix+handle,"*"),handle}}function installMessageChannelImplementation(){var channel=new MessageChannel;channel.port1.onmessage=function(event){var handle=event.data;runIfPresent(handle)},setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return channel.port2.postMessage(handle),handle}}function installReadyStateChangeImplementation(){var html=doc.documentElement;setImmediate=function(){var handle=addFromSetImmediateArguments(arguments),script=doc.createElement("script");return script.onreadystatechange=function(){runIfPresent(handle),script.onreadystatechange=null,html.removeChild(script),script=null},html.appendChild(script),handle}}function installSetTimeoutImplementation(){setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return setTimeout(partiallyApplied(runIfPresent,handle),0),handle}}if(!global.setImmediate){var setImmediate,nextHandle=1,tasksByHandle={},currentlyRunningATask=!1,doc=global.document,attachTo=Object.getPrototypeOf&&Object.getPrototypeOf(global);attachTo=attachTo&&attachTo.setTimeout?attachTo:global,"[object process]"==={}.toString.call(global.process)?installNextTickImplementation():canUsePostMessage()?installPostMessageImplementation():global.MessageChannel?installMessageChannelImplementation():doc&&"onreadystatechange"in doc.createElement("script")?installReadyStateChangeImplementation():installSetTimeoutImplementation(),attachTo.setImmediate=setImmediate,attachTo.clearImmediate=clearImmediate}}(new Function("return this")()),function(){function Viewport(){return this.PRE_IOS7_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.IOS7_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.DEFAULT_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.ensureViewportElement(),this.platform={},this.platform.name=this.getPlatformName(),this.platform.version=this.getPlatformVersion(),this}Viewport.prototype.ensureViewportElement=function(){this.viewportElement=document.querySelector("meta[name=viewport]"),this.viewportElement||(this.viewportElement=document.createElement("meta"),this.viewportElement.name="viewport",document.head.appendChild(this.viewportElement))},Viewport.prototype.setup=function(){function isWebView(){return!!(window.cordova||window.phonegap||window.PhoneGap)}this.viewportElement&&"true"!=this.viewportElement.getAttribute("data-no-adjust")&&("ios"==this.platform.name?this.platform.version>=7&&isWebView()?this.viewportElement.setAttribute("content",this.IOS7_VIEWPORT):this.viewportElement.setAttribute("content",this.PRE_IOS7_VIEWPORT):this.viewportElement.setAttribute("content",this.DEFAULT_VIEWPORT))},Viewport.prototype.getPlatformName=function(){return navigator.userAgent.match(/Android/i)?"android":navigator.userAgent.match(/iPhone|iPad|iPod/i)?"ios":void 0},Viewport.prototype.getPlatformVersion=function(){var start=window.navigator.userAgent.indexOf("OS ");return window.Number(window.navigator.userAgent.substr(start+3,3).replace("_","."))},window.Viewport=Viewport}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/back_button.tpl",'<span \n class="toolbar-button--quiet {{modifierTemplater(\'toolbar-button--*\')}}" \n ng-click="$root.ons.findParentComponentUntil(\'ons-navigator\', $event).popPage({cancelIfRunning: true})"\n ng-show="showBackButton"\n style="height: 44px; line-height: 0; padding: 0 10px 0 0; position: relative;">\n \n <i \n class="ion-ios-arrow-back ons-back-button__icon" \n style="vertical-align: top; background-color: transparent; height: 44px; line-height: 44px; font-size: 36px; margin-left: 8px; margin-right: 2px; width: 16px; display: inline-block; padding-top: 1px;"></i>\n\n <span \n style="vertical-align: top; display: inline-block; line-height: 44px; height: 44px;" \n class="back-button__label"></span>\n</span>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/button.tpl",'<span class="label ons-button-inner"></span>\n<span class="spinner button__spinner {{modifierTemplater(\'button--*__spinner\')}}"></span>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/dialog.tpl",'<div class="dialog-mask"></div>\n<div class="dialog {{ modifierTemplater(\'dialog--*\') }}"></div>\n</div>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/icon.tpl",'<i class="fa fa-{{icon}} fa-{{spin}} fa-{{fixedWidth}} fa-rotate-{{rotate}} fa-flip-{{flip}}" ng-class="sizeClass" ng-style="style"></i>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/popover.tpl",'<div class="popover-mask"></div>\n<div class="popover popover--{{ direction }} {{ modifierTemplater(\'popover--*\') }}">\n <div class="popover__content {{ modifierTemplater(\'popover__content--*\') }}"></div>\n <div class="popover__{{ arrowPosition }}-arrow"></div>\n</div>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/row.tpl",'<div class="row row-{{align}} ons-row-inner"></div>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/sliding_menu.tpl",'<div class="onsen-sliding-menu__menu ons-sliding-menu-inner"></div>\n<div class="onsen-sliding-menu__main ons-sliding-menu-inner"></div>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/split_view.tpl",'<div class="onsen-split-view__secondary full-screen ons-split-view-inner"></div>\n<div class="onsen-split-view__main full-screen ons-split-view-inner"></div>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/switch.tpl",'<label class="switch {{modifierTemplater(\'switch--*\')}}">\n <input type="checkbox" class="switch__input {{modifierTemplater(\'switch--*__input\')}}" ng-model="model">\n <div class="switch__toggle {{modifierTemplater(\'switch--*__toggle\')}}"></div>\n</label>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/tab.tpl",'<input type="radio" name="tab-bar-{{tabbarId}}" style="display: none">\n<button class="tab-bar__button tab-bar-inner {{tabbarModifierTemplater(\'tab-bar--*__button\')}} {{modifierTemplater(\'tab-bar__button--*\')}}" ng-click="tryToChange()">\n</button>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/tab_bar.tpl",'<div class="ons-tab-bar__content tab-bar__content"></div>\n<div ng-hide="hideTabs" class="tab-bar ons-tab-bar__footer {{modifierTemplater(\'tab-bar--*\')}} ons-tabbar-inner"></div>\n')}])}(),function(module){try{module=angular.module("templates-main")}catch(err){module=angular.module("templates-main",[])}module.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/toolbar_button.tpl","<span class=\"toolbar-button {{modifierTemplater('toolbar-button--*')}} navigation-bar__line-height\" ng-transclude></span>\n")}])}(),window.DoorLock=function(){var DoorLock=function(options){options=options||{},this._lockList=[],this._waitList=[],this._log=options.log||function(){}};return DoorLock.generateId=function(){var i=0;return function(){return i++}}(),DoorLock.prototype={lock:function(){var self=this,unlock=function(){self._unlock(unlock)};return unlock.id=DoorLock.generateId(),this._lockList.push(unlock),this._log("lock: "+unlock.id),unlock},_unlock:function(fn){var index=this._lockList.indexOf(fn);if(-1===index)throw new Error("This function is not registered in the lock list.");this._lockList.splice(index,1),this._log("unlock: "+fn.id),this._tryToFreeWaitList()},_tryToFreeWaitList:function(){for(;!this.isLocked()&&this._waitList.length>0;)this._waitList.shift()()},waitUnlock:function(callback){if(!(callback instanceof Function))throw new Error("The callback param must be a function.");this.isLocked()?this._waitList.push(callback):callback()},isLocked:function(){return this._lockList.length>0}},DoorLock}(),window.ons=function(){"use strict";function waitDeviceReady(){var unlockDeviceReady=ons._readyLock.lock();window.addEventListener("DOMContentLoaded",function(){ons.isWebView()?window.document.addEventListener("deviceready",unlockDeviceReady,!1):unlockDeviceReady()},!1)}function waitOnsenUILoad(){var unlockOnsenUI=ons._readyLock.lock();module.run(["$compile","$rootScope","$onsen",function($compile,$rootScope,$onsen){if("loading"===document.readyState||"uninitialized"==document.readyState)window.addEventListener("DOMContentLoaded",function(){document.body.appendChild(document.createElement("ons-dummy-for-init"))});else{if(!document.body)throw new Error("Invalid initialization state.");document.body.appendChild(document.createElement("ons-dummy-for-init"))}$rootScope.$on("$ons-ready",unlockOnsenUI)}])}function initAngularModule(){module.value("$onsGlobal",ons),module.run(["$compile","$rootScope","$onsen","$q",function($compile,$rootScope,$onsen,$q){ons._onsenService=$onsen,ons._qService=$q,$rootScope.ons=window.ons,$rootScope.console=window.console,$rootScope.alert=window.alert,ons.$compile=$compile}])}function initKeyboardEvents(){ons.softwareKeyboard=new MicroEvent,ons.softwareKeyboard._visible=!1;var onShow=function(){ons.softwareKeyboard._visible=!0,ons.softwareKeyboard.emit("show")},onHide=function(){ons.softwareKeyboard._visible=!1,ons.softwareKeyboard.emit("hide")},bindEvents=function(){return"undefined"!=typeof Keyboard?(Keyboard.onshow=onShow,Keyboard.onhide=onHide,ons.softwareKeyboard.emit("init",{visible:Keyboard.isVisible}),!0):"undefined"!=typeof cordova.plugins&&"undefined"!=typeof cordova.plugins.Keyboard?(window.addEventListener("native.keyboardshow",onShow),window.addEventListener("native.keyboardhide",onHide),ons.softwareKeyboard.emit("init",{visible:cordova.plugins.Keyboard.isVisible}),!0):!1},noPluginError=function(){console.warn("ons-keyboard: Cordova Keyboard plugin is not present.")};document.addEventListener("deviceready",function(){bindEvents()||((document.querySelector("[ons-keyboard-active]")||document.querySelector("[ons-keyboard-inactive]"))&&noPluginError(),ons.softwareKeyboard.on=noPluginError)})}function createOnsenFacade(){var ons={_readyLock:new DoorLock,_onsenService:null,_config:{autoStatusBarFill:!0},_unlockersDict:{},componentBase:window,bootstrap:function(name,deps){angular.isArray(name)&&(deps=name,name=void 0),name||(name="myOnsenApp"),deps=["onsen"].concat(angular.isArray(deps)?deps:[]);var module=angular.module(name,deps),doc=window.document;if("loading"==doc.readyState||"uninitialized"==doc.readyState||"interactive"==doc.readyState)doc.addEventListener("DOMContentLoaded",function(){angular.bootstrap(doc.documentElement,[name])},!1);else{if(!doc.documentElement)throw new Error("Invalid state");angular.bootstrap(doc.documentElement,[name])}return module},enableAutoStatusBarFill:function(){if(this.isReady())throw new Error("This method must be called before ons.isReady() is true.");this._config.autoStatusBarFill=!0},disableAutoStatusBarFill:function(){if(this.isReady())throw new Error("This method must be called before ons.isReady() is true.");this._config.autoStatusBarFill=!1},findParentComponentUntil:function(name,dom){var element;return dom instanceof HTMLElement?element=angular.element(dom):dom instanceof angular.element?element=dom:dom.target&&(element=angular.element(dom.target)),element.inheritedData(name)},setDefaultDeviceBackButtonListener:function(listener){this._getOnsenService().getDefaultDeviceBackButtonHandler().setListener(listener)},disableDeviceBackButtonHandler:function(){this._getOnsenService().DeviceBackButtonHandler.disable()},enableDeviceBackButtonHandler:function(){this._getOnsenService().DeviceBackButtonHandler.enable()},findComponent:function(selector,dom){var target=(dom?dom:document).querySelector(selector);return target?angular.element(target).data(target.nodeName.toLowerCase())||null:null},isReady:function(){return!ons._readyLock.isLocked()},compile:function(dom){if(!ons.$compile)throw new Error("ons.$compile() is not ready. Wait for initialization with ons.ready().");if(!(dom instanceof HTMLElement))throw new Error("First argument must be an instance of HTMLElement.");var scope=angular.element(dom).scope();if(!scope)throw new Error("AngularJS Scope is null. Argument DOM element must be attached in DOM document.");ons.$compile(dom)(scope)},_getOnsenService:function(){if(!this._onsenService)throw new Error("$onsen is not loaded, wait for ons.ready().");return this._onsenService},ready:function(callback){if(callback instanceof Function)ons.isReady()?callback():ons._readyLock.waitUnlock(callback);else if(angular.isArray(callback)&&arguments[1]instanceof Function){var dependencies=callback;callback=arguments[1],ons.ready(function(){var $onsen=ons._getOnsenService();$onsen.waitForVariables(dependencies,callback)})}},isWebView:function(){if("loading"===document.readyState||"uninitialized"==document.readyState)throw new Error("isWebView() method is available after dom contents loaded.");return!!(window.cordova||window.phonegap||window.PhoneGap)},createAlertDialog:function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");var alertDialog=angular.element("<ons-alert-dialog>"),$onsen=this._getOnsenService();return angular.element(document.body).append(angular.element(alertDialog)),$onsen.getPageHTMLAsync(page).then(function(html){var div=document.createElement("div");div.innerHTML=html;for(var el=angular.element(div.querySelector("ons-alert-dialog")),attrs=el.prop("attributes"),i=0,l=attrs.length;l>i;i++)alertDialog.attr(attrs[i].name,attrs[i].value);alertDialog.html(el.html());var parentScope;return options.parentScope?(parentScope=options.parentScope.$new(),ons.$compile(alertDialog)(parentScope)):ons.compile(alertDialog[0]),el.attr("disabled")&&alertDialog.attr("disabled","disabled"),parentScope&&(alertDialog.data("ons-alert-dialog")._parentScope=parentScope),alertDialog.data("ons-alert-dialog")})},createDialog:function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");var dialog=angular.element("<ons-dialog>"),$onsen=this._getOnsenService();return angular.element(document.body).append(angular.element(dialog)),$onsen.getPageHTMLAsync(page).then(function(html){var div=document.createElement("div");div.innerHTML=html;for(var el=angular.element(div.querySelector("ons-dialog")),attrs=el.prop("attributes"),i=0,l=attrs.length;l>i;i++)dialog.attr(attrs[i].name,attrs[i].value);dialog.html(el.html());var parentScope;options.parentScope?(parentScope=options.parentScope.$new(),ons.$compile(dialog)(parentScope)):ons.compile(dialog[0]),el.attr("disabled")&&dialog.attr("disabled","disabled");var deferred=ons._qService.defer();return dialog.on("ons-dialog:init",function(e){var child=dialog[0].querySelector(".dialog");if(el[0].hasAttribute("style")){var parentStyle=el[0].getAttribute("style"),childStyle=child.getAttribute("style"),newStyle=function(a,b){var c=(";"===a.substr(-1)?a:a+";")+(";"===b.substr(-1)?b:b+";");return c}(parentStyle,childStyle);child.setAttribute("style",newStyle)}parentScope&&(e.component._parentScope=parentScope),deferred.resolve(e.component)}),deferred.promise})},createPopover:function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");var popover=angular.element("<ons-popover>"),$onsen=this._getOnsenService();return angular.element(document.body).append(angular.element(popover)),$onsen.getPageHTMLAsync(page).then(function(html){var div=document.createElement("div");div.innerHTML=html;for(var el=angular.element(div.querySelector("ons-popover")),attrs=el.prop("attributes"),i=0,l=attrs.length;l>i;i++)popover.attr(attrs[i].name,attrs[i].value);popover.html(el.html());var parentScope;options.parentScope?(parentScope=options.parentScope.$new(),ons.$compile(popover)(parentScope)):ons.compile(popover[0]),el.attr("disabled")&&popover.attr("disabled","disabled");var deferred=ons._qService.defer();return popover.on("ons-popover:init",function(e){var child=popover[0].querySelector(".popover");if(el[0].hasAttribute("style")){var parentStyle=el[0].getAttribute("style"),childStyle=child.getAttribute("style"),newStyle=function(a,b){var c=(";"===a.substr(-1)?a:a+";")+(";"===b.substr(-1)?b:b+";");return c}(parentStyle,childStyle);child.setAttribute("style",newStyle)}parentScope&&(e.component._parentScope=parentScope),deferred.resolve(e.component)}),deferred.promise})}};return ons}var module=angular.module("onsen",["templates-main"]);angular.module("onsen.directives",["onsen"]);var ons=createOnsenFacade();return initKeyboardEvents(),waitDeviceReady(),waitOnsenUILoad(),initAngularModule(),ons}(),function(){"use strict";var module=angular.module("onsen");module.factory("AlertDialogView",["$onsen","DialogAnimator","SlideDialogAnimator","AndroidAlertDialogAnimator","IOSAlertDialogAnimator",function($onsen,DialogAnimator,SlideDialogAnimator,AndroidAlertDialogAnimator,IOSAlertDialogAnimator){var AlertDialogView=Class.extend({init:function(scope,element,attrs){if(this._scope=scope,this._element=element,this._attrs=attrs,this._element.css({display:"none",zIndex:20001}),this._dialog=element,this._visible=!1,this._doorLock=new DoorLock,this._animation=AlertDialogView._animatorDict["undefined"!=typeof attrs.animation?attrs.animation:"default"],!this._animation)throw new Error("No such animation: "+attrs.animation);this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)),this._createMask(attrs.maskColor),this._scope.$on("$destroy",this._destroy.bind(this))},show:function(options){options=options||{};var cancel=!1,callback=options.callback||function(){};this.emit("preshow",{alertDialog:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;this._mask.css("display","block"),this._mask.css("opacity",1),this._element.css("display","block"),options.animation&&(animation=AlertDialogView._animatorDict[options.animation]),animation.show(this,function(){this._visible=!0,unlock(),this.emit("postshow",{alertDialog:this}),callback()}.bind(this))}.bind(this))},hide:function(options){options=options||{};var cancel=!1,callback=options.callback||function(){};this.emit("prehide",{alertDialog:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;options.animation&&(animation=AlertDialogView._animatorDict[options.animation]),animation.hide(this,function(){this._element.css("display","none"),this._mask.css("display","none"),this._visible=!1,unlock(),this.emit("posthide",{alertDialog:this}),callback()}.bind(this))}.bind(this))},isShown:function(){return this._visible},destroy:function(){this._parentScope?(this._parentScope.$destroy(),this._parentScope=null):this._scope.$destroy()},_destroy:function(){this.emit("destroy"),this._mask.off(),this._element.remove(),this._mask.remove(),this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=this._scope=this._attrs=this._element=this._mask=null},setDisabled:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this._element.attr("disabled",!0):this._element.removeAttr("disabled")},isDisabled:function(){return this._element[0].hasAttribute("disabled")},setCancelable:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this._element.attr("cancelable",!0):this._element.removeAttr("cancelable")},isCancelable:function(){return this._element[0].hasAttribute("cancelable")},_cancel:function(){this.isCancelable()&&this.hide({callback:function(){this.emit("cancel")}.bind(this)})},_onDeviceBackButton:function(event){this.isCancelable()?this._cancel.bind(this)():event.callParentHandler()},_createMask:function(color){this._mask=angular.element("<div>").addClass("alert-dialog-mask").css({zIndex:2e4,display:"none"}),this._mask.on("click",this._cancel.bind(this)),color&&this._mask.css("background-color",color),angular.element(document.body).append(this._mask)}});return AlertDialogView._animatorDict={"default":$onsen.isAndroid()?new AndroidAlertDialogAnimator:new IOSAlertDialogAnimator,fade:$onsen.isAndroid()?new AndroidAlertDialogAnimator:new IOSAlertDialogAnimator,slide:new SlideDialogAnimator,none:new DialogAnimator},AlertDialogView.registerAnimator=function(name,animator){if(!(animator instanceof DialogAnimator))throw new Error('"animator" param must be an instance of DialogAnimator');this._animatorDict[name]=animator},MicroEvent.mixin(AlertDialogView),AlertDialogView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("AndroidAlertDialogAnimator",["DialogAnimator",function(DialogAnimator){var AndroidAlertDialogAnimator=DialogAnimator.extend({timing:"cubic-bezier(.1, .7, .4, 1)",duration:.2,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)",opacity:0},duration:0}).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:0}).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)",opacity:0},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return AndroidAlertDialogAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("AndroidDialogAnimator",["DialogAnimator",function(DialogAnimator){var AndroidDialogAnimator=DialogAnimator.extend({timing:"ease-in-out",duration:.3,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -60%, 0)",opacity:0},duration:0}).queue({css:{transform:"translate3d(-50%, -50%, 0)",opacity:1},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -50%, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3d(-50%, -60%, 0)",opacity:0},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return AndroidDialogAnimator}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("ButtonView",["$onsen",function($onsen){var ButtonView=Class.extend({init:function(scope,element,attrs){this._element=element,this._scope=scope,this._attrs=attrs},startSpin:function(){this._attrs.$set("shouldSpin","true")},stopSpin:function(){this._attrs.$set("shouldSpin","false")},isSpinning:function(){return"true"===this._attrs.shouldSpin},setSpinAnimation:function(animation){this._scope.$apply(function(){var animations=["slide-left","slide-right","slide-up","slide-down","expand-left","expand-right","expand-up","expand-down","zoom-out","zoom-in"];animations.indexOf(animation)<0&&(console.warn("Animation "+animation+"doesn't exist."),animation="slide-left"),this._scope.animation=animation}.bind(this))},isDisabled:function(){return this._element[0].hasAttribute("disabled")},setDisabled:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this._element[0].setAttribute("disabled",""):this._element[0].removeAttribute("disabled")}});return MicroEvent.mixin(ButtonView),ButtonView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("CarouselView",["$onsen",function($onsen){var VerticalModeTrait={_getScrollDelta:function(event){return event.gesture.deltaY},_getScrollVelocity:function(event){return event.gesture.velocityY},_getElementSize:function(){return this._currentElementSize||(this._currentElementSize=this._element[0].getBoundingClientRect().height),this._currentElementSize},_generateScrollTransform:function(scroll){return"translate3d(0px, "+-scroll+"px, 0px)"},_layoutCarouselItems:function(){for(var children=this._getCarouselItemElements(),sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),i=0;i<children.length;i++)angular.element(children[i]).css({position:"absolute",height:sizeAttr,width:"100%",visibility:"visible",left:"0px",top:i*sizeInfo.number+sizeInfo.unit})}},HorizontalModeTrait={_getScrollDelta:function(event){return event.gesture.deltaX},_getScrollVelocity:function(event){return event.gesture.velocityX},_getElementSize:function(){return this._currentElementSize||(this._currentElementSize=this._element[0].getBoundingClientRect().width),this._currentElementSize},_generateScrollTransform:function(scroll){return"translate3d("+-scroll+"px, 0px, 0px)"},_layoutCarouselItems:function(){for(var children=this._getCarouselItemElements(),sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),i=0;i<children.length;i++)angular.element(children[i]).css({position:"absolute",width:sizeAttr,height:"100%",top:"0px",visibility:"visible",left:i*sizeInfo.number+sizeInfo.unit})}},CarouselView=Class.extend({_element:void 0,_scope:void 0,_doorLock:void 0,_scroll:void 0,init:function(scope,element,attrs){this._element=element,this._scope=scope,this._attrs=attrs,this._doorLock=new DoorLock,this._scroll=0,this._lastActiveIndex=0,this._bindedOnDrag=this._onDrag.bind(this),this._bindedOnDragEnd=this._onDragEnd.bind(this),this._bindedOnResize=this._onResize.bind(this),this._mixin(this._isVertical()?VerticalModeTrait:HorizontalModeTrait),this._prepareEventListeners(),this._layoutCarouselItems(),this._setupInitialIndex(),this._attrs.$observe("direction",this._onDirectionChange.bind(this)),this._scope.$on("$destroy",this._destroy.bind(this)),this._saveLastState()},_onResize:function(){this.refresh()},_onDirectionChange:function(){this._element.css(this._isVertical()?{overflowX:"auto",overflowY:""}:{overflowX:"",overflowY:"auto"})},_saveLastState:function(){this._lastState={elementSize:this._getCarouselItemSize(),carouselElementCount:this._getCarouselItemCount(),width:this._getCarouselItemSize()*this._getCarouselItemCount()}},_getCarouselItemSize:function(){var sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),elementSize=this._getElementSize();if("%"===sizeInfo.unit)return Math.round(sizeInfo.number/100*elementSize);if("px"===sizeInfo.unit)return sizeInfo.number;throw new Error("Invalid state")},_getInitialIndex:function(){var index=parseInt(this._element.attr("initial-index"),10);return"number"!=typeof index||isNaN(index)?0:Math.max(Math.min(index,this._getCarouselItemCount()-1),0)},_getCarouselItemSizeAttr:function(){var attrName="item-"+(this._isVertical()?"height":"width"),itemSizeAttr=(""+this._element.attr(attrName)).trim();return itemSizeAttr.match(/^\d+(px|%)$/)?itemSizeAttr:"100%"},_decomposeSizeString:function(size){var matches=size.match(/^(\d+)(px|%)/);return{number:parseInt(matches[1],10),unit:matches[2]}},_setupInitialIndex:function(){this._scroll=this._getCarouselItemSize()*this._getInitialIndex(),this._lastActiveIndex=this._getInitialIndex(),this._scrollTo(this._scroll)},setSwipeable:function(swipeable){swipeable?this._element[0].setAttribute("swipeable",""):this._element[0].removeAttribute("swipeable")},isSwipeable:function(){return this._element[0].hasAttribute("swipeable")},setAutoScrollRatio:function(ratio){if(0>ratio||ratio>1)throw new Error("Invalid ratio.");this._element[0].setAttribute("auto-scroll-ratio",ratio)},getAutoScrollRatio:function(ratio){var attr=this._element[0].getAttribute("auto-scroll-ratio");if(!attr)return.5;var scrollRatio=parseFloat(attr);if(0>scrollRatio||scrollRatio>1)throw new Error("Invalid ratio.");return isNaN(scrollRatio)?.5:scrollRatio},setActiveCarouselItemIndex:function(index,options){options=options||{},index=Math.max(0,Math.min(index,this._getCarouselItemCount()-1));var scroll=this._getCarouselItemSize()*index,max=this._calculateMaxScroll();this._scroll=Math.max(0,Math.min(max,scroll)),this._scrollTo(this._scroll,{animate:"none"!==options.animation,callback:options.callback}),this._tryFirePostChangeEvent()},getActiveCarouselItemIndex:function(){var scroll=this._scroll,count=this._getCarouselItemCount(),size=this._getCarouselItemSize(); if(0>scroll)return 0;for(var i=0;count>i;i++)if(scroll>=size*i&&size*(i+1)>scroll)return i;return i},next:function(options){this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex()+1,options)},prev:function(options){this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex()-1,options)},setAutoScrollEnabled:function(enabled){enabled?this._element[0].setAttribute("auto-scroll",""):this._element[0].removeAttribute("auto-scroll")},isAutoScrollEnabled:function(enabled){return this._element[0].hasAttribute("auto-scroll")},setDisabled:function(disabled){disabled?this._element[0].setAttribute("disabled",""):this._element[0].removeAttribute("disabled")},isDisabled:function(){return this._element[0].hasAttribute("disabled")},setOverscrollable:function(scrollable){scrollable?this._element[0].setAttribute("overscrollable",""):this._element[0].removeAttribute("overscrollable")},_mixin:function(trait){Object.keys(trait).forEach(function(key){this[key]=trait[key]}.bind(this))},_isEnabledChangeEvent:function(){var elementSize=this._getElementSize(),carouselItemSize=this._getCarouselItemSize();return this.isAutoScrollEnabled()&&elementSize===carouselItemSize},_isVertical:function(){return"vertical"===this._element.attr("direction")},_prepareEventListeners:function(){this._hammer=new Hammer(this._element[0],{dragMinDistance:1}),this._hammer.on("drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown",this._bindedOnDrag),this._hammer.on("dragend",this._bindedOnDragEnd),angular.element(window).on("resize",this._bindedOnResize)},_tryFirePostChangeEvent:function(){var currentIndex=this.getActiveCarouselItemIndex();if(this._lastActiveIndex!==currentIndex){var lastActiveIndex=this._lastActiveIndex;this._lastActiveIndex=currentIndex,this.emit("postchange",{carousel:this,activeIndex:currentIndex,lastActiveIndex:lastActiveIndex})}},_onDrag:function(event){if(this.isSwipeable()){var direction=event.gesture.direction;if((!this._isVertical()||"left"!==direction&&"right"!==direction)&&(this._isVertical()||"up"!==direction&&"down"!==direction)){event.stopPropagation(),this._lastDragEvent=event;var scroll=this._scroll-this._getScrollDelta(event);this._scrollTo(scroll),event.gesture.preventDefault(),this._tryFirePostChangeEvent()}}},_onDragEnd:function(event){if(this._currentElementSize=void 0,this._carouselItemElements=void 0,this.isSwipeable()){if(this._scroll=this._scroll-this._getScrollDelta(event),0!==this._getScrollDelta(event)&&event.stopPropagation(),this._isOverScroll(this._scroll)){var waitForAction=!1;this.emit("overscroll",{carousel:this,activeIndex:this.getActiveCarouselItemIndex(),direction:this._getOverScrollDirection(),waitToReturn:function(promise){waitForAction=!0,promise.then(function(){this._scrollToKillOverScroll()}.bind(this))}.bind(this)}),waitForAction||this._scrollToKillOverScroll()}else this._startMomemtumScroll(event);this._lastDragEvent=null,event.gesture.preventDefault()}},_getTouchEvents:function(){var EVENTS=["drag","dragstart","dragend","dragup","dragdown","dragleft","dragright","swipe","swipeup","swipedown","swipeleft","swiperight"];return EVENTS.join(" ")},isOverscrollable:function(){return this._element[0].hasAttribute("overscrollable")},_startMomemtumScroll:function(event){if(this._lastDragEvent){var velocity=this._getScrollVelocity(this._lastDragEvent),duration=.3,scrollDelta=100*duration*velocity,scroll=this._scroll+(this._getScrollDelta(this._lastDragEvent)>0?-scrollDelta:scrollDelta);scroll=this._normalizeScrollPosition(scroll),this._scroll=scroll,animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(this._scroll)},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){done(),this._tryFirePostChangeEvent()}.bind(this)).play()}},_normalizeScrollPosition:function(scroll){var max=this._calculateMaxScroll();if(this.isAutoScrollEnabled()){for(var arr=[],size=this._getCarouselItemSize(),i=0;i<this._getCarouselItemCount();i++)max>=i*size&&arr.push(i*size);arr.push(max),arr.sort(function(left,right){return left=Math.abs(left-scroll),right=Math.abs(right-scroll),left-right}),arr=arr.filter(function(item,pos){return!pos||item!=arr[pos-1]});var lastScroll=this._lastActiveIndex*size,scrollRatio=Math.abs(scroll-lastScroll)/size;return scrollRatio<=this.getAutoScrollRatio()?lastScroll:scrollRatio>this.getAutoScrollRatio()&&1>scrollRatio&&arr[0]===lastScroll&&arr.length>1?arr[1]:arr[0]}return Math.max(0,Math.min(max,scroll))},_getCarouselItemElements:function(){for(var nodeList=this._element[0].querySelectorAll("ons-carousel-item"),rv=[],i=nodeList.length;i--;)rv.unshift(nodeList[i]);return rv},_scrollTo:function(scroll,options){function normalizeScroll(scroll){var ratio=.35;if(0>scroll)return isOverscrollable?Math.round(scroll*ratio):0;var maxScroll=self._calculateMaxScroll();return scroll>maxScroll?isOverscrollable?maxScroll+Math.round((scroll-maxScroll)*ratio):maxScroll:scroll}options=options||{};var self=this,isOverscrollable=this.isOverscrollable();options.animate?animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(normalizeScroll(scroll))},{duration:.3,timing:"cubic-bezier(.1, .7, .1, 1)"}).play(options.callback):animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(normalizeScroll(scroll))}).play(options.callback)},_calculateMaxScroll:function(){var max=this._getCarouselItemCount()*this._getCarouselItemSize()-this._getElementSize();return Math.ceil(0>max?0:max)},_isOverScroll:function(scroll){return 0>scroll||scroll>this._calculateMaxScroll()?!0:!1},_getOverScrollDirection:function(){return this._isVertical()?this._scroll<=0?"up":"down":this._scroll<=0?"left":"right"},_scrollToKillOverScroll:function(){var duration=.4;if(this._scroll<0)return animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(0)},{duration:duration,timing:"cubic-bezier(.1, .4, .1, 1)"}).play(),void(this._scroll=0);var maxScroll=this._calculateMaxScroll();return maxScroll<this._scroll?(animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(maxScroll)},{duration:duration,timing:"cubic-bezier(.1, .4, .1, 1)"}).play(),void(this._scroll=maxScroll)):void 0},_getCarouselItemCount:function(){return this._getCarouselItemElements().length},refresh:function(){if(0!==this._getCarouselItemSize()){if(this._mixin(this._isVertical()?VerticalModeTrait:HorizontalModeTrait),this._layoutCarouselItems(),this._lastState&&this._lastState.width>0){var scroll=this._scroll;this._isOverScroll(scroll)?this._scrollToKillOverScroll():(this.isAutoScrollEnabled()&&(scroll=this._normalizeScrollPosition(scroll)),this._scrollTo(scroll))}this._saveLastState(),this.emit("refresh",{carousel:this})}},first:function(){this.setActiveCarouselItemIndex(0)},last:function(){this.setActiveCarouselItemIndex(Math.max(this._getCarouselItemCount()-1,0))},_destroy:function(){this.emit("destroy"),this._hammer.off("drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown",this._bindedOnDrag),this._hammer.off("dragend",this._bindedOnDragEnd),angular.element(window).off("resize",this._bindedOnResize),this._element=this._scope=this._attrs=null}});return MicroEvent.mixin(CarouselView),CarouselView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("DialogView",["$onsen","DialogAnimator","IOSDialogAnimator","AndroidDialogAnimator","SlideDialogAnimator",function($onsen,DialogAnimator,IOSDialogAnimator,AndroidDialogAnimator,SlideDialogAnimator){var DialogView=Class.extend({init:function(scope,element,attrs){if(this._scope=scope,this._element=element,this._attrs=attrs,this._element.css("display","none"),this._dialog=angular.element(element[0].querySelector(".dialog")),this._mask=angular.element(element[0].querySelector(".dialog-mask")),this._dialog.css("z-index",20001),this._mask.css("z-index",2e4),this._mask.on("click",this._cancel.bind(this)),this._visible=!1,this._doorLock=new DoorLock,this._animation=DialogView._animatorDict["undefined"!=typeof attrs.animation?attrs.animation:"default"],!this._animation)throw new Error("No such animation: "+attrs.animation);this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)),this._scope.$on("$destroy",this._destroy.bind(this))},getDeviceBackButtonHandler:function(){return this._deviceBackButtonHandler},show:function(options){options=options||{};var cancel=!1,callback=options.callback||function(){};this.emit("preshow",{dialog:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;this._element.css("display","block"),this._mask.css("opacity",1),options.animation&&(animation=DialogView._animatorDict[options.animation]),animation.show(this,function(){this._visible=!0,unlock(),this.emit("postshow",{dialog:this}),callback()}.bind(this))}.bind(this))},hide:function(options){options=options||{};var cancel=!1,callback=options.callback||function(){};this.emit("prehide",{dialog:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;options.animation&&(animation=DialogView._animatorDict[options.animation]),animation.hide(this,function(){this._element.css("display","none"),this._visible=!1,unlock(),this.emit("posthide",{dialog:this}),callback()}.bind(this))}.bind(this))},isShown:function(){return this._visible},destroy:function(){this._parentScope?(this._parentScope.$destroy(),this._parentScope=null):this._scope.$destroy()},_destroy:function(){this.emit("destroy"),this._element.remove(),this._deviceBackButtonHandler.destroy(),this._mask.off(),this._deviceBackButtonHandler=this._scope=this._attrs=this._element=this._dialog=this._mask=null},setDisabled:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this._element.attr("disabled",!0):this._element.removeAttr("disabled")},isDisabled:function(){return this._element[0].hasAttribute("disabled")},setCancelable:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this._element.attr("cancelable",!0):this._element.removeAttr("cancelable")},isCancelable:function(){return this._element[0].hasAttribute("cancelable")},_cancel:function(){this.isCancelable()&&this.hide({callback:function(){this.emit("cancel")}.bind(this)})},_onDeviceBackButton:function(event){this.isCancelable()?this._cancel.bind(this)():event.callParentHandler()}});return DialogView._animatorDict={"default":$onsen.isAndroid()?new AndroidDialogAnimator:new IOSDialogAnimator,fade:$onsen.isAndroid()?new AndroidDialogAnimator:new IOSDialogAnimator,slide:new SlideDialogAnimator,none:new DialogAnimator},DialogView.registerAnimator=function(name,animator){if(!(animator instanceof DialogAnimator))throw new Error('"animator" param must be an instance of DialogAnimator');this._animatorDict[name]=animator},MicroEvent.mixin(DialogView),DialogView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("DialogAnimator",function(){var DialogAnimator=Class.extend({show:function(dialog,callback){callback()},hide:function(dialog,callback){callback()}});return DialogAnimator})}(),function(){"use strict";var module=angular.module("onsen");module.factory("FadePopoverAnimator",["PopoverAnimator",function(PopoverAnimator){var FadePopoverAnimator=PopoverAnimator.extend({timing:"cubic-bezier(.1, .7, .4, 1)",duration:.2,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(popover,callback){var pop=popover._element[0].querySelector(".popover"),mask=popover._element[0].querySelector(".popover-mask");animit.runAll(animit(mask).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(pop).queue({transform:"scale3d(1.3, 1.3, 1.0)",opacity:0}).queue({transform:"scale3d(1.0, 1.0, 1.0)",opacity:1},{duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(popover,callback){var pop=popover._element[0].querySelector(".popover"),mask=popover._element[0].querySelector(".popover-mask");animit.runAll(animit(mask).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(pop).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return FadePopoverAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("FadeTransitionAnimator",["NavigatorTransitionAnimator",function(NavigatorTransitionAnimator){var FadeTransitionAnimator=NavigatorTransitionAnimator.extend({push:function(enterPage,leavePage,callback){animit.runAll(animit([enterPage.getPageView().getContentElement(),enterPage.getPageView().getBackgroundElement()]).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:.4,timing:"linear"}).resetStyle().queue(function(done){callback(),done()}),animit(enterPage.getPageView().getToolbarElement()).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:.4,timing:"linear"}).resetStyle())},pop:function(enterPage,leavePage,callback){animit.runAll(animit([leavePage.getPageView().getContentElement(),leavePage.getPageView().getBackgroundElement()]).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:.4,timing:"linear"}).queue(function(done){callback(),done()}),animit(leavePage.getPageView().getToolbarElement()).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:.4,timing:"linear"}))}});return FadeTransitionAnimator}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("GenericView",["$onsen",function($onsen){var GenericView=Class.extend({init:function(scope,element,attrs){this._element=element,this._scope=scope}});return MicroEvent.mixin(GenericView),GenericView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("IOSAlertDialogAnimator",["DialogAnimator",function(DialogAnimator){var IOSAlertDialogAnimator=DialogAnimator.extend({timing:"cubic-bezier(.1, .7, .4, 1)",duration:.2,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.3, 1.3, 1.0)",opacity:0},duration:0}).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{opacity:1},duration:0}).queue({css:{opacity:0},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return IOSAlertDialogAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("IOSDialogAnimator",["DialogAnimator",function(DialogAnimator){var IOSDialogAnimator=DialogAnimator.extend({timing:"ease-in-out",duration:.3,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, 300%, 0)"},duration:0}).queue({css:{transform:"translate3d(-50%, -50%, 0)"},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -50%, 0)"},duration:0}).queue({css:{transform:"translate3d(-50%, 300%, 0)"},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return IOSDialogAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("IOSSlideTransitionAnimator",["NavigatorTransitionAnimator","PageView",function(NavigatorTransitionAnimator,PageView){var IOSSlideTransitionAnimator=NavigatorTransitionAnimator.extend({backgroundMask:angular.element('<div style="position: absolute; width: 100%;height: 100%; background-color: black; opacity: 0;"></div>'),_decompose:function(page){function excludeBackButtonLabel(elements){for(var result=[],i=0;i<elements.length;i++)result.push("ons-back-button"===elements[i].nodeName.toLowerCase()?elements[i].querySelector(".ons-back-button__icon"):elements[i]);return result}var left=page.getPageView().getToolbarLeftItemsElement(),right=page.getPageView().getToolbarRightItemsElement(),other=[].concat(0===left.children.length?left:excludeBackButtonLabel(left.children)).concat(0===right.children.length?right:excludeBackButtonLabel(right.children)),pageLabels=[page.getPageView().getToolbarCenterItemsElement(),page.getPageView().getToolbarBackButtonLabelElement()];return{pageLabels:pageLabels,other:other,content:page.getPageView().getContentElement(),background:page.getPageView().getBackgroundElement(),toolbar:page.getPageView().getToolbarElement(),bottomToolbar:page.getPageView().getBottomToolbarElement()}},_shouldAnimateToolbar:function(enterPage,leavePage){var bothPageHasToolbar=enterPage.getPageView().hasToolbarElement()&&leavePage.getPageView().hasToolbarElement(),noAndroidLikeToolbar=!angular.element(enterPage.getPageView().getToolbarElement()).hasClass("navigation-bar--android")&&!angular.element(leavePage.getPageView().getToolbarElement()).hasClass("navigation-bar--android");return bothPageHasToolbar&&noAndroidLikeToolbar},push:function(enterPage,leavePage,callback){var mask=this.backgroundMask.remove();leavePage.element[0].parentNode.insertBefore(mask[0],leavePage.element[0].nextSibling);var enterPageDecomposition=this._decompose(enterPage),leavePageDecomposition=this._decompose(leavePage),delta=function(){var rect=leavePage.element[0].getBoundingClientRect();return Math.round((rect.right-rect.left)/2*.6)}(),maskClear=animit(mask[0]).queue({opacity:0,transform:"translate3d(0, 0, 0)"}).queue({opacity:.1},{duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle().queue(function(done){mask.remove(),done()}),shouldAnimateToolbar=this._shouldAnimateToolbar(enterPage,leavePage);shouldAnimateToolbar?(enterPage.element.css({zIndex:"auto"}),leavePage.element.css({zIndex:"auto"}),animit.runAll(maskClear,animit([enterPageDecomposition.content,enterPageDecomposition.bottomToolbar,enterPageDecomposition.background]).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:0}).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(enterPageDecomposition.toolbar).queue({css:{background:"none",backgroundColor:"rgba(0, 0, 0, 0)",borderColor:"rgba(0, 0, 0, 0)"},duration:0}).wait(.3).resetStyle({duration:.1,transition:"background-color 0.1s linear, border-color 0.1s linear"}),animit(enterPageDecomposition.pageLabels).queue({css:{transform:"translate3d("+delta+"px, 0, 0)",opacity:0},duration:0}).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(enterPageDecomposition.other).queue({css:{opacity:0},duration:0}).queue({css:{opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit([leavePageDecomposition.content,leavePageDecomposition.bottomToolbar,leavePageDecomposition.background]).queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).queue({css:{transform:"translate3D(-25%, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle().queue(function(done){enterPage.element.css({zIndex:""}),leavePage.element.css({zIndex:""}),callback(),done()}),animit(leavePageDecomposition.pageLabels).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3d(-"+delta+"px, 0, 0)",opacity:0},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(leavePageDecomposition.other).queue({css:{opacity:1},duration:0}).queue({css:{opacity:0},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle())):animit.runAll(maskClear,animit(enterPage.element[0]).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:0}).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).queue({css:{transform:"translate3D(-25%, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle().queue(function(done){callback(),done()}))},pop:function(enterPage,leavePage,done){var mask=this.backgroundMask.remove();enterPage.element[0].parentNode.insertBefore(mask[0],enterPage.element[0].nextSibling);var enterPageDecomposition=this._decompose(enterPage),leavePageDecomposition=this._decompose(leavePage),delta=function(){var rect=leavePage.element[0].getBoundingClientRect();return Math.round((rect.right-rect.left)/2*.6)}(),maskClear=animit(mask[0]).queue({opacity:.1,transform:"translate3d(0, 0, 0)"}).queue({opacity:0},{duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle().queue(function(done){mask.remove(),done()}),shouldAnimateToolbar=this._shouldAnimateToolbar(enterPage,leavePage);shouldAnimateToolbar?(enterPage.element.css({zIndex:"auto"}),leavePage.element.css({zIndex:"auto"}),animit.runAll(maskClear,animit([enterPageDecomposition.content,enterPageDecomposition.bottomToolbar,enterPageDecomposition.background]).queue({css:{transform:"translate3D(-25%, 0px, 0px)",opacity:.9},duration:0}).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(enterPageDecomposition.pageLabels).queue({css:{transform:"translate3d(-"+delta+"px, 0, 0)",opacity:0},duration:0}).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(enterPageDecomposition.toolbar).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(enterPageDecomposition.other).queue({css:{opacity:0},duration:0}).queue({css:{opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit([leavePageDecomposition.content,leavePageDecomposition.bottomToolbar,leavePageDecomposition.background]).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).wait(0).queue(function(finish){enterPage.element.css({zIndex:""}),leavePage.element.css({zIndex:""}),done(),finish()}),animit(leavePageDecomposition.other).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3d(0, 0, 0)",opacity:0},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}),animit(leavePageDecomposition.toolbar).queue({css:{background:"none",backgroundColor:"rgba(0, 0, 0, 0)",borderColor:"rgba(0, 0, 0, 0)"},duration:0}),animit(leavePageDecomposition.pageLabels).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3d("+delta+"px, 0, 0)",opacity:0},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}))):animit.runAll(maskClear,animit(enterPage.element[0]).queue({css:{transform:"translate3D(-25%, 0px, 0px)",opacity:.9},duration:0}).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(finish){done(),finish()}))}});return IOSSlideTransitionAnimator}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("LazyRepeatView",["$onsen","$document","$compile",function($onsen,$document,$compile){var LazyRepeatView=Class.extend({init:function(scope,element,attrs,linker){if(this._element=element,this._scope=scope,this._attrs=attrs,this._linker=linker,this._parentElement=element.parent(),this._pageContent=this._findPageContent(),!this._pageContent)throw new Error("ons-lazy-repeat must be a descendant of an <ons-page> object.");this._itemHeightSum=[],this._maxIndex=0,this._doorLock=new DoorLock,this._delegate=this._getDelegate(),this._renderedElements={},this._addEventListeners(),this._scope.$watch(this._countItems.bind(this),this._onChange.bind(this)),this._scope.$on("$destroy",this._destroy.bind(this)),this._onChange()},_getDelegate:function(){var delegate=this._scope.$eval(this._attrs.onsLazyRepeat);return"undefined"==typeof delegate&&(delegate=eval(this._attrs.onsLazyRepeat)),delegate},_countItems:function(){return this._delegate.countItems()},_getItemHeight:function(i){return this._delegate.calculateItemHeight(i)},_getTopOffset:function(){return this._parentElement[0].getBoundingClientRect().top},_render:function(){var items=this._getItemsInView(),keep={};this._parentElement.css("height",this._itemHeightSum[this._maxIndex]+"px");for(var i=0,l=items.length;l>i;i++){var _item=items[i];this._renderElement(_item),keep[_item.index]=!0}for(var key in this._renderedElements)this._renderedElements.hasOwnProperty(key)&&!keep.hasOwnProperty(key)&&this._removeElement(key)},_isRendered:function(i){return this._renderedElements.hasOwnProperty(i)},_renderElement:function(item){if(this._isRendered(item.index)){var currentItem=this._renderedElements[item.index];return void(this._delegate.configureItemScope&&this._delegate.configureItemScope(item.index,currentItem.scope))}var childScope=this._scope.$new();this._addSpecialProperties(item.index,childScope),this._linker(childScope,function(clone){this._delegate.configureItemScope?this._delegate.configureItemScope(item.index,childScope):this._delegate.createItemContent&&(clone.append(this._delegate.createItemContent(item.index)),$compile(clone[0].firstChild)(childScope)),this._parentElement.append(clone),clone.css({position:"absolute",top:item.top+"px",left:"0px",right:"0px",display:"none"});var element={element:clone,scope:childScope};this._scope.$evalAsync(function(){clone.css("display","block")}),this._renderedElements[item.index]=element}.bind(this))},_removeElement:function(i){if(this._isRendered(i)){var element=this._renderedElements[i];this._delegate.destroyItemScope?this._delegate.destroyItemScope(i,element.scope):this._delegate.destroyItemContent&&this._delegate.destroyItemContent(i,element.element.children()[0]),element.element.remove(),element.scope.$destroy(),element.element=element.scope=null,delete this._renderedElements[i]}},_removeAllElements:function(){for(var key in this._renderedElements)this._removeElement.hasOwnProperty(key)&&this._removeElement(key)},_calculateStartIndex:function(current){for(var start=0,end=this._maxIndex;;){var middle=Math.floor((start+end)/2),value=current+this._itemHeightSum[middle];if(start>end)return 0;if(value>=0&&value-this._getItemHeight(middle)<0)return middle;isNaN(value)||value>=0?end=middle-1:start=middle+1}},_getItemsInView:function(){var topOffset=this._getTopOffset(),topPosition=topOffset,cnt=this._countItems(),startIndex=this._calculateStartIndex(topPosition);startIndex=Math.max(startIndex-30,0),startIndex>0&&(topPosition+=this._itemHeightSum[startIndex-1]),cnt<this._itemHeightSum.length&&(this._itemHeightSum=new Array(cnt),this._maxIndex=cnt-1);for(var items=[],i=startIndex;cnt>i&&topPosition<4*window.innerHeight;i++){var h=this._getItemHeight(i);i>=this._itemHeightSum.length&&(this._itemHeightSum=this._itemHeightSum.concat(new Array(100))),this._itemHeightSum[i]=i>0?this._itemHeightSum[i-1]+h:h,this._maxIndex=Math.max(i,this._maxIndex),items.push({index:i,top:topPosition-topOffset}),topPosition+=h}return items},_addSpecialProperties:function(i,scope){scope.$index=i,scope.$first=0===i,scope.$last=i===this._countItems()-1,scope.$middle=!scope.$first&&!scope.$last,scope.$even=i%2===0,scope.$odd=!scope.$even},_onChange:function(){this._doorLock._waitList.length>0||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock();setTimeout(function(){unlock()},200),this._render()}.bind(this))},_findPageContent:function(){for(var e=this._element[0];e.parentNode&&(e=e.parentNode,!(e.className&&e.className.split(/\s+/).indexOf("page__content")>=0)););return e},_addEventListeners:function(){this._boundOnChange=this._onChange.bind(this),this._pageContent.addEventListener("scroll",this._boundOnChange,!0),$document[0].addEventListener("resize",this._boundOnChange,!0)},_removeEventListeners:function(){this._pageContent.removeEventListener("scroll",this._boundOnChange,!0),$document[0].removeEventListener("resize",this._boundOnChange,!0)},_destroy:function(){this._removeEventListeners(),this._removeAllElements(),this._parentElement=this._renderedElements=this._element=this._scope=this._attrs=null}});return LazyRepeatView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("LiftTransitionAnimator",["NavigatorTransitionAnimator",function(NavigatorTransitionAnimator){var LiftTransitionAnimator=NavigatorTransitionAnimator.extend({backgroundMask:angular.element('<div style="position: absolute; width: 100%;height: 100%; background-color: black;"></div>'),push:function(enterPage,leavePage,callback){var mask=this.backgroundMask.remove();leavePage.element[0].parentNode.insertBefore(mask[0],leavePage.element[0]);var maskClear=animit(mask[0]).wait(.6).queue(function(done){mask.remove(),done()});animit.runAll(maskClear,animit(enterPage.element[0]).queue({css:{transform:"translate3D(0, 100%, 0)"},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).wait(.2).resetStyle().queue(function(done){callback(),done()}),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3D(0, -10%, 0)",opacity:.9},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}))},pop:function(enterPage,leavePage,callback){var mask=this.backgroundMask.remove();enterPage.element[0].parentNode.insertBefore(mask[0],enterPage.element[0]),animit.runAll(animit(mask[0]).wait(.4).queue(function(done){mask.remove(),done()}),animit(enterPage.element[0]).queue({css:{transform:"translate3D(0, -10%, 0)",opacity:.9},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle().wait(.4).queue(function(done){callback(),done()}),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).queue({css:{transform:"translate3D(0, 100%, 0)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}))}});return LiftTransitionAnimator}])}(),function(){"use strict;";var module=angular.module("onsen"); module.factory("ModalView",["$onsen","$rootScope",function($onsen,$rootScope){var ModalView=Class.extend({_element:void 0,_scope:void 0,init:function(scope,element){this._scope=scope,this._element=element;var pageView=$rootScope.ons.findParentComponentUntil("ons-page",this._element);pageView&&(this._pageContent=angular.element(pageView._element[0].querySelector(".page__content"))),this._scope.$on("$destroy",this._destroy.bind(this)),this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)),this.hide()},getDeviceBackButtonHandler:function(){return this._deviceBackButtonHandler},show:function(){this._element.css("display","table")},_isVisible:function(){return this._element[0].clientWidth>0},_onDeviceBackButton:function(){},hide:function(){this._element.css("display","none")},toggle:function(){return this._isVisible()?this.hide.apply(this,arguments):this.show.apply(this,arguments)},_destroy:function(){this.emit("destroy",{page:this}),this._deviceBackButtonHandler.destroy(),this._element=this._scope=null}});return MicroEvent.mixin(ModalView),ModalView}])}(),function(){"use strict;";var module=angular.module("onsen"),NavigatorPageObject=Class.extend({init:function(params){this.page=params.page,this.name=params.page,this.element=params.element,this.pageScope=params.pageScope,this.options=params.options,this.navigator=params.navigator,this._blockEvents=function(event){(this.navigator._isPopping||this.navigator._isPushing)&&(event.preventDefault(),event.stopPropagation())}.bind(this),this.element.on(this._pointerEvents,this._blockEvents)},_pointerEvents:"touchstart touchend touchmove click",getPageView:function(){if(!this._pageView&&(this._pageView=this.element.inheritedData("ons-page"),!this._pageView))throw new Error("Fail to fetch PageView from ons-page element.");return this._pageView},destroy:function(){this.pageScope.$destroy(),this.element.off(this._pointerEvents,this._blockEvents),this.element.remove(),this.element=null,this._pageView=null,this.pageScope=null,this.options=null;var index=this.navigator.pages.indexOf(this);-1!==index&&this.navigator.pages.splice(index,1),this.navigator=null}});module.factory("NavigatorView",["$http","$parse","$templateCache","$compile","$onsen","$timeout","SimpleSlideTransitionAnimator","NavigatorTransitionAnimator","LiftTransitionAnimator","NullTransitionAnimator","IOSSlideTransitionAnimator","FadeTransitionAnimator",function($http,$parse,$templateCache,$compile,$onsen,$timeout,SimpleSlideTransitionAnimator,NavigatorTransitionAnimator,LiftTransitionAnimator,NullTransitionAnimator,IOSSlideTransitionAnimator,FadeTransitionAnimator){var NavigatorView=Class.extend({_element:void 0,_attrs:void 0,pages:void 0,_scope:void 0,_doorLock:void 0,_profiling:!1,init:function(scope,element,attrs){this._element=element||angular.element(window.document.body),this._scope=scope||this._element.scope(),this._attrs=attrs,this._doorLock=new DoorLock,this.pages=[],this._isPopping=this._isPushing=!1,this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)),this._scope.$on("$destroy",this._destroy.bind(this))},_destroy:function(){this.emit("destroy"),this.pages.forEach(function(page){page.destroy()}),this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this._element=this._scope=this._attrs=null},_onDeviceBackButton:function(event){this.pages.length>1?this._scope.$evalAsync(this.popPage.bind(this)):event.callParentHandler()},_normalizePageElement:function(element){for(var i=0;i<element.length;i++)if(1===element[i].nodeType)return angular.element(element[i]);throw new Error("invalid state")},_createPageElementAndLinkFunction:function(templateHTML,pageScope,done){function safeApply(scope){var phase=scope.$root.$$phase;"$apply"!==phase&&"$digest"!==phase&&scope.$apply()}var div=document.createElement("div");div.innerHTML=templateHTML.trim();var pageElement=angular.element(div),hasPage=1===div.childElementCount&&"ons-page"===div.childNodes[0].nodeName.toLowerCase();if(!hasPage)throw new Error('You can not supply no "ons-page" element to "ons-navigator".');pageElement=angular.element(div.childNodes[0]);var link=$compile(pageElement);return{element:pageElement,link:function(){link(pageScope),safeApply(pageScope)}}},insertPage:function(index,page,options){if(options=options||{},options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);if(index===this.pages.length)return this.pushPage.apply(this,[].slice.call(arguments,1));this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock();$onsen.getPageHTMLAsync(page).then(function(templateHTML){var pageScope=this._createPageScope(),object=this._createPageElementAndLinkFunction(templateHTML,pageScope),element=object.element,link=object.link;element=this._normalizePageElement(element);var pageObject=this._createPageObject(page,element,pageScope,options);this.pages.length>0?(index=normalizeIndex(index),this._element[0].insertBefore(element[0],this.pages[index]?this.pages[index].element[0]:null),this.pages.splice(index,0,pageObject),link(),setTimeout(function(){this.getCurrentPage()!==pageObject&&element.css("display","none"),unlock(),element=null}.bind(this),1e3/60)):(this._element.append(element),this.pages.push(pageObject),link(),unlock(),element=null)}.bind(this),function(){throw unlock(),new Error("Page is not found: "+page)})}.bind(this));var normalizeIndex=function(index){return 0>index&&(index=this.pages.length+index),index}.bind(this)},pushPage:function(page,options){if(this._profiling&&console.time("pushPage"),options=options||{},!options.cancelIfRunning||!this._isPushing){if(options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);this._emitPrePushEvent()||this._doorLock.waitUnlock(function(){this._pushPage(page,options)}.bind(this))}},_pushPage:function(page,options){var unlock=this._doorLock.lock(),done=function(){unlock(),this._profiling&&console.timeEnd("pushPage")};$onsen.getPageHTMLAsync(page).then(function(templateHTML){var pageScope=this._createPageScope(),object=this._createPageElementAndLinkFunction(templateHTML,pageScope);setImmediate(function(){this._pushPageDOM(page,object.element,object.link,pageScope,options,done),object=null}.bind(this))}.bind(this),function(){throw done(),new Error("Page is not found: "+page)}.bind(this))},getDeviceBackButtonHandler:function(){return this._deviceBackButtonHandler},_getAnimatorOption:function(options,defaultAnimator){var animator=null;if(options.animation instanceof NavigatorTransitionAnimator)return options.animation;if("string"==typeof options.animation&&(animator=NavigatorView._transitionAnimatorDict[options.animation]),!animator&&this._element.attr("animation")&&(animator=NavigatorView._transitionAnimatorDict[this._element.attr("animation")]),animator||(animator=defaultAnimator||NavigatorView._transitionAnimatorDict["default"]),!(animator instanceof NavigatorTransitionAnimator))throw new Error('"animator" is not an instance of NavigatorTransitionAnimator.');return animator},_createPageScope:function(){return this._scope.$new()},_createPageObject:function(page,element,pageScope,options){return options.animator=this._getAnimatorOption(options),new NavigatorPageObject({page:page,element:element,pageScope:pageScope,options:options,navigator:this})},_pushPageDOM:function(page,element,link,pageScope,options,unlock){this._profiling&&console.time("pushPageDOM"),unlock=unlock||function(){},options=options||{},element=this._normalizePageElement(element);var pageObject=this._createPageObject(page,element,pageScope,options),event={enterPage:pageObject,leavePage:this.pages[this.pages.length-1],navigator:this};this.pages.push(pageObject);var done=function(){this.pages[this.pages.length-2]&&this.pages[this.pages.length-2].element.css("display","none"),this._profiling&&console.timeEnd("pushPageDOM"),this._isPushing=!1,unlock(),this.emit("postpush",event),"function"==typeof options.onTransitionEnd&&options.onTransitionEnd(),element=null}.bind(this);if(this._isPushing=!0,this.pages.length>1){var leavePage=this.pages.slice(-2)[0],enterPage=this.pages.slice(-1)[0];this._element.append(element),link(),options.animator.push(enterPage,leavePage,done),element=null}else this._element.append(element),link(),done(),element=null},_emitPrePushEvent:function(){var isCanceled=!1,prePushEvent={navigator:this,currentPage:this.getCurrentPage(),cancel:function(){isCanceled=!0}};return this.emit("prepush",prePushEvent),isCanceled},_emitPrePopEvent:function(){var isCanceled=!1,leavePage=this.getCurrentPage(),prePopEvent={navigator:this,currentPage:leavePage,leavePage:leavePage,enterPage:this.pages[this.pages.length-2],cancel:function(){isCanceled=!0}};return this.emit("prepop",prePopEvent),isCanceled},popPage:function(options){options=options||{},options.cancelIfRunning&&this._isPopping||this._doorLock.waitUnlock(function(){if(this.pages.length<=1)throw new Error("NavigatorView's page stack is empty.");this._emitPrePopEvent()||this._popPage(options)}.bind(this))},_popPage:function(options){var unlock=this._doorLock.lock(),leavePage=this.pages.pop();this.pages[this.pages.length-1]&&this.pages[this.pages.length-1].element.css("display","block");var enterPage=this.pages[this.pages.length-1],event={leavePage:leavePage,enterPage:this.pages[this.pages.length-1],navigator:this},callback=function(){leavePage.destroy(),this._isPopping=!1,unlock(),this.emit("postpop",event),event.leavePage=null,"function"==typeof options.onTransitionEnd&&options.onTransitionEnd()}.bind(this);this._isPopping=!0;var animator=this._getAnimatorOption(options,leavePage.options.animator);animator.pop(enterPage,leavePage,callback)},replacePage:function(page,options){options=options||{};var onTransitionEnd=options.onTransitionEnd||function(){};options.onTransitionEnd=function(){this.pages.length>1&&this.pages[this.pages.length-2].destroy(),onTransitionEnd()}.bind(this),this.pushPage(page,options)},resetToPage:function(page,options){options=options||{},options.animator||options.animation||(options.animation="none");var onTransitionEnd=options.onTransitionEnd||function(){},self=this;options.onTransitionEnd=function(){for(;self.pages.length>1;)self.pages.shift().destroy();onTransitionEnd()},this.pushPage(page,options)},getCurrentPage:function(){return this.pages[this.pages.length-1]},getPages:function(){return this.pages},canPopPage:function(){return this.pages.length>1}});return NavigatorView._transitionAnimatorDict={"default":$onsen.isAndroid()?new SimpleSlideTransitionAnimator:new IOSSlideTransitionAnimator,slide:$onsen.isAndroid()?new SimpleSlideTransitionAnimator:new IOSSlideTransitionAnimator,simpleslide:new SimpleSlideTransitionAnimator,lift:new LiftTransitionAnimator,fade:new FadeTransitionAnimator,none:new NullTransitionAnimator},NavigatorView.registerTransitionAnimator=function(name,animator){if(!(animator instanceof NavigatorTransitionAnimator))throw new Error('"animator" param must be an instance of NavigatorTransitionAnimator');this._transitionAnimatorDict[name]=animator},MicroEvent.mixin(NavigatorView),NavigatorView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("NavigatorTransitionAnimator",function(){var NavigatorTransitionAnimator=Class.extend({push:function(enterPage,leavePage,callback){callback()},pop:function(enterPage,leavePage,callback){callback()}});return NavigatorTransitionAnimator})}(),function(){"use strict;";var module=angular.module("onsen");module.factory("NullTransitionAnimator",["NavigatorTransitionAnimator",function(NavigatorTransitionAnimator){var NullTransitionAnimator=NavigatorTransitionAnimator.extend({});return NullTransitionAnimator}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("OverlaySlidingMenuAnimator",["SlidingMenuAnimator",function(SlidingMenuAnimator){var OverlaySlidingMenuAnimator=SlidingMenuAnimator.extend({_blackMask:void 0,_isRight:!1,_element:!1,_menuPage:!1,_mainPage:!1,_width:!1,_duration:!1,setup:function(element,mainPage,menuPage,options){options=options||{},this._width=options.width||"90%",this._isRight=!!options.isRight,this._element=element,this._mainPage=mainPage,this._menuPage=menuPage,this._duration=.4,menuPage.css("box-shadow","0px 0 10px 0px rgba(0, 0, 0, 0.2)"),menuPage.css({width:options.width,display:"none",zIndex:2}),menuPage.css("-webkit-transform","translate3d(0px, 0px, 0px)"),mainPage.css({zIndex:1}),menuPage.css(this._isRight?{right:"-"+options.width,left:"auto"}:{right:"auto",left:"-"+options.width}),this._blackMask=angular.element("<div></div>").css({backgroundColor:"black",top:"0px",left:"0px",right:"0px",bottom:"0px",position:"absolute",display:"none",zIndex:0}),element.prepend(this._blackMask)},onResized:function(options){if(this._menuPage.css("width",options.width),this._menuPage.css(this._isRight?{right:"-"+options.width,left:"auto"}:{right:"auto",left:"-"+options.width}),options.isOpened){var max=this._menuPage[0].clientWidth,menuStyle=this._generateMenuPageStyle(max);animit(this._menuPage[0]).queue(menuStyle).play()}},destroy:function(){this._blackMask&&(this._blackMask.remove(),this._blackMask=null),this._mainPage.removeAttr("style"),this._menuPage.removeAttr("style"),this._element=this._mainPage=this._menuPage=null},openMenu:function(callback,instant){var duration=instant===!0?0:this._duration;this._menuPage.css("display","block"),this._blackMask.css("display","block");var max=this._menuPage[0].clientWidth,menuStyle=this._generateMenuPageStyle(max),mainPageStyle=this._generateMainPageStyle(max);setTimeout(function(){animit(this._mainPage[0]).queue(mainPageStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){callback(),done()}).play(),animit(this._menuPage[0]).queue(menuStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).play()}.bind(this),1e3/60)},closeMenu:function(callback,instant){var duration=instant===!0?0:this._duration;this._blackMask.css({display:"block"});var menuPageStyle=this._generateMenuPageStyle(0),mainPageStyle=this._generateMainPageStyle(0);setTimeout(function(){animit(this._mainPage[0]).queue(mainPageStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){this._menuPage.css("display","none"),callback(),done()}.bind(this)).play(),animit(this._menuPage[0]).queue(menuPageStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).play()}.bind(this),1e3/60)},translateMenu:function(options){this._menuPage.css("display","block"),this._blackMask.css({display:"block"});var menuPageStyle=this._generateMenuPageStyle(Math.min(options.maxDistance,options.distance)),mainPageStyle=this._generateMainPageStyle(Math.min(options.maxDistance,options.distance));delete mainPageStyle.opacity,animit(this._menuPage[0]).queue(menuPageStyle).play(),Object.keys(mainPageStyle).length>0&&animit(this._mainPage[0]).queue(mainPageStyle).play()},_generateMenuPageStyle:function(distance){var x=(this._menuPage[0].clientWidth,this._isRight?-distance:distance),transform="translate3d("+x+"px, 0, 0)";return{transform:transform,"box-shadow":0===distance?"none":"0px 0 10px 0px rgba(0, 0, 0, 0.2)"}},_generateMainPageStyle:function(distance){var max=this._menuPage[0].clientWidth,opacity=1-.1*distance/max;return{opacity:opacity}},copy:function(){return new OverlaySlidingMenuAnimator}});return OverlaySlidingMenuAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("PageView",["$onsen","$parse",function($onsen,$parse){var PageView=Class.extend({_registeredToolbarElement:!1,_registeredBottomToolbarElement:!1,_nullElement:window.document.createElement("div"),_toolbarElement:null,_bottomToolbarElement:null,init:function(scope,element,attrs){this._scope=scope,this._element=element,this._attrs=attrs,this._registeredToolbarElement=!1,this._registeredBottomToolbarElement=!1,this._nullElement=window.document.createElement("div"),this._toolbarElement=angular.element(this._nullElement),this._bottomToolbarElement=angular.element(this._nullElement),this._clearListener=scope.$on("$destroy",this._destroy.bind(this)),this._userDeviceBackButtonListener=angular.noop,(this._attrs.ngDeviceBackbutton||this._attrs.onDeviceBackbutton)&&(this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)))},_onDeviceBackButton:function($event){if(this._userDeviceBackButtonListener($event),this._attrs.ngDeviceBackbutton&&$parse(this._attrs.ngDeviceBackbutton)(this._scope,{$event:$event}),this._attrs.onDeviceBackbutton){var lastEvent=window.$event;window.$event=$event,new Function(this._attrs.onDeviceBackbutton)(),window.$event=lastEvent}},setDeviceBackButtonHandler:function(callback){this._deviceBackButtonHandler||(this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this))),this._userDeviceBackButtonListener=callback},getDeviceBackButtonHandler:function(){return this._deviceBackButtonHandler||null},registerToolbar:function(element){if(this._registeredToolbarElement)throw new Error("This page's toolbar is already registered.");angular.element(this.getContentElement()).attr("no-status-bar-fill",""),element.remove();var statusFill=this._element[0].querySelector(".page__status-bar-fill");statusFill?angular.element(statusFill).after(element):this._element.prepend(element),this._toolbarElement=element,this._registeredToolbarElement=!0},registerBottomToolbar:function(element){if(this._registeredBottomToolbarElement)throw new Error("This page's bottom-toolbar is already registered.");element.remove(),this._bottomToolbarElement=element,this._registeredBottomToolbarElement=!0;var fill=angular.element(document.createElement("div"));fill.addClass("page__bottom-bar-fill"),fill.css({width:"0px",height:"0px"}),this._element.prepend(fill),this._element.append(element)},registerExtraElement:function(element){this._extraElement||(this._extraElement=angular.element("<div></div>"),this._extraElement.addClass("page__extra"),this._extraElement.css({"z-index":"10001"}),this._element.append(this._extraElement)),this._extraElement.append(element.remove())},hasToolbarElement:function(){return!!this._registeredToolbarElement},hasBottomToolbarElement:function(){return!!this._registeredBottomToolbarElement},getContentElement:function(){for(var i=0;i<this._element.length;i++)if(this._element[i].querySelector){var content=this._element[i].querySelector(".page__content");if(content)return content}throw Error('fail to get ".page__content" element.')},getBackgroundElement:function(){for(var i=0;i<this._element.length;i++)if(this._element[i].querySelector){var content=this._element[i].querySelector(".page__background");if(content)return content}throw Error('fail to get ".page__background" element.')},getToolbarElement:function(){return this._toolbarElement[0]||this._nullElement},getBottomToolbarElement:function(){return this._bottomToolbarElement[0]||this._nullElement},getToolbarLeftItemsElement:function(){return this._toolbarElement[0].querySelector(".left")||this._nullElement},getToolbarCenterItemsElement:function(){return this._toolbarElement[0].querySelector(".center")||this._nullElement},getToolbarRightItemsElement:function(){return this._toolbarElement[0].querySelector(".right")||this._nullElement},getToolbarBackButtonLabelElement:function(){return this._toolbarElement[0].querySelector("ons-back-button .back-button__label")||this._nullElement},_destroy:function(){this.emit("destroy",{page:this}),this._deviceBackButtonHandler&&(this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null),this._element=null,this._toolbarElement=null,this._nullElement=null,this._bottomToolbarElement=null,this._extraElement=null,this._scope=null,this._clearListener()}});return MicroEvent.mixin(PageView),PageView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("PopoverView",["$onsen","PopoverAnimator","FadePopoverAnimator",function($onsen,PopoverAnimator,FadePopoverAnimator){var PopoverView=Class.extend({init:function(scope,element,attrs){if(this._element=element,this._scope=scope,this._attrs=attrs,this._mask=angular.element(this._element[0].querySelector(".popover-mask")),this._popover=angular.element(this._element[0].querySelector(".popover")),this._mask.css("z-index",2e4),this._popover.css("z-index",20001),this._element.css("display","none"),attrs.maskColor&&this._mask.css("background-color",attrs.maskColor),this._mask.on("click",this._cancel.bind(this)),this._visible=!1,this._doorLock=new DoorLock,this._animation=PopoverView._animatorDict["undefined"!=typeof attrs.animation?attrs.animation:"fade"],!this._animation)throw new Error("No such animation: "+attrs.animation);this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)),this._onChange=function(){setImmediate(function(){this._currentTarget&&this._positionPopover(this._currentTarget)}.bind(this))}.bind(this),this._popover[0].addEventListener("DOMNodeInserted",this._onChange,!1),this._popover[0].addEventListener("DOMNodeRemoved",this._onChange,!1),window.addEventListener("resize",this._onChange,!1),this._scope.$on("$destroy",this._destroy.bind(this))},_onDeviceBackButton:function(event){this.isCancelable()?this._cancel.bind(this)():event.callParentHandler()},_setDirection:function(direction){if("up"===direction)this._scope.direction=direction,this._scope.arrowPosition="bottom";else if("left"===direction)this._scope.direction=direction,this._scope.arrowPosition="right";else if("down"===direction)this._scope.direction=direction,this._scope.arrowPosition="top";else{if("right"!=direction)throw new Error("Invalid direction.");this._scope.direction=direction,this._scope.arrowPosition="left"}this._scope.$$phase||this._scope.$apply()},_positionPopoverByDirection:function(target,direction){var el=angular.element(this._element[0].querySelector(".popover")),pos=target.getBoundingClientRect(),own=el[0].getBoundingClientRect(),arrow=angular.element(el.children()[1]),offset=14,margin=6,radius=parseInt(window.getComputedStyle(el[0].querySelector(".popover__content")).borderRadius);arrow.css({top:"",left:""});var diff=function(x){return x/2*Math.sqrt(2)-x/2}(parseInt(window.getComputedStyle(arrow[0]).width)),limit=margin+radius+diff;this._setDirection(direction),["left","right"].indexOf(direction)>-1?("left"==direction?el.css("left",pos.right-pos.width-own.width-offset+"px"):el.css("left",pos.right+offset+"px"),el.css("top",pos.bottom-pos.height/2-own.height/2+"px")):("up"==direction?el.css("top",pos.bottom-pos.height-own.height-offset+"px"):el.css("top",pos.bottom+offset+"px"),el.css("left",pos.right-pos.width/2-own.width/2+"px")),own=el[0].getBoundingClientRect(),["left","right"].indexOf(direction)>-1?own.top<margin?(arrow.css("top",Math.max(own.height/2+own.top-margin,limit)+"px"),el.css("top",margin+"px")):own.bottom>window.innerHeight-margin&&(arrow.css("top",Math.min(own.height/2-(window.innerHeight-own.bottom)+margin,own.height-limit)+"px"),el.css("top",window.innerHeight-own.height-margin+"px")):own.left<margin?(arrow.css("left",Math.max(own.width/2+own.left-margin,limit)+"px"),el.css("left",margin+"px")):own.right>window.innerWidth-margin&&(arrow.css("left",Math.min(own.width/2-(window.innerWidth-own.right)+margin,own.width-limit)+"px"),el.css("left",window.innerWidth-own.width-margin+"px"))},_positionPopover:function(target){var directions;directions=this._element.attr("direction")?this._element.attr("direction").split(/\s+/):["up","down","left","right"];for(var position=target.getBoundingClientRect(),scores={left:position.left,right:window.innerWidth-position.right,up:position.top,down:window.innerHeight-position.bottom},orderedDirections=Object.keys(scores).sort(function(a,b){return-(scores[a]-scores[b])}),i=0,l=orderedDirections.length;l>i;i++){var direction=orderedDirections[i];if(directions.indexOf(direction)>-1)return void this._positionPopoverByDirection(target,direction)}},show:function(target,options){if("string"==typeof target?target=document.querySelector(target):target instanceof Event&&(target=target.target),!target)throw new Error("Target undefined");options=options||{};var cancel=!1;this.emit("preshow",{popover:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;this._element.css("display","block"),this._currentTarget=target,this._positionPopover(target),options.animation&&(animation=PopoverView._animatorDict[options.animation]),animation.show(this,function(){this._visible=!0,this._positionPopover(target),unlock(),this.emit("postshow",{popover:this})}.bind(this))}.bind(this))},hide:function(options){options=options||{};var cancel=!1;this.emit("prehide",{popover:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;options.animation&&(animation=PopoverView._animatorDict[options.animation]),animation.hide(this,function(){this._element.css("display","none"),this._visible=!1,unlock(),this.emit("posthide",{popover:this})}.bind(this))}.bind(this))},isShown:function(){return this._visible},destroy:function(){this._parentScope?(this._parentScope.$destroy(),this._parentScope=null):this._scope.$destroy()},_destroy:function(){this.emit("destroy"),this._deviceBackButtonHandler.destroy(),this._popover[0].removeEventListener("DOMNodeInserted",this._onChange,!1),this._popover[0].removeEventListener("DOMNodeRemoved",this._onChange,!1),window.removeEventListener("resize",this._onChange,!1),this._mask.off(),this._mask.remove(),this._popover.remove(),this._element.remove(),this._onChange=this._deviceBackButtonHandler=this._mask=this._popover=this._element=this._scope=null},setCancelable:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this._element.attr("cancelable",!0):this._element.removeAttr("cancelable")},isCancelable:function(){return this._element[0].hasAttribute("cancelable")},_cancel:function(){this.isCancelable()&&this.hide()}});return PopoverView._animatorDict={fade:new FadePopoverAnimator,none:new PopoverAnimator},PopoverView.registerAnimator=function(name,animator){if(!(animator instanceof PopoverAnimator))throw new Error('"animator" param must be an instance of PopoverAnimator');this._animatorDict[name]=animator},MicroEvent.mixin(PopoverView),PopoverView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("PopoverAnimator",function(){var PopoverAnimator=Class.extend({show:function(popover,callback){callback()},hide:function(popover,callback){callback()}});return PopoverAnimator})}(),function(){"use strict";var module=angular.module("onsen");module.factory("PullHookView",["$onsen","$parse",function($onsen,$parse){var PullHookView=Class.extend({STATE_INITIAL:"initial",STATE_PREACTION:"preaction",STATE_ACTION:"action",init:function(scope,element,attrs){if(this._element=element,this._scope=scope,this._attrs=attrs,this._scrollElement=this._createScrollElement(),this._pageElement=this._scrollElement.parent(),!this._pageElement.hasClass("page__content")&&!this._pageElement.hasClass("ons-scroller__content"))throw new Error("<ons-pull-hook> must be a direct descendant of an <ons-page> or an <ons-scroller> element.");this._currentTranslation=0,this._createEventListeners(),this._setState(this.STATE_INITIAL,!0),this._setStyle(),this._scope.$on("$destroy",this._destroy.bind(this))},_createScrollElement:function(){var scrollElement=angular.element("<div>").addClass("scroll"),pageElement=this._element.parent(),children=pageElement.children();return pageElement.append(scrollElement),scrollElement.append(children),scrollElement},_setStyle:function(){var h=this._getHeight();this._element.css({top:"-"+h+"px",height:h+"px",lineHeight:h+"px"})},_onScroll:function(event){var el=this._pageElement[0];el.scrollTop<0&&(el.scrollTop=0)},_generateTranslationTransform:function(scroll){return"translate3d(0px, "+scroll+"px, 0px)"},_onDrag:function(event){if(!this.isDisabled()&&"left"!==event.gesture.direction&&"right"!==event.gesture.direction){var el=this._pageElement[0];if(el.scrollTop=this._startScroll-event.gesture.deltaY,el.scrollTop<window.innerHeight&&"up"!==event.gesture.direction&&event.gesture.preventDefault(),0===this._currentTranslation&&0===this._getCurrentScroll()){this._transitionDragLength=event.gesture.deltaY;var direction=event.gesture.interimDirection;"down"===direction?this._transitionDragLength-=1:this._transitionDragLength+=1}var scroll=event.gesture.deltaY-this._startScroll;scroll=Math.max(scroll,0),this._thresholdHeightEnabled()&&scroll>=this._getThresholdHeight()?(event.gesture.stopDetect(),setImmediate(function(){this._setState(this.STATE_ACTION),this._translateTo(this._getHeight(),{animate:!0}),this._waitForAction(this._onDone.bind(this))}.bind(this))):this._setState(scroll>=this._getHeight()?this.STATE_PREACTION:this.STATE_INITIAL),event.stopPropagation(),this._translateTo(scroll)}},_onDragStart:function(event){this.isDisabled()||(this._startScroll=this._getCurrentScroll())},_onDragEnd:function(event){if(!this.isDisabled()&&this._currentTranslation>0){var scroll=this._currentTranslation;scroll>this._getHeight()?(this._setState(this.STATE_ACTION),this._translateTo(this._getHeight(),{animate:!0}),this._waitForAction(this._onDone.bind(this))):this._translateTo(0,{animate:!0})}},_waitForAction:function(done){this._attrs.ngAction?this._scope.$eval(this._attrs.ngAction,{$done:done}):this._attrs.onAction?eval(this._attrs.onAction):done()},_onDone:function(done){this._element&&(this._translateTo(0,{animate:!0}),this._setState(this.STATE_INITIAL))},_getHeight:function(){return parseInt(this._element[0].getAttribute("height")||"64",10)},setHeight:function(height){this._element[0].setAttribute("height",height+"px"),this._setStyle()},setThresholdHeight:function(thresholdHeight){this._element[0].setAttribute("threshold-height",thresholdHeight+"px")},_getThresholdHeight:function(){return parseInt(this._element[0].getAttribute("threshold-height")||"96",10)},_thresholdHeightEnabled:function(){var th=this._getThresholdHeight();return th>0&&th>=this._getHeight()},_setState:function(state,noEvent){var oldState=this._getState();this._scope.$evalAsync(function(){this._element[0].setAttribute("state",state),noEvent||oldState===this._getState()||this.emit("changestate",{state:state,pullHook:this})}.bind(this))},_getState:function(){return this._element[0].getAttribute("state")},getCurrentState:function(){return this._getState()},_getCurrentScroll:function(){return this._pageElement[0].scrollTop},isDisabled:function(){return this._element[0].hasAttribute("disabled")},setDisabled:function(disabled){disabled?this._element[0].setAttribute("disabled",""):this._element[0].removeAttribute("disabled")},_translateTo:function(scroll,options){options=options||{},this._currentTranslation=scroll,options.animate?animit(this._scrollElement[0]).queue({transform:this._generateTranslationTransform(scroll)},{duration:.3,timing:"cubic-bezier(.1, .7, .1, 1)"}).play(options.callback):animit(this._scrollElement[0]).queue({transform:this._generateTranslationTransform(scroll)}).play(options.callback)},_getMinimumScroll:function(){var scrollHeight=this._scrollElement[0].getBoundingClientRect().height,pageHeight=this._pageElement[0].getBoundingClientRect().height;return scrollHeight>pageHeight?-(scrollHeight-pageHeight):0},_createEventListeners:function(){var element=this._scrollElement.parent();this._hammer=new Hammer(element[0],{dragMinDistance:1,dragDistanceCorrection:!1}),this._bindedOnDrag=this._onDrag.bind(this),this._bindedOnDragStart=this._onDragStart.bind(this),this._bindedOnDragEnd=this._onDragEnd.bind(this),this._bindedOnScroll=this._onScroll.bind(this),this._hammer.on("drag",this._bindedOnDrag), this._hammer.on("dragstart",this._bindedOnDragStart),this._hammer.on("dragend",this._bindedOnDragEnd),element.on("scroll",this._bindedOnScroll)},_destroyEventListeners:function(){var element=this._scrollElement.parent();this._hammer.off("drag",this._bindedOnDrag),this._hammer.off("dragstart",this._bindedOnDragStart),this._hammer.off("dragend",this._bindedOnDragEnd),element.off("scroll",this._bindedOnScroll)},_destroy:function(){this.emit("destroy"),this._destroyEventListeners(),this._element=this._scope=this._attrs=null}});return MicroEvent.mixin(PullHookView),PullHookView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("PushSlidingMenuAnimator",["SlidingMenuAnimator",function(SlidingMenuAnimator){var PushSlidingMenuAnimator=SlidingMenuAnimator.extend({_isRight:!1,_element:void 0,_menuPage:void 0,_mainPage:void 0,_width:void 0,_duration:!1,setup:function(element,mainPage,menuPage,options){options=options||{},this._element=element,this._mainPage=mainPage,this._menuPage=menuPage,this._isRight=!!options.isRight,this._width=options.width||"90%",this._duration=.4,menuPage.css({width:options.width,display:"none"}),menuPage.css(this._isRight?{right:"-"+options.width,left:"auto"}:{right:"auto",left:"-"+options.width})},onResized:function(options){if(this._menuPage.css("width",options.width),this._menuPage.css(this._isRight?{right:"-"+options.width,left:"auto"}:{right:"auto",left:"-"+options.width}),options.isOpened){var max=this._menuPage[0].clientWidth,mainPageTransform=this._generateAbovePageTransform(max),menuPageStyle=this._generateBehindPageStyle(max);animit(this._mainPage[0]).queue({transform:mainPageTransform}).play(),animit(this._menuPage[0]).queue(menuPageStyle).play()}},destroy:function(){this._mainPage.removeAttr("style"),this._menuPage.removeAttr("style"),this._element=this._mainPage=this._menuPage=null},openMenu:function(callback,instant){var duration=instant===!0?0:this._duration;this._menuPage.css("display","block");var max=this._menuPage[0].clientWidth,aboveTransform=this._generateAbovePageTransform(max),behindStyle=this._generateBehindPageStyle(max);setTimeout(function(){animit(this._mainPage[0]).queue({transform:aboveTransform},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){callback(),done()}).play(),animit(this._menuPage[0]).queue(behindStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).play()}.bind(this),1e3/60)},closeMenu:function(callback,instant){var duration=instant===!0?0:this._duration,aboveTransform=this._generateAbovePageTransform(0),behindStyle=this._generateBehindPageStyle(0);setTimeout(function(){animit(this._mainPage[0]).queue({transform:aboveTransform},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue({transform:"translate3d(0, 0, 0)"}).queue(function(done){this._menuPage.css("display","none"),callback(),done()}.bind(this)).play(),animit(this._menuPage[0]).queue(behindStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){done()}).play()}.bind(this),1e3/60)},translateMenu:function(options){this._menuPage.css("display","block");var aboveTransform=this._generateAbovePageTransform(Math.min(options.maxDistance,options.distance)),behindStyle=this._generateBehindPageStyle(Math.min(options.maxDistance,options.distance));animit(this._mainPage[0]).queue({transform:aboveTransform}).play(),animit(this._menuPage[0]).queue(behindStyle).play()},_generateAbovePageTransform:function(distance){var x=this._isRight?-distance:distance,aboveTransform="translate3d("+x+"px, 0, 0)";return aboveTransform},_generateBehindPageStyle:function(distance){var behindX=(this._menuPage[0].clientWidth,this._isRight?-distance:distance),behindTransform="translate3d("+behindX+"px, 0, 0)";return{transform:behindTransform}},copy:function(){return new PushSlidingMenuAnimator}});return PushSlidingMenuAnimator}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("RevealSlidingMenuAnimator",["SlidingMenuAnimator",function(SlidingMenuAnimator){var RevealSlidingMenuAnimator=SlidingMenuAnimator.extend({_blackMask:void 0,_isRight:!1,_menuPage:void 0,_element:void 0,_mainPage:void 0,_duration:void 0,setup:function(element,mainPage,menuPage,options){this._element=element,this._menuPage=menuPage,this._mainPage=mainPage,this._isRight=!!options.isRight,this._width=options.width||"90%",this._duration=.4,mainPage.css({boxShadow:"0px 0 10px 0px rgba(0, 0, 0, 0.2)"}),menuPage.css({width:options.width,opacity:.9,display:"none"}),menuPage.css(this._isRight?{right:"0px",left:"auto"}:{right:"auto",left:"0px"}),this._blackMask=angular.element("<div></div>").css({backgroundColor:"black",top:"0px",left:"0px",right:"0px",bottom:"0px",position:"absolute",display:"none"}),element.prepend(this._blackMask),animit(mainPage[0]).queue({transform:"translate3d(0, 0, 0)"}).play()},onResized:function(options){if(this._width=options.width,this._menuPage.css("width",this._width),options.isOpened){var max=this._menuPage[0].clientWidth,aboveTransform=this._generateAbovePageTransform(max),behindStyle=this._generateBehindPageStyle(max);animit(this._mainPage[0]).queue({transform:aboveTransform}).play(),animit(this._menuPage[0]).queue(behindStyle).play()}},destroy:function(){this._blackMask&&(this._blackMask.remove(),this._blackMask=null),this._mainPage&&this._mainPage.attr("style",""),this._menuPage&&this._menuPage.attr("style",""),this._mainPage=this._menuPage=this._element=void 0},openMenu:function(callback,instant){var duration=instant===!0?0:this._duration;this._menuPage.css("display","block"),this._blackMask.css("display","block");var max=this._menuPage[0].clientWidth,aboveTransform=this._generateAbovePageTransform(max),behindStyle=this._generateBehindPageStyle(max);setTimeout(function(){animit(this._mainPage[0]).queue({transform:aboveTransform},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){callback(),done()}).play(),animit(this._menuPage[0]).queue(behindStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).play()}.bind(this),1e3/60)},closeMenu:function(callback,instant){var duration=instant===!0?0:this._duration;this._blackMask.css("display","block");var aboveTransform=this._generateAbovePageTransform(0),behindStyle=this._generateBehindPageStyle(0);setTimeout(function(){animit(this._mainPage[0]).queue({transform:aboveTransform},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue({transform:"translate3d(0, 0, 0)"}).queue(function(done){this._menuPage.css("display","none"),callback(),done()}.bind(this)).play(),animit(this._menuPage[0]).queue(behindStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){done()}).play()}.bind(this),1e3/60)},translateMenu:function(options){this._menuPage.css("display","block"),this._blackMask.css("display","block");var aboveTransform=this._generateAbovePageTransform(Math.min(options.maxDistance,options.distance)),behindStyle=this._generateBehindPageStyle(Math.min(options.maxDistance,options.distance));delete behindStyle.opacity,animit(this._mainPage[0]).queue({transform:aboveTransform}).play(),animit(this._menuPage[0]).queue(behindStyle).play()},_generateAbovePageTransform:function(distance){var x=this._isRight?-distance:distance,aboveTransform="translate3d("+x+"px, 0, 0)";return aboveTransform},_generateBehindPageStyle:function(distance){var max=this._menuPage[0].getBoundingClientRect().width,behindDistance=(distance-max)/max*10;behindDistance=isNaN(behindDistance)?0:Math.max(Math.min(behindDistance,0),-10);var behindX=this._isRight?-behindDistance:behindDistance,behindTransform="translate3d("+behindX+"%, 0, 0)",opacity=1+behindDistance/100;return{transform:behindTransform,opacity:opacity}},copy:function(){return new RevealSlidingMenuAnimator}});return RevealSlidingMenuAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("SimpleSlideTransitionAnimator",["NavigatorTransitionAnimator",function(NavigatorTransitionAnimator){var SimpleSlideTransitionAnimator=NavigatorTransitionAnimator.extend({backgroundMask:angular.element('<div style="z-index: 2; position: absolute; width: 100%;height: 100%; background-color: black; opacity: 0;"></div>'),timing:"cubic-bezier(.1, .7, .4, 1)",duration:.3,blackMaskOpacity:.4,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},push:function(enterPage,leavePage,callback){var mask=this.backgroundMask.remove();leavePage.element[0].parentNode.insertBefore(mask[0],leavePage.element[0].nextSibling),animit.runAll(animit(mask[0]).queue({opacity:0,transform:"translate3d(0, 0, 0)"}).queue({opacity:this.blackMaskOpacity},{duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){mask.remove(),done()}),animit(enterPage.element[0]).queue({css:{transform:"translate3D(100%, 0, 0)"},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)"},duration:this.duration,timing:this.timing}).resetStyle(),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).queue({css:{transform:"translate3D(-45%, 0px, 0px)"},duration:this.duration,timing:this.timing}).resetStyle().wait(.2).queue(function(done){callback(),done()}))},pop:function(enterPage,leavePage,done){var mask=this.backgroundMask.remove();enterPage.element[0].parentNode.insertBefore(mask[0],enterPage.element[0].nextSibling),animit.runAll(animit(mask[0]).queue({opacity:this.blackMaskOpacity,transform:"translate3d(0, 0, 0)"}).queue({opacity:0},{duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){mask.remove(),done()}),animit(enterPage.element[0]).queue({css:{transform:"translate3D(-45%, 0px, 0px)",opacity:.9},duration:0}).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:this.duration,timing:this.timing}).resetStyle(),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:this.duration,timing:this.timing}).wait(.2).queue(function(finish){done(),finish()}))}});return SimpleSlideTransitionAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("SlideDialogAnimator",["DialogAnimator",function(DialogAnimator){var SlideDialogAnimator=DialogAnimator.extend({timing:"cubic-bezier(.1, .7, .4, 1)",duration:.2,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3D(-50%, -350%, 0)"},duration:0}).queue({css:{transform:"translate3D(-50%, -50%, 0)"},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3D(-50%, -50%, 0)"},duration:0}).queue({css:{transform:"translate3D(-50%, -350%, 0)"},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return SlideDialogAnimator}])}(),function(){"use strict";var module=angular.module("onsen"),SlidingMenuViewModel=Class.extend({_distance:0,_maxDistance:void 0,init:function(options){if(!angular.isNumber(options.maxDistance))throw new Error("options.maxDistance must be number");this.setMaxDistance(options.maxDistance)},setMaxDistance:function(maxDistance){if(0>=maxDistance)throw new Error("maxDistance must be greater then zero.");this.isOpened()&&(this._distance=maxDistance),this._maxDistance=maxDistance},shouldOpen:function(){return!this.isOpened()&&this._distance>=this._maxDistance/2},shouldClose:function(){return!this.isClosed()&&this._distance<this._maxDistance/2},openOrClose:function(options){this.shouldOpen()?this.open(options):this.shouldClose()&&this.close(options)},close:function(options){var callback=options.callback||function(){};this.isClosed()?callback():(this._distance=0,this.emit("close",options))},open:function(options){var callback=options.callback||function(){};this.isOpened()?callback():(this._distance=this._maxDistance,this.emit("open",options))},isClosed:function(){return 0===this._distance},isOpened:function(){return this._distance===this._maxDistance},getX:function(){return this._distance},getMaxDistance:function(){return this._maxDistance},translate:function(x){this._distance=Math.max(1,Math.min(this._maxDistance-1,x));var options={distance:this._distance,maxDistance:this._maxDistance};this.emit("translate",options)},toggle:function(){this.isClosed()?this.open():this.close()}});MicroEvent.mixin(SlidingMenuViewModel),module.factory("SlidingMenuView",["$onsen","$compile","SlidingMenuAnimator","RevealSlidingMenuAnimator","PushSlidingMenuAnimator","OverlaySlidingMenuAnimator",function($onsen,$compile,SlidingMenuAnimator,RevealSlidingMenuAnimator,PushSlidingMenuAnimator,OverlaySlidingMenuAnimator){var SlidingMenuView=Class.extend({_scope:void 0,_attrs:void 0,_element:void 0,_menuPage:void 0,_mainPage:void 0,_doorLock:void 0,_isRightMenu:!1,init:function(scope,element,attrs){this._scope=scope,this._attrs=attrs,this._element=element,this._menuPage=angular.element(element[0].querySelector(".onsen-sliding-menu__menu")),this._mainPage=angular.element(element[0].querySelector(".onsen-sliding-menu__main")),this._doorLock=new DoorLock,this._isRightMenu="right"===attrs.side,this._mainPageHammer=new Hammer(this._mainPage[0]),this._bindedOnTap=this._onTap.bind(this);var maxDistance=this._normalizeMaxSlideDistanceAttr();this._logic=new SlidingMenuViewModel({maxDistance:Math.max(maxDistance,1)}),this._logic.on("translate",this._translate.bind(this)),this._logic.on("open",function(options){this._open(options)}.bind(this)),this._logic.on("close",function(options){this._close(options)}.bind(this)),attrs.$observe("maxSlideDistance",this._onMaxSlideDistanceChanged.bind(this)),attrs.$observe("swipeable",this._onSwipeableChanged.bind(this)),this._bindedOnWindowResize=this._onWindowResize.bind(this),window.addEventListener("resize",this._bindedOnWindowResize),this._boundHandleEvent=this._handleEvent.bind(this),this._bindEvents(),attrs.mainPage&&this.setMainPage(attrs.mainPage),attrs.menuPage&&this.setMenuPage(attrs.menuPage),this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this));var unlock=this._doorLock.lock();window.setTimeout(function(){var maxDistance=this._normalizeMaxSlideDistanceAttr();this._logic.setMaxDistance(maxDistance),this._menuPage.css({opacity:1}),this._animator=this._getAnimatorOption(),this._animator.setup(this._element,this._mainPage,this._menuPage,{isRight:this._isRightMenu,width:this._attrs.maxSlideDistance||"90%"}),unlock()}.bind(this),400),scope.$on("$destroy",this._destroy.bind(this)),attrs.swipeable||this.setSwipeable(!0)},getDeviceBackButtonHandler:function(){return this._deviceBackButtonHandler},_onDeviceBackButton:function(event){this.isMenuOpened()?this.closeMenu():event.callParentHandler()},_onTap:function(){this.isMenuOpened()&&this.closeMenu()},_refreshMenuPageWidth:function(){var width="maxSlideDistance"in this._attrs?this._attrs.maxSlideDistance:"90%";this._animator&&this._animator.onResized({isOpened:this._logic.isOpened(),width:width})},_destroy:function(){this.emit("destroy"),this._deviceBackButtonHandler.destroy(),window.removeEventListener("resize",this._bindedOnWindowResize),this._mainPageHammer.off("tap",this._bindedOnTap),this._element=this._scope=this._attrs=null},_getAnimatorOption:function(){var animator=SlidingMenuView._animatorDict[this._attrs.type];return animator instanceof SlidingMenuAnimator||(animator=SlidingMenuView._animatorDict["default"]),animator.copy()},_onSwipeableChanged:function(swipeable){swipeable=""===swipeable||void 0===swipeable||"true"==swipeable,this.setSwipeable(swipeable)},setSwipeable:function(enabled){enabled?this._activateHammer():this._deactivateHammer()},_onWindowResize:function(){this._recalculateMAX(),this._refreshMenuPageWidth()},_onMaxSlideDistanceChanged:function(){this._recalculateMAX(),this._refreshMenuPageWidth()},_normalizeMaxSlideDistanceAttr:function(){var maxDistance=this._attrs.maxSlideDistance;if("maxSlideDistance"in this._attrs){if("string"!=typeof maxDistance)throw new Error("invalid state");-1!==maxDistance.indexOf("px",maxDistance.length-2)?maxDistance=parseInt(maxDistance.replace("px",""),10):maxDistance.indexOf("%",maxDistance.length-1)>0&&(maxDistance=maxDistance.replace("%",""),maxDistance=parseFloat(maxDistance)/100*this._mainPage[0].clientWidth)}else maxDistance=.9*this._mainPage[0].clientWidth;return maxDistance},_recalculateMAX:function(){var maxDistance=this._normalizeMaxSlideDistanceAttr();maxDistance&&this._logic.setMaxDistance(parseInt(maxDistance,10))},_activateHammer:function(){this._hammertime.on("touch dragleft dragright swipeleft swiperight release",this._boundHandleEvent)},_deactivateHammer:function(){this._hammertime.off("touch dragleft dragright swipeleft swiperight release",this._boundHandleEvent)},_bindEvents:function(){this._hammertime=new Hammer(this._element[0],{dragMinDistance:1})},_appendMainPage:function(pageUrl,templateHTML){var pageScope=this._scope.$new(),pageContent=angular.element(templateHTML),link=$compile(pageContent);this._mainPage.append(pageContent),this._currentPageElement&&(this._currentPageElement.remove(),this._currentPageScope.$destroy()),link(pageScope),this._currentPageElement=pageContent,this._currentPageScope=pageScope,this._currentPageUrl=pageUrl},_appendMenuPage:function(templateHTML){var pageScope=this._scope.$new(),pageContent=angular.element(templateHTML),link=$compile(pageContent);this._menuPage.append(pageContent),this._currentMenuPageScope&&(this._currentMenuPageScope.$destroy(),this._currentMenuPageElement.remove()),link(pageScope),this._currentMenuPageElement=pageContent,this._currentMenuPageScope=pageScope},setMenuPage:function(page,options){if(!page)throw new Error("cannot set undefined page");options=options||{},options.callback=options.callback||function(){};var self=this;$onsen.getPageHTMLAsync(page).then(function(html){self._appendMenuPage(angular.element(html)),options.closeMenu&&self.close(),options.callback()},function(){throw new Error("Page is not found: "+page)})},setMainPage:function(pageUrl,options){options=options||{},options.callback=options.callback||function(){};var done=function(){options.closeMenu&&this.close(),options.callback()}.bind(this);if(this.currentPageUrl===pageUrl)return void done();if(!pageUrl)throw new Error("cannot set undefined page");var self=this;$onsen.getPageHTMLAsync(pageUrl).then(function(html){self._appendMainPage(pageUrl,html),done()},function(){throw new Error("Page is not found: "+page)})},_handleEvent:function(event){if(!this._doorLock.isLocked())switch(this._isInsideIgnoredElement(event.target)&&event.gesture.stopDetect(),event.type){case"dragleft":case"dragright":if(this._logic.isClosed()&&!this._isInsideSwipeTargetArea(event))return;event.gesture.preventDefault();var deltaX=event.gesture.deltaX,deltaDistance=this._isRightMenu?-deltaX:deltaX,startEvent=event.gesture.startEvent;if("isOpened"in startEvent||(startEvent.isOpened=this._logic.isOpened()),0>deltaDistance&&this._logic.isClosed())break;if(deltaDistance>0&&this._logic.isOpened())break;var distance=startEvent.isOpened?deltaDistance+this._logic.getMaxDistance():deltaDistance;this._logic.translate(distance);break;case"swipeleft":if(event.gesture.preventDefault(),this._logic.isClosed()&&!this._isInsideSwipeTargetArea(event))return;this._isRightMenu?this.open():this.close(),event.gesture.stopDetect();break;case"swiperight":if(event.gesture.preventDefault(),this._logic.isClosed()&&!this._isInsideSwipeTargetArea(event))return;this._isRightMenu?this.close():this.open(),event.gesture.stopDetect();break;case"release":this._lastDistance=null,this._logic.shouldOpen()?this.open():this._logic.shouldClose()&&this.close()}},_isInsideIgnoredElement:function(element){do{if(element.getAttribute&&element.getAttribute("sliding-menu-ignore"))return!0;element=element.parentNode}while(element);return!1},_isInsideSwipeTargetArea:function(event){var x=event.gesture.center.pageX;"_swipeTargetWidth"in event.gesture.startEvent||(event.gesture.startEvent._swipeTargetWidth=this._getSwipeTargetWidth());var targetWidth=event.gesture.startEvent._swipeTargetWidth;return this._isRightMenu?this._mainPage[0].clientWidth-x<targetWidth:targetWidth>x},_getSwipeTargetWidth:function(){var targetWidth=this._attrs.swipeTargetWidth;"string"==typeof targetWidth&&(targetWidth=targetWidth.replace("px",""));var width=parseInt(targetWidth,10);return 0>width||!targetWidth?this._mainPage[0].clientWidth:width},closeMenu:function(){return this.close.apply(this,arguments)},close:function(options){options=options||{},options="function"==typeof options?{callback:options}:options,this._logic.isClosed()||(this.emit("preclose",{slidingMenu:this}),this._doorLock.waitUnlock(function(){this._logic.close(options)}.bind(this)))},_close:function(options){var callback=options.callback||function(){},unlock=this._doorLock.lock(),instant="none"==options.animation;this._animator.closeMenu(function(){unlock(),this._mainPage.children().css("pointer-events",""),this._mainPageHammer.off("tap",this._bindedOnTap),this.emit("postclose",{slidingMenu:this}),callback()}.bind(this),instant)},openMenu:function(){return this.open.apply(this,arguments)},open:function(options){options=options||{},options="function"==typeof options?{callback:options}:options,this.emit("preopen",{slidingMenu:this}),this._doorLock.waitUnlock(function(){this._logic.open(options)}.bind(this))},_open:function(options){var callback=options.callback||function(){},unlock=this._doorLock.lock(),instant="none"==options.animation;this._animator.openMenu(function(){unlock(),this._mainPage.children().css("pointer-events","none"),this._mainPageHammer.on("tap",this._bindedOnTap),this.emit("postopen",{slidingMenu:this}),callback()}.bind(this),instant)},toggle:function(options){this._logic.isClosed()?this.open(options):this.close(options)},toggleMenu:function(){return this.toggle.apply(this,arguments)},isMenuOpened:function(){return this._logic.isOpened()},_translate:function(event){this._animator.translateMenu(event)}});return SlidingMenuView._animatorDict={"default":new RevealSlidingMenuAnimator,overlay:new OverlaySlidingMenuAnimator,reveal:new RevealSlidingMenuAnimator,push:new PushSlidingMenuAnimator},SlidingMenuView.registerSlidingMenuAnimator=function(name,animator){if(!(animator instanceof SlidingMenuAnimator))throw new Error('"animator" param must be an instance of SlidingMenuAnimator');this._animatorDict[name]=animator},MicroEvent.mixin(SlidingMenuView),SlidingMenuView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("SlidingMenuAnimator",function(){return Class.extend({setup:function(element,mainPage,menuPage,options){},onResized:function(options){},openMenu:function(callback){},closeClose:function(callback){},destroy:function(){},translateMenu:function(mainPage,menuPage,options){},copy:function(){throw new Error("Override copy method.")}})})}(),function(){"use strict";var module=angular.module("onsen");module.factory("SplitView",["$compile","RevealSlidingMenuAnimator","$onsen","$onsGlobal",function($compile,RevealSlidingMenuAnimator,$onsen,$onsGlobal){function isNumber(n){return!isNaN(parseFloat(n))&&isFinite(n)}var SPLIT_MODE=0,COLLAPSE_MODE=1,MAIN_PAGE_RATIO=.9,SplitView=Class.extend({init:function(scope,element,attrs){element.addClass("onsen-sliding-menu"),this._element=element,this._scope=scope,this._attrs=attrs,this._mainPage=angular.element(element[0].querySelector(".onsen-split-view__main")),this._secondaryPage=angular.element(element[0].querySelector(".onsen-split-view__secondary")),this._max=this._mainPage[0].clientWidth*MAIN_PAGE_RATIO,this._mode=SPLIT_MODE,this._doorLock=new DoorLock,this._doSplit=!1,this._doCollapse=!1,$onsGlobal.orientation.on("change",this._onResize.bind(this)),this._animator=new RevealSlidingMenuAnimator,this._element.css("display","none"),attrs.mainPage&&this.setMainPage(attrs.mainPage),attrs.secondaryPage&&this.setSecondaryPage(attrs.secondaryPage);var unlock=this._doorLock.lock();this._considerChangingCollapse(),this._setSize(),setTimeout(function(){this._element.css("display","block"),unlock()}.bind(this),1e3/60*2),scope.$on("$destroy",this._destroy.bind(this))},_appendSecondPage:function(templateHTML){var pageScope=this._scope.$new(),pageContent=$compile(templateHTML)(pageScope);this._secondaryPage.append(pageContent),this._currentSecondaryPageElement&&(this._currentSecondaryPageElement.remove(),this._currentSecondaryPageScope.$destroy()),this._currentSecondaryPageElement=pageContent,this._currentSecondaryPageScope=pageScope},_appendMainPage:function(templateHTML){var pageScope=this._scope.$new(),pageContent=$compile(templateHTML)(pageScope);this._mainPage.append(pageContent),this._currentPage&&(this._currentPage.remove(),this._currentPageScope.$destroy()),this._currentPage=pageContent,this._currentPageScope=pageScope},setSecondaryPage:function(page){if(!page)throw new Error("cannot set undefined page");$onsen.getPageHTMLAsync(page).then(function(html){this._appendSecondPage(angular.element(html.trim()))}.bind(this),function(){throw new Error("Page is not found: "+page)})},setMainPage:function(page){if(!page)throw new Error("cannot set undefined page");$onsen.getPageHTMLAsync(page).then(function(html){this._appendMainPage(angular.element(html.trim()))}.bind(this),function(){throw new Error("Page is not found: "+page)})},_onResize:function(){var lastMode=this._mode;this._considerChangingCollapse(),lastMode===COLLAPSE_MODE&&this._mode===COLLAPSE_MODE&&this._animator.onResized({isOpened:!1,width:"90%"}),this._max=this._mainPage[0].clientWidth*MAIN_PAGE_RATIO},_considerChangingCollapse:function(){var should=this._shouldCollapse();should&&this._mode!==COLLAPSE_MODE?(this._fireUpdateEvent(),this._doSplit?this._activateSplitMode():this._activateCollapseMode()):should||this._mode!==COLLAPSE_MODE||(this._fireUpdateEvent(),this._doCollapse?this._activateCollapseMode():this._activateSplitMode()),this._doCollapse=this._doSplit=!1},update:function(){this._fireUpdateEvent();var should=this._shouldCollapse();this._doSplit?this._activateSplitMode():this._doCollapse?this._activateCollapseMode():should?this._activateCollapseMode():should||this._activateSplitMode(),this._doSplit=this._doCollapse=!1},_getOrientation:function(){return $onsGlobal.orientation.isPortrait()?"portrait":"landscape"},getCurrentMode:function(){return this._mode===COLLAPSE_MODE?"collapse":"split"},_shouldCollapse:function(){var c="portrait";if("string"==typeof this._attrs.collapse&&(c=this._attrs.collapse.trim()),"portrait"==c)return $onsGlobal.orientation.isPortrait();if("landscape"==c)return $onsGlobal.orientation.isLandscape();if("width"==c.substr(0,5)){var num=c.split(" ")[1];num.indexOf("px")>=0&&(num=num.substr(0,num.length-2));var width=window.innerWidth;return isNumber(num)&&num>width}var mq=window.matchMedia(c);return mq.matches},_setSize:function(){if(this._mode===SPLIT_MODE){this._attrs.mainPageWidth||(this._attrs.mainPageWidth="70");var secondarySize=100-this._attrs.mainPageWidth.replace("%","");this._secondaryPage.css({width:secondarySize+"%",opacity:1}),this._mainPage.css({width:this._attrs.mainPageWidth+"%"}),this._mainPage.css("left",secondarySize+"%")}},_fireEvent:function(name){this.emit(name,{splitView:this,width:window.innerWidth,orientation:this._getOrientation()})},_fireUpdateEvent:function(){var that=this;this.emit("update",{splitView:this,shouldCollapse:this._shouldCollapse(),currentMode:this.getCurrentMode(),split:function(){that._doSplit=!0,that._doCollapse=!1},collapse:function(){that._doSplit=!1,that._doCollapse=!0},width:window.innerWidth,orientation:this._getOrientation()})},_activateCollapseMode:function(){this._mode!==COLLAPSE_MODE&&(this._fireEvent("precollapse"),this._secondaryPage.attr("style",""),this._mainPage.attr("style",""),this._mode=COLLAPSE_MODE,this._animator.setup(this._element,this._mainPage,this._secondaryPage,{isRight:!1,width:"90%"}),this._fireEvent("postcollapse"))},_activateSplitMode:function(){this._mode!==SPLIT_MODE&&(this._fireEvent("presplit"),this._animator.destroy(),this._secondaryPage.attr("style",""),this._mainPage.attr("style",""),this._mode=SPLIT_MODE,this._setSize(),this._fireEvent("postsplit"))},_destroy:function(){this.emit("destroy"),this._element=null,this._scope=null}});return MicroEvent.mixin(SplitView),SplitView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("SwitchView",["$onsen",function($onsen){var SwitchView=Class.extend({init:function(element,scope,attrs){this._element=element,this._checkbox=angular.element(element[0].querySelector("input[type=checkbox]")),this._scope=scope,attrs.$observe("disabled",function(disabled){element.attr("disabled")?this._checkbox.attr("disabled","disabled"):this._checkbox.removeAttr("disabled")}.bind(this)),this._checkbox.on("change",function(event){this.emit("change",{"switch":this,value:this._checkbox[0].checked,isInteractive:!0})}.bind(this))},isChecked:function(){return this._checkbox[0].checked},setChecked:function(isChecked){isChecked=!!isChecked,this._checkbox[0].checked!=isChecked&&(this._scope.model=isChecked,this._checkbox[0].checked=isChecked,this._scope.$evalAsync(),this.emit("change",{"switch":this,value:isChecked,isInteractive:!1}))},getCheckboxElement:function(){return this._checkbox[0]}});return MicroEvent.mixin(SwitchView),SwitchView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("TabbarAnimator",function(){var TabbarAnimator=Class.extend({apply:function(enterPage,leavePage,done){throw new Error("This method must be implemented.")}});return TabbarAnimator}),module.factory("TabbarNoneAnimator",["TabbarAnimator",function(TabbarAnimator){var TabbarNoneAnimator=TabbarAnimator.extend({apply:function(enterPage,leavePage,done){done()}});return TabbarNoneAnimator}]),module.factory("TabbarFadeAnimator",["TabbarAnimator",function(TabbarAnimator){var TabbarFadeAnimator=TabbarAnimator.extend({apply:function(enterPage,leavePage,done){animit.runAll(animit(enterPage[0]).queue({transform:"translate3D(0, 0, 0)",opacity:0}).queue({transform:"translate3D(0, 0, 0)",opacity:1},{duration:.4,timing:"linear"}).resetStyle().queue(function(callback){done(),callback()}),animit(leavePage[0]).queue({transform:"translate3D(0, 0, 0)",opacity:1}).queue({transform:"translate3D(0, 0, 0)",opacity:0},{duration:.4,timing:"linear"}))}});return TabbarFadeAnimator}]),module.factory("TabbarView",["$onsen","$compile","TabbarAnimator","TabbarNoneAnimator","TabbarFadeAnimator",function($onsen,$compile,TabbarAnimator,TabbarNoneAnimator,TabbarFadeAnimator){var TabbarView=Class.extend({_tabbarId:void 0,_tabItems:void 0,init:function(scope,element,attrs){this._scope=scope,this._element=element,this._attrs=attrs,this._tabbarId=Date.now(),this._tabItems=[],this._contentElement=angular.element(element[0].querySelector(".ons-tab-bar__content")),this._tabbarElement=angular.element(element[0].querySelector(".ons-tab-bar__footer")),this._scope.$on("$destroy",this._destroy.bind(this)),this._hasTopTabbar()&&this._prepareForTopTabbar()},_prepareForTopTabbar:function(){this._contentElement.attr("no-status-bar-fill",""),setImmediate(function(){this._contentElement.addClass("tab-bar--top__content"),this._tabbarElement.addClass("tab-bar--top")}.bind(this));var page=ons.findParentComponentUntil("ons-page",this._element[0]); if(page&&this._element.css("top",window.getComputedStyle(page.getContentElement(),null).getPropertyValue("padding-top")),$onsen.shouldFillStatusBar(this._element[0])){var fill=angular.element(document.createElement("div"));fill.addClass("tab-bar__status-bar-fill"),fill.css({width:"0px",height:"0px"}),this._element.prepend(fill)}},_hasTopTabbar:function(){return"top"===this._attrs.position},setActiveTab:function(index,options){options=options||{};var previousTabItem=this._tabItems[this.getActiveTabIndex()],selectedTabItem=this._tabItems[index];if(("undefined"!=typeof selectedTabItem.noReload||selectedTabItem.isPersistent())&&index===this.getActiveTabIndex())return this.emit("reactive",{index:index,tabItem:selectedTabItem}),!1;var needLoad=selectedTabItem.page&&!options.keepPage;if(!selectedTabItem)return!1;var canceled=!1;if(this.emit("prechange",{index:index,tabItem:selectedTabItem,cancel:function(){canceled=!0}}),canceled)return selectedTabItem.setInactive(),previousTabItem&&previousTabItem.setActive(),!1;if(selectedTabItem.setActive(),needLoad){var removeElement=!0;previousTabItem&&previousTabItem.isPersistent()&&(removeElement=!1,previousTabItem._pageElement=this._currentPageElement);var params={callback:function(){this.emit("postchange",{index:index,tabItem:selectedTabItem})}.bind(this),_removeElement:removeElement};options.animation&&(params.animation=options.animation),selectedTabItem.isPersistent()&&selectedTabItem._pageElement?this._loadPersistentPageDOM(selectedTabItem._pageElement,params):this._loadPage(selectedTabItem.page,params)}for(var i=0;i<this._tabItems.length;i++)this._tabItems[i]!=selectedTabItem?this._tabItems[i].setInactive():needLoad||this.emit("postchange",{index:index,tabItem:selectedTabItem});return!0},setTabbarVisibility:function(visible){this._scope.hideTabs=!visible,this._onTabbarVisibilityChanged()},_onTabbarVisibilityChanged:function(){this._hasTopTabbar()?this._scope.hideTabs?this._contentElement.css("top","0px"):this._contentElement.css("top",""):this._scope.hideTabs?this._contentElement.css("bottom","0px"):this._contentElement.css("bottom","")},addTabItem:function(tabItem){this._tabItems.push(tabItem)},getActiveTabIndex:function(){for(var tabItem,i=0;i<this._tabItems.length;i++)if(tabItem=this._tabItems[i],tabItem.isActive())return i;return-1},loadPage:function(page,options){return this._loadPage(page,options)},_loadPage:function(page,options){$onsen.getPageHTMLAsync(page).then(function(html){var pageElement=angular.element(html.trim());this._loadPageDOM(pageElement,options)}.bind(this),function(){throw new Error("Page is not found: "+page)})},_switchPage:function(element,scope,options){if(this._currentPageElement){var oldPageElement=this._currentPageElement,oldPageScope=this._currentPageScope;this._currentPageElement=element,this._currentPageScope=scope,this._getAnimatorOption(options).apply(element,oldPageElement,function(){options._removeElement?(oldPageElement.remove(),oldPageScope.$destroy()):oldPageElement.css("display","none"),options.callback instanceof Function&&options.callback()})}else this._currentPageElement=element,this._currentPageScope=scope,options.callback instanceof Function&&options.callback()},_loadPageDOM:function(element,options){options=options||{};var pageScope=this._scope.$new(),link=$compile(element);this._contentElement.append(element);var pageContent=link(pageScope);pageScope.$evalAsync(),this._switchPage(pageContent,pageScope,options)},_loadPersistentPageDOM:function(element,options){options=options||{},element.css("display","block"),this._switchPage(element,element.scope(),options)},_getAnimatorOption:function(options){var animationAttr=this._element.attr("animation")||"default";return TabbarView._animatorDict[options.animation||animationAttr]||TabbarView._animatorDict["default"]},_destroy:function(){this.emit("destroy"),this._element=this._scope=this._attrs=null}});return MicroEvent.mixin(TabbarView),TabbarView._animatorDict={"default":new TabbarNoneAnimator,none:new TabbarNoneAnimator,fade:new TabbarFadeAnimator},TabbarView.registerAnimator=function(name,animator){if(!(animator instanceof TabbarAnimator))throw new Error('"animator" param must be an instance of TabbarAnimator');this._animatorDict[name]=animator},TabbarView}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsAlertDialog",["$onsen","AlertDialogView",function($onsen,AlertDialogView){return{restrict:"E",replace:!1,scope:!0,transclude:!1,compile:function(element,attrs){var modifierTemplater=$onsen.generateModifierTemplater(attrs);element.addClass("alert-dialog "+modifierTemplater("alert-dialog--*"));var titleElement=angular.element(element[0].querySelector(".alert-dialog-title")),contentElement=angular.element(element[0].querySelector(".alert-dialog-content"));return titleElement.length&&titleElement.addClass(modifierTemplater("alert-dialog-title--*")),contentElement.length&&contentElement.addClass(modifierTemplater("alert-dialog-content--*")),{pre:function(scope,element,attrs){var alertDialog=new AlertDialogView(scope,element,attrs);$onsen.declareVarAttribute(attrs,alertDialog),$onsen.registerEventHandlers(alertDialog,"preshow prehide postshow posthide destroy"),$onsen.addModifierMethods(alertDialog,"alert-dialog--*",element),titleElement.length&&$onsen.addModifierMethods(alertDialog,"alert-dialog-title--*",titleElement),contentElement.length&&$onsen.addModifierMethods(alertDialog,"alert-dialog-content--*",contentElement),$onsen.isAndroid()&&alertDialog.addModifier("android"),element.data("ons-alert-dialog",alertDialog),scope.$on("$destroy",function(){alertDialog._events=void 0,$onsen.removeModifierMethods(alertDialog),element.data("ons-alert-dialog",void 0),element=null})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsBackButton",["$onsen","$compile","GenericView","ComponentCleaner",function($onsen,$compile,GenericView,ComponentCleaner){return{restrict:"E",replace:!1,templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/back_button.tpl",transclude:!0,scope:!0,link:{pre:function(scope,element,attrs,controller,transclude){var backButton=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,backButton),element.data("ons-back-button",backButton),scope.$on("$destroy",function(){backButton._events=void 0,$onsen.removeModifierMethods(backButton),element.data("ons-back-button",void 0),element=null}),scope.modifierTemplater=$onsen.generateModifierTemplater(attrs);var navigator=ons.findParentComponentUntil("ons-navigator",element);scope.$watch(function(){return navigator.pages.length},function(nbrOfPages){scope.showBackButton=nbrOfPages>1}),$onsen.addModifierMethods(backButton,"toolbar-button--*",element.children()),transclude(scope,function(clonedElement){clonedElement[0]&&element[0].querySelector(".back-button__label").appendChild(clonedElement[0])}),ComponentCleaner.onDestroy(scope,function(){ComponentCleaner.destroyScope(scope),ComponentCleaner.destroyAttributes(attrs),element=null,scope=null,attrs=null})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsBottomToolbar",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",replace:!1,transclude:!1,scope:!1,compile:function(element,attrs){var modifierTemplater=$onsen.generateModifierTemplater(attrs),inline="undefined"!=typeof attrs.inline;return element.addClass("bottom-bar"),element.addClass(modifierTemplater("bottom-bar--*")),element.css({"z-index":0}),inline&&element.css("position","static"),{pre:function(scope,element,attrs){var bottomToolbar=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,bottomToolbar),element.data("ons-bottomToolbar",bottomToolbar),scope.$on("$destroy",function(){bottomToolbar._events=void 0,$onsen.removeModifierMethods(bottomToolbar),element.data("ons-bottomToolbar",void 0),element=null}),$onsen.addModifierMethods(bottomToolbar,"bottom-bar--*",element);var pageView=element.inheritedData("ons-page");pageView&&!inline&&pageView.registerBottomToolbar(element)},post:function(scope,element,attrs){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsButton",["$onsen","ButtonView",function($onsen,ButtonView){return{restrict:"E",replace:!1,transclude:!0,scope:{animation:"@"},templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/button.tpl",link:function(scope,element,attrs,_,transclude){var button=new ButtonView(scope,element,attrs);$onsen.declareVarAttribute(attrs,button),element.data("ons-button",button),scope.$on("$destroy",function(){button._events=void 0,$onsen.removeModifierMethods(button),element.data("ons-button",void 0),element=null});var initialAnimation="slide-left";if(scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),element.addClass("button effeckt-button"),element.addClass(scope.modifierTemplater("button--*")),element.addClass(initialAnimation),$onsen.addModifierMethods(button,"button--*",element),transclude(scope.$parent,function(cloned){angular.element(element[0].querySelector(".ons-button-inner")).append(cloned)}),attrs.ngController)throw new Error("This element can't accept ng-controller directive.");scope.item={},scope.item.animation=initialAnimation,scope.$watch("animation",function(newAnimation){newAnimation&&(scope.item.animation&&element.removeClass(scope.item.animation),scope.item.animation=newAnimation,element.addClass(scope.item.animation))}),attrs.$observe("shouldSpin",function(shouldSpin){"true"===shouldSpin?element.attr("data-loading",!0):element.removeAttr("data-loading")}),$onsen.cleaner.onDestroy(scope,function(){$onsen.clearComponent({scope:scope,attrs:attrs,element:element}),scope=element=attrs=null}),$onsen.fireComponentEvent(element[0],"init")}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsCarousel",["$onsen","CarouselView",function($onsen,CarouselView){return{restrict:"E",replace:!1,scope:!1,transclude:!1,compile:function(element,attrs){var templater=$onsen.generateModifierTemplater(attrs);return element.addClass(templater("carousel--*")),function(scope,element,attrs){var carousel=new CarouselView(scope,element,attrs);element.data("ons-carousel",carousel),$onsen.registerEventHandlers(carousel,"postchange refresh overscroll destroy"),$onsen.declareVarAttribute(attrs,carousel),scope.$on("$destroy",function(){carousel._events=void 0,element.data("ons-carousel",void 0),element=null}),element[0].hasAttribute("auto-refresh")&&scope.$watch(function(){return element[0].childNodes.length},function(){setImmediate(function(){carousel.refresh()})}),setImmediate(function(){carousel.refresh()}),$onsen.fireComponentEvent(element[0],"init")}}}}]),module.directive("onsCarouselItem",["$onsen",function($onsen){return{restrict:"E",replace:!1,scope:!1,transclude:!1,compile:function(element,attrs){var templater=$onsen.generateModifierTemplater(attrs);return element.addClass(templater("carousel-item--*")),element.css("width","100%"),function(scope,element,attrs){}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsCol",["$timeout","$onsen",function($timeout,$onsen){return{restrict:"E",replace:!1,transclude:!1,scope:!1,compile:function(element,attrs,transclude){return element.addClass("col ons-col-inner"),function(scope,element,attrs){function updateAlign(align){"top"===align||"center"===align||"bottom"===align?(element.removeClass("col-top col-center col-bottom"),element.addClass("col-"+align)):element.removeClass("col-top col-center col-bottom")}function updateWidth(width){"string"==typeof width?(width=(""+width).trim(),width=width.match(/^\d+$/)?width+"%":width,element.css({"-webkit-box-flex":"0","-webkit-flex":"0 0 "+width,"-moz-box-flex":"0","-moz-flex":"0 0 "+width,"-ms-flex":"0 0 "+width,flex:"0 0 "+width,"max-width":width})):element.removeAttr("style")}attrs.$observe("align",function(align){updateAlign(align)}),attrs.$observe("width",function(width){updateWidth(width)}),attrs.$observe("size",function(size){attrs.width||updateWidth(size)}),updateAlign(attrs.align),updateWidth(attrs.size&&!attrs.width?attrs.size:attrs.width),$onsen.cleaner.onDestroy(scope,function(){$onsen.clearComponent({scope:scope,element:element,attrs:attrs}),element=attrs=scope=null}),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsDialog",["$onsen","DialogView",function($onsen,DialogView){return{restrict:"E",replace:!1,scope:!0,transclude:!0,templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/dialog.tpl",compile:function(element,attrs,transclude){return element[0].setAttribute("no-status-bar-fill",""),{pre:function(scope,element,attrs){transclude(scope,function(clone){angular.element(element[0].querySelector(".dialog")).append(clone)});var dialog=new DialogView(scope,element,attrs);scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),$onsen.addModifierMethods(dialog,"dialog--*",angular.element(element[0].querySelector(".dialog"))),$onsen.declareVarAttribute(attrs,dialog),$onsen.registerEventHandlers(dialog,"preshow prehide postshow posthide destroy"),element.data("ons-dialog",dialog),scope.$on("$destroy",function(){dialog._events=void 0,$onsen.removeModifierMethods(dialog),element.data("ons-dialog",void 0),element=null})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsDummyForInit",["$rootScope",function($rootScope){var isReady=!1;return{restrict:"E",replace:!1,link:{post:function(scope,element){isReady||(isReady=!0,$rootScope.$broadcast("$ons-ready")),element.remove()}}}}])}(),function(){"use strict";var EVENTS="drag dragleft dragright dragup dragdown hold release swipe swipeleft swiperight swipeup swipedown tap doubletap touch transform pinch pinchin pinchout rotate".split(/ +/);angular.module("onsen").directive("onsGestureDetector",["$onsen",function($onsen){function titlize(str){return str.charAt(0).toUpperCase()+str.slice(1)}var scopeDef=EVENTS.reduce(function(dict,name){return dict["ng"+titlize(name)]="&",dict},{});return{restrict:"E",scope:scopeDef,replace:!1,transclude:!0,compile:function(element,attrs){return function(scope,element,attrs,controller,transclude){function handleEvent(event){var attr="ng"+titlize(event.type);attr in scopeDef&&scope[attr]({$event:event})}transclude(scope.$parent,function(cloned){element.append(cloned)});var hammer=new Hammer(element[0]);hammer.on(EVENTS.join(" "),handleEvent),$onsen.cleaner.onDestroy(scope,function(){hammer.off(EVENTS.join(" "),handleEvent),$onsen.clearComponent({scope:scope,element:element,attrs:attrs}),hammer.element=scope=element=attrs=null}),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";function cleanClassAttribute(element){var classList=(""+element.attr("class")).split(/ +/).filter(function(classString){return"fa"!==classString&&"fa-"!==classString.substring(0,3)&&"ion-"!==classString.substring(0,4)});element.attr("class",classList.join(" "))}function buildClassAndStyle(attrs){var classList=["ons-icon"],style={};0===attrs.icon.indexOf("ion-")?(classList.push(attrs.icon),classList.push("ons-icon--ion")):0===attrs.icon.indexOf("fa-")?(classList.push(attrs.icon),classList.push("fa")):(classList.push("fa"),classList.push("fa-"+attrs.icon));var size=""+attrs.size;return size.match(/^[1-5]x|lg$/)?classList.push("fa-"+size):"string"==typeof attrs.size?style["font-size"]=size:classList.push("fa-lg"),{"class":classList.join(" "),style:style}}var module=angular.module("onsen");module.directive("onsIcon",["$onsen",function($onsen){return{restrict:"E",replace:!1,transclude:!1,link:function(scope,element,attrs){if(attrs.ngController)throw new Error("This element can't accept ng-controller directive.");var update=function(){cleanClassAttribute(element);var builded=buildClassAndStyle(attrs);element.css(builded.style),element.addClass(builded["class"])},builded=buildClassAndStyle(attrs);element.css(builded.style),element.addClass(builded["class"]),attrs.$observe("icon",update),attrs.$observe("size",update),attrs.$observe("fixedWidth",update),attrs.$observe("rotate",update),attrs.$observe("flip",update),attrs.$observe("spin",update),$onsen.cleaner.onDestroy(scope,function(){$onsen.clearComponent({scope:scope,element:element,attrs:attrs}),element=scope=attrs=null}),$onsen.fireComponentEvent(element[0],"init")}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsIfOrientation",["$onsen","$onsGlobal",function($onsen,$onsGlobal){return{restrict:"A",replace:!1,transclude:!1,scope:!1,compile:function(element){return element.css("display","none"),function(scope,element,attrs){function update(){var userOrientation=(""+attrs.onsIfOrientation).toLowerCase(),orientation=getLandscapeOrPortrait();("portrait"===userOrientation||"landscape"===userOrientation)&&(userOrientation===orientation?element.css("display",""):element.css("display","none"))}function getLandscapeOrPortrait(){return $onsGlobal.orientation.isPortrait()?"portrait":"landscape"}element.addClass("ons-if-orientation-inner"),attrs.$observe("onsIfOrientation",update),$onsGlobal.orientation.on("change",update),update(),$onsen.cleaner.onDestroy(scope,function(){$onsGlobal.orientation.off("change",update),$onsen.clearComponent({element:element,scope:scope,attrs:attrs}),element=scope=attrs=null})}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsIfPlatform",["$onsen",function($onsen){return{restrict:"A",replace:!1,transclude:!1,scope:!1,compile:function(element){function getPlatformString(){if(navigator.userAgent.match(/Android/i))return"android";if(navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/RIM Tablet OS/i)||navigator.userAgent.match(/BB10/i))return"blackberry";if(navigator.userAgent.match(/iPhone|iPad|iPod/i))return"ios";if(navigator.userAgent.match(/IEMobile/i))return"windows";var isOpera=!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0;if(isOpera)return"opera";var isFirefox="undefined"!=typeof InstallTrigger;if(isFirefox)return"firefox";var isSafari=Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0;if(isSafari)return"safari";var isChrome=!!window.chrome&&!isOpera;if(isChrome)return"chrome";var isIE=!1||!!document.documentMode;return isIE?"ie":"unknown"}element.addClass("ons-if-platform-inner"),element.css("display","none");var platform=getPlatformString();return function(scope,element,attrs){function update(){attrs.onsIfPlatform.toLowerCase()===platform.toLowerCase()?element.css("display","block"):element.css("display","none")}attrs.$observe("onsIfPlatform",function(userPlatform){userPlatform&&update()}),update(),$onsen.cleaner.onDestroy(scope,function(){$onsen.clearComponent({element:element,scope:scope,attrs:attrs}),element=scope=attrs=null})}}}}])}(),function(){"use strict";var module=angular.module("onsen"),compileFunction=function(show,$onsen){return function(element){return function(scope,element,attrs){var dispShow=show?"block":"none",dispHide=show?"none":"block",onShow=function(){element.css("display",dispShow)},onHide=function(){element.css("display",dispHide)},onInit=function(e){e.visible?onShow():onHide()};ons.softwareKeyboard.on("show",onShow),ons.softwareKeyboard.on("hide",onHide),ons.softwareKeyboard.on("init",onInit),ons.softwareKeyboard._visible?onShow():onHide(),$onsen.cleaner.onDestroy(scope,function(){ons.softwareKeyboard.off("show",onShow),ons.softwareKeyboard.off("hide",onHide),ons.softwareKeyboard.off("init",onInit),$onsen.clearComponent({element:element,scope:scope,attrs:attrs}),element=scope=attrs=null})}}};module.directive("onsKeyboardActive",["$onsen",function($onsen){return{restrict:"A",replace:!1,transclude:!1,scope:!1,compile:compileFunction(!0,$onsen)}}]),module.directive("onsKeyboardInactive",["$onsen",function($onsen){return{restrict:"A",replace:!1,transclude:!1,scope:!1,compile:compileFunction(!1,$onsen)}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsLazyRepeat",["$onsen","LazyRepeatView",function($onsen,LazyRepeatView){return{restrict:"A",replace:!1,priority:1e3,transclude:"element",compile:function(element,attrs,linker){return function(scope,element,attrs){new LazyRepeatView(scope,element,attrs,linker);scope.$on("$destroy",function(){scope=element=attrs=linker=null})}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsList",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",scope:!1,replace:!1,transclude:!1,compile:function(element,attrs){return function(scope,element,attrs){var list=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,list),element.data("ons-list",list),scope.$on("$destroy",function(){list._events=void 0,$onsen.removeModifierMethods(list),element.data("ons-list",void 0),element=null});var templater=$onsen.generateModifierTemplater(attrs);element.addClass("list ons-list-inner"),element.addClass(templater("list--*")),$onsen.addModifierMethods(list,"list--*",element),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsListHeader",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",replace:!1,transclude:!1,compile:function(){return function(scope,element,attrs){var listHeader=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,listHeader),element.data("ons-listHeader",listHeader),scope.$on("$destroy",function(){listHeader._events=void 0,$onsen.removeModifierMethods(listHeader),element.data("ons-listHeader",void 0),element=null});var templater=$onsen.generateModifierTemplater(attrs);element.addClass("list__header ons-list-header-inner"),element.addClass(templater("list__header--*")),$onsen.addModifierMethods(listHeader,"list__header--*",element),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsListItem",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",replace:!1,transclude:!1,compile:function(){return function(scope,element,attrs){var listItem=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,listItem),element.data("ons-list-item",listItem),scope.$on("$destroy",function(){listItem._events=void 0,$onsen.removeModifierMethods(listItem),element.data("ons-list-item",void 0),element=null});var templater=$onsen.generateModifierTemplater(attrs);element.addClass("list__item ons-list-item-inner"),element.addClass(templater("list__item--*")),$onsen.addModifierMethods(listItem,"list__item--*",element),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsLoadingPlaceholder",["$onsen","$compile",function($onsen,$compile){return{restrict:"A",replace:!1,transclude:!1,scope:!1,compile:function(element,attrs){if(!attrs.onsLoadingPlaceholder.length)throw Error("Must define page to load.");setImmediate(function(){$onsen.getPageHTMLAsync(attrs.onsLoadingPlaceholder).then(function(html){html=html.trim().replace(/^<ons-page>/,"").replace(/<\/ons-page>$/,"");var div=document.createElement("div");div.innerHTML=html;var newElement=angular.element(div);newElement.css("display","none"),element.append(newElement),ons.compile(newElement[0]);for(var i=element[0].childNodes.length-1;i>=0;i--){var e=element[0].childNodes[i];e!==div&&element[0].removeChild(e)}newElement.css("display","block")})})}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsModal",["$onsen","ModalView",function($onsen,ModalView){function compile(element,attrs){var modifierTemplater=$onsen.generateModifierTemplater(attrs),html=element[0].innerHTML;element[0].innerHTML="";var wrapper=angular.element("<div></div>");wrapper.addClass("modal__content"),wrapper.addClass(modifierTemplater("modal--*__content")),element.css("display","none"),element.addClass("modal"),element.addClass(modifierTemplater("modal--*")),wrapper[0].innerHTML=html,element.append(wrapper)}return{restrict:"E",replace:!1,scope:!1,transclude:!1,compile:function(element,attrs){return compile(element,attrs),{pre:function(scope,element,attrs){var page=element.inheritedData("ons-page");page&&page.registerExtraElement(element);var modal=new ModalView(scope,element);$onsen.addModifierMethods(modal,"modal--*",element),$onsen.addModifierMethods(modal,"modal--*__content",element.children()),$onsen.declareVarAttribute(attrs,modal),element.data("ons-modal",modal),scope.$on("$destroy",function(){modal._events=void 0,$onsen.removeModifierMethods(modal),element.data("ons-modal",void 0)})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsNavigator",["$compile","NavigatorView","$onsen",function($compile,NavigatorView,$onsen){return{restrict:"E",transclude:!1,scope:!0,compile:function(element){var html=$onsen.normalizePageHTML(element.html());return element.contents().remove(),{pre:function(scope,element,attrs,controller){var navigator=new NavigatorView(scope,element,attrs);if($onsen.declareVarAttribute(attrs,navigator),$onsen.registerEventHandlers(navigator,"prepush prepop postpush postpop destroy"),attrs.page)navigator.pushPage(attrs.page,{});else{var pageScope=navigator._createPageScope(),pageElement=angular.element(html),linkScope=$compile(pageElement),link=function(){linkScope(pageScope)};navigator._pushPageDOM("",pageElement,link,pageScope,{}),pageElement=null}element.data("ons-navigator",navigator),scope.$on("$destroy",function(){navigator._events=void 0,element.data("ons-navigator",void 0),element=null})},post:function(scope,element,attrs){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsPage",["$onsen","PageView",function($onsen,PageView){function firePageInitEvent(element){var i=0,f=function(){if(!(i++<5))throw new Error('Fail to fire "pageinit" event. Attach "ons-page" element to the document after initialization.');isAttached(element)?(fillStatusBar(element),$onsen.fireComponentEvent(element,"init"),fireActualPageInitEvent(element)):setImmediate(f)};f()}function fireActualPageInitEvent(element){var event=document.createEvent("HTMLEvents");event.initEvent("pageinit",!0,!0),element.dispatchEvent(event)}function fillStatusBar(element){if($onsen.shouldFillStatusBar(element)){var fill=angular.element(document.createElement("div"));fill.addClass("page__status-bar-fill"),fill.css({width:"0px",height:"0px"}),angular.element(element).prepend(fill)}}function isAttached(element){return document.documentElement===element?!0:element.parentNode?isAttached(element.parentNode):!1}function preLink(scope,element,attrs,controller,transclude){var page=new PageView(scope,element,attrs);$onsen.declareVarAttribute(attrs,page),element.data("ons-page",page);var modifierTemplater=$onsen.generateModifierTemplater(attrs),template="page--*";element.addClass("page "+modifierTemplater(template)),$onsen.addModifierMethods(page,template,element);var pageContent=angular.element(element[0].querySelector(".page__content"));pageContent.addClass(modifierTemplater("page--*__content")),pageContent=null;var pageBackground=angular.element(element[0].querySelector(".page__background"));pageBackground.addClass(modifierTemplater("page--*__background")),pageBackground=null,$onsen.cleaner.onDestroy(scope,function(){page._events=void 0,$onsen.removeModifierMethods(page),element.data("ons-page",void 0),$onsen.clearComponent({element:element,scope:scope,attrs:attrs}),scope=element=attrs=null})}function postLink(scope,element,attrs){firePageInitEvent(element[0])}return{restrict:"E",transclude:!1,scope:!1,compile:function(element){var children=element.children().remove(),content=angular.element('<div class="page__content ons-page-inner"></div>').append(children),background=angular.element('<div class="page__background"></div>');if(element.attr("style")&&(background.attr("style",element.attr("style")),element.attr("style","")),element.append(background),Modernizr.csstransforms3d)element.append(content);else{content.css("overflow","visible");var wrapper=angular.element("<div></div>");wrapper.append(children),content.append(wrapper),element.append(content),wrapper=null;var scroller=new IScroll(content[0],{momentum:!0,bounce:!0,hScrollbar:!1,vScrollbar:!1,preventDefault:!1}),offset=10;scroller.on("scrollStart",function(e){var scrolled=scroller.y-offset;scrolled<scroller.maxScrollY+40&&scroller.refresh()})}return content=null,background=null,children=null,{pre:preLink,post:postLink}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsPopover",["$onsen","PopoverView",function($onsen,PopoverView){return{restrict:"E",replace:!1,transclude:!0,scope:!0,templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/popover.tpl",compile:function(element,attrs,transclude){return{pre:function(scope,element,attrs){transclude(scope,function(clone){angular.element(element[0].querySelector(".popover__content")).append(clone)});var popover=new PopoverView(scope,element,attrs);$onsen.declareVarAttribute(attrs,popover),$onsen.registerEventHandlers(popover,"preshow prehide postshow posthide destroy"),element.data("ons-popover",popover),scope.$on("$destroy",function(){popover._events=void 0,$onsen.removeModifierMethods(popover),element.data("ons-popover",void 0),element=null}),scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),$onsen.addModifierMethods(popover,"popover--*",angular.element(element[0].querySelector(".popover"))),$onsen.addModifierMethods(popover,"popover__content--*",angular.element(element[0].querySelector(".popover__content"))),$onsen.isAndroid()&&setImmediate(function(){popover.addModifier("android")}),scope.direction="up",scope.arrowPosition="bottom"},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsPullHook",["$onsen","PullHookView",function($onsen,PullHookView){return{restrict:"E",replace:!1,scope:!0,compile:function(element,attrs){return{pre:function(scope,element,attrs){var pullHook=new PullHookView(scope,element,attrs);$onsen.declareVarAttribute(attrs,pullHook),$onsen.registerEventHandlers(pullHook,"changestate destroy"),element.data("ons-pull-hook",pullHook),scope.$on("$destroy",function(){pullHook._events=void 0,element.data("ons-pull-hook",void 0),scope=element=attrs=null})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsRow",["$onsen","$timeout",function($onsen,$timeout){return{restrict:"E",replace:!1,transclude:!1,scope:!1,compile:function(element,attrs){return element.addClass("row ons-row-inner"),function(scope,element,attrs){function update(){var align=(""+attrs.align).trim();("top"===align||"center"===align||"bottom"===align)&&(element.removeClass("row-bottom row-center row-top"),element.addClass("row-"+align))}attrs.$observe("align",function(align){update()}),update(),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsScroller",["$onsen","$timeout",function($onsen,$timeout){return{restrict:"E",replace:!1,transclude:!0,scope:{onScrolled:"&",infinitScrollEnable:"="},compile:function(element,attrs){element.addClass("ons-scroller").children().remove();return function(scope,element,attrs,controller,transclude){if(attrs.ngController)throw new Error('"ons-scroller" can\'t accept "ng-controller" directive.'); var wrapper=angular.element("<div></div>");wrapper.addClass("ons-scroller__content ons-scroller-inner"),element.append(wrapper),transclude(scope.$parent,function(cloned){wrapper.append(cloned),wrapper=null});var scrollWrapper;scrollWrapper=element[0];var offset=parseInt(attrs.threshold)||10;scope.onScrolled&&scrollWrapper.addEventListener("scroll",function(){if(scope.infinitScrollEnable){var scrollTopAndOffsetHeight=scrollWrapper.scrollTop+scrollWrapper.offsetHeight,scrollHeightMinusOffset=scrollWrapper.scrollHeight-offset;scrollTopAndOffsetHeight>=scrollHeightMinusOffset&&scope.onScrolled()}}),Modernizr.csstransforms3d||$timeout(function(){var iScroll=new IScroll(scrollWrapper,{momentum:!0,bounce:!0,hScrollbar:!1,vScrollbar:!1,preventDefault:!1});iScroll.on("scrollStart",function(e){var scrolled=iScroll.y-offset;scrolled<iScroll.maxScrollY+40&&iScroll.refresh()}),scope.onScrolled&&iScroll.on("scrollEnd",function(e){var scrolled=iScroll.y-offset;scrolled<iScroll.maxScrollY&&scope.onScrolled()})},500),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsSlidingMenu",["$compile","SlidingMenuView","$onsen",function($compile,SlidingMenuView,$onsen){return{restrict:"E",replace:!1,transclude:!1,scope:!0,compile:function(element,attrs){var main=element[0].querySelector(".main"),menu=element[0].querySelector(".menu");if(main)var mainHtml=angular.element(main).remove().html().trim();if(menu)var menuHtml=angular.element(menu).remove().html().trim();return function(scope,element,attrs){if(attrs.ngController)throw new Error("This element can't accept ng-controller directive.");element.append(angular.element("<div></div>").addClass("onsen-sliding-menu__menu ons-sliding-menu-inner")),element.append(angular.element("<div></div>").addClass("onsen-sliding-menu__main ons-sliding-menu-inner"));var slidingMenu=new SlidingMenuView(scope,element,attrs);$onsen.registerEventHandlers(slidingMenu,"preopen preclose postopen postclose destroy"),mainHtml&&!attrs.mainPage&&slidingMenu._appendMainPage(null,mainHtml),menuHtml&&!attrs.menuPage&&slidingMenu._appendMenuPage(menuHtml),$onsen.declareVarAttribute(attrs,slidingMenu),element.data("ons-sliding-menu",slidingMenu),scope.$on("$destroy",function(){slidingMenu._events=void 0,element.data("ons-sliding-menu",void 0)}),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsSplitView",["$compile","SplitView","$onsen",function($compile,SplitView,$onsen){return{restrict:"E",replace:!1,transclude:!1,scope:!0,compile:function(element,attrs){var mainPage=element[0].querySelector(".main-page"),secondaryPage=element[0].querySelector(".secondary-page");if(mainPage)var mainHtml=angular.element(mainPage).remove().html().trim();if(secondaryPage)var secondaryHtml=angular.element(secondaryPage).remove().html().trim();return function(scope,element,attrs){if(attrs.ngController)throw new Error("This element can't accept ng-controller directive.");element.append(angular.element("<div></div>").addClass("onsen-split-view__secondary full-screen ons-split-view-inner")),element.append(angular.element("<div></div>").addClass("onsen-split-view__main full-screen ons-split-view-inner"));var splitView=new SplitView(scope,element,attrs);mainHtml&&!attrs.mainPage&&splitView._appendMainPage(mainHtml),secondaryHtml&&!attrs.secondaryPage&&splitView._appendSecondPage(secondaryHtml),$onsen.declareVarAttribute(attrs,splitView),$onsen.registerEventHandlers(splitView,"update presplit precollapse postsplit postcollapse destroy"),element.data("ons-split-view",splitView),scope.$on("$destroy",function(){splitView._events=void 0,element.data("ons-split-view",void 0)}),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsSwitch",["$onsen","$parse","SwitchView",function($onsen,$parse,SwitchView){return{restrict:"E",replace:!1,transclude:!1,scope:!0,templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/switch.tpl",compile:function(element){return function(scope,element,attrs){if(attrs.ngController)throw new Error("This element can't accept ng-controller directive.");var switchView=new SwitchView(element,scope,attrs),checkbox=angular.element(element[0].querySelector("input[type=checkbox]"));scope.modifierTemplater=$onsen.generateModifierTemplater(attrs);var label=element.children(),input=angular.element(label.children()[0]),toggle=angular.element(label.children()[1]);if($onsen.addModifierMethods(switchView,"switch--*",label),$onsen.addModifierMethods(switchView,"switch--*__input",input),$onsen.addModifierMethods(switchView,"switch--*__toggle",toggle),attrs.$observe("checked",function(checked){scope.model=!!element.attr("checked")}),attrs.$observe("name",function(name){element.attr("name")&&checkbox.attr("name",name)}),attrs.ngModel){var set=$parse(attrs.ngModel).assign;scope.$parent.$watch(attrs.ngModel,function(value){scope.model=value}),scope.$watch("model",function(to,from){set(scope.$parent,to),to!==from&&scope.$eval(attrs.ngChange)})}$onsen.declareVarAttribute(attrs,switchView),element.data("ons-switch",switchView),$onsen.cleaner.onDestroy(scope,function(){switchView._events=void 0,$onsen.removeModifierMethods(switchView),element.data("ons-switch",void 0),$onsen.clearComponent({element:element,scope:scope,attrs:attrs}),checkbox=element=attrs=scope=null}),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";function tab($onsen,$compile){return{restrict:"E",transclude:!0,scope:{page:"@",active:"@",icon:"@",activeIcon:"@",label:"@",noReload:"@",persistent:"@"},templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/tab.tpl",compile:function(element,attrs){return element.addClass("tab-bar__item"),function(scope,element,attrs,controller,transclude){var tabbarView=element.inheritedData("ons-tabbar");if(!tabbarView)throw new Error("This ons-tab element is must be child of ons-tabbar element.");element.addClass(tabbarView._scope.modifierTemplater("tab-bar--*__item")),element.addClass(tabbarView._scope.modifierTemplater("tab-bar__item--*")),transclude(scope.$parent,function(cloned){var wrapper=angular.element(element[0].querySelector(".tab-bar-inner"));if(attrs.icon||attrs.label||!cloned[0]){var innerElement=angular.element("<div>"+defaultInnerTemplate+"</div>").children();wrapper.append(innerElement),$compile(innerElement)(scope)}else wrapper.append(cloned)});var radioButton=element[0].querySelector("input");scope.tabbarModifierTemplater=tabbarView._scope.modifierTemplater,scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),scope.tabbarId=tabbarView._tabbarId,scope.tabIcon=scope.icon,tabbarView.addTabItem(scope),scope.setActive=function(){element.addClass("active"),radioButton.checked=!0,scope.activeIcon&&(scope.tabIcon=scope.activeIcon),angular.element(element[0].querySelectorAll("[ons-tab-inactive]")).css("display","none"),angular.element(element[0].querySelectorAll("[ons-tab-active]")).css("display","inherit")},scope.setInactive=function(){element.removeClass("active"),radioButton.checked=!1,scope.tabIcon=scope.icon,angular.element(element[0].querySelectorAll("[ons-tab-inactive]")).css("display","inherit"),angular.element(element[0].querySelectorAll("[ons-tab-active]")).css("display","none")},scope.isPersistent=function(){return"undefined"!=typeof scope.persistent},scope.isActive=function(){return element.hasClass("active")},scope.tryToChange=function(){tabbarView.setActiveTab(tabbarView._tabItems.indexOf(scope))},scope.active&&tabbarView.setActiveTab(tabbarView._tabItems.indexOf(scope)),$onsen.fireComponentEvent(element[0],"init")}}}}var module=angular.module("onsen");module.directive("onsTab",tab),module.directive("onsTabbarItem",tab);var defaultInnerTemplate='<div ng-if="icon != undefined" class="tab-bar__icon"><ons-icon icon="{{tabIcon}}" style="font-size: 28px; line-height: 34px; vertical-align: top;"></ons-icon></div><div ng-if="label" class="tab-bar__label">{{label}}</div>';tab.$inject=["$onsen","$compile"]}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsTabbar",["$onsen","$compile","TabbarView",function($onsen,$compile,TabbarView){return{restrict:"E",replace:!1,transclude:!0,scope:!0,templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/tab_bar.tpl",link:function(scope,element,attrs,controller,transclude){scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),scope.selectedTabItem={source:""},attrs.$observe("hideTabs",function(hide){var visible="true"!==hide;tabbarView.setTabbarVisibility(visible)});var tabbarView=new TabbarView(scope,element,attrs);$onsen.addModifierMethods(tabbarView,"tab-bar--*",angular.element(element.children()[1])),$onsen.registerEventHandlers(tabbarView,"reactive prechange postchange destroy"),scope.tabbarId=tabbarView._tabbarId,element.data("ons-tabbar",tabbarView),$onsen.declareVarAttribute(attrs,tabbarView),transclude(scope,function(cloned){angular.element(element[0].querySelector(".ons-tabbar-inner")).append(cloned)}),scope.$on("$destroy",function(){tabbarView._events=void 0,$onsen.removeModifierMethods(tabbarView),element.data("ons-tabbar",void 0)}),$onsen.fireComponentEvent(element[0],"init")}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsTemplate",["$onsen","$templateCache",function($onsen,$templateCache){return{restrict:"E",transclude:!1,priority:1e3,terminal:!0,compile:function(element){$templateCache.put(element.attr("id"),element.remove().html()),$onsen.fireComponentEvent(element[0],"init")}}}])}(),function(){"use strict";function ensureLeftContainer(element,modifierTemplater){var container=element[0].querySelector(".left");return container||(container=document.createElement("div"),container.setAttribute("class","left"),container.innerHTML="&nbsp;"),""===container.innerHTML.trim()&&(container.innerHTML="&nbsp;"),angular.element(container).addClass("navigation-bar__left").addClass(modifierTemplater("navigation-bar--*__left")),container}function ensureCenterContainer(element,modifierTemplater){var container=element[0].querySelector(".center");return container||(container=document.createElement("div"),container.setAttribute("class","center")),""===container.innerHTML.trim()&&(container.innerHTML="&nbsp;"),angular.element(container).addClass("navigation-bar__title navigation-bar__center").addClass(modifierTemplater("navigation-bar--*__center")),container}function ensureRightContainer(element,modifierTemplater){var container=element[0].querySelector(".right");return container||(container=document.createElement("div"),container.setAttribute("class","right"),container.innerHTML="&nbsp;"),""===container.innerHTML.trim()&&(container.innerHTML="&nbsp;"),angular.element(container).addClass("navigation-bar__right").addClass(modifierTemplater("navigation-bar--*__right")),container}function hasCenterClassElementOnly(element){for(var child,hasCenter=!1,hasOther=!1,children=element.contents(),i=0;i<children.length;i++)child=angular.element(children[i]),child.hasClass("center")?hasCenter=!0:(child.hasClass("left")||child.hasClass("right"))&&(hasOther=!0);return hasCenter&&!hasOther}function ensureToolbarItemElements(element,modifierTemplater){var center;if(hasCenterClassElementOnly(element))center=ensureCenterContainer(element,modifierTemplater),element.contents().remove(),element.append(center);else{center=ensureCenterContainer(element,modifierTemplater);var left=ensureLeftContainer(element,modifierTemplater),right=ensureRightContainer(element,modifierTemplater);element.contents().remove(),element.append(angular.element([left,center,right]))}}var module=angular.module("onsen");module.directive("onsToolbar",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",replace:!1,scope:!1,transclude:!1,compile:function(element,attrs){var shouldAppendAndroidModifier=ons.platform.isAndroid()&&!element[0].hasAttribute("fixed-style"),modifierTemplater=$onsen.generateModifierTemplater(attrs,shouldAppendAndroidModifier?["android"]:[]),inline="undefined"!=typeof attrs.inline;return element.addClass("navigation-bar"),element.addClass(modifierTemplater("navigation-bar--*")),inline||element.css({position:"absolute","z-index":"10000",left:"0px",right:"0px",top:"0px"}),ensureToolbarItemElements(element,modifierTemplater),{pre:function(scope,element,attrs){var toolbar=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,toolbar),scope.$on("$destroy",function(){toolbar._events=void 0,$onsen.removeModifierMethods(toolbar),element.data("ons-toolbar",void 0),element=null}),$onsen.addModifierMethods(toolbar,"navigation-bar--*",element),angular.forEach(["left","center","right"],function(position){var el=element[0].querySelector(".navigation-bar__"+position);el&&$onsen.addModifierMethods(toolbar,"navigation-bar--*__"+position,angular.element(el))});var pageView=element.inheritedData("ons-page");pageView&&!inline&&pageView.registerToolbar(element),element.data("ons-toolbar",toolbar)},post:function(scope,element,attrs){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsToolbarButton",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",transclude:!0,scope:{},templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/toolbar_button.tpl",link:{pre:function(scope,element,attrs){var toolbarButton=new GenericView(scope,element,attrs),innerElement=element[0].querySelector(".toolbar-button");$onsen.declareVarAttribute(attrs,toolbarButton),element.data("ons-toolbar-button",toolbarButton),scope.$on("$destroy",function(){toolbarButton._events=void 0,$onsen.removeModifierMethods(toolbarButton),element.data("ons-toolbar-button",void 0),element=null});var modifierTemplater=$onsen.generateModifierTemplater(attrs);if(attrs.ngController)throw new Error("This element can't accept ng-controller directive.");attrs.$observe("disabled",function(value){value===!1||"undefined"==typeof value?innerElement.removeAttribute("disabled"):innerElement.setAttribute("disabled","disabled")}),scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),$onsen.addModifierMethods(toolbarButton,"toolbar-button--*",element.children()),element.children("span").addClass(modifierTemplater("toolbar-button--*")),$onsen.cleaner.onDestroy(scope,function(){$onsen.clearComponent({scope:scope,attrs:attrs,element:element}),scope=element=attrs=null})},post:function(scope,element,attrs){$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen"),ComponentCleaner={decomposeNode:function(element){for(var children=element.remove().children(),i=0;i<children.length;i++)ComponentCleaner.decomposeNode(angular.element(children[i]))},destroyAttributes:function(attrs){attrs.$$element=null,attrs.$$observers=null},destroyElement:function(element){element.remove()},destroyScope:function(scope){scope.$$listeners={},scope.$$watchers=null,scope=null},onDestroy:function(scope,fn){var clear=scope.$on("$destroy",function(){clear(),fn.apply(null,arguments)})}};module.factory("ComponentCleaner",function(){return ComponentCleaner}),function(){var ngEventDirectives={};"click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste".split(" ").forEach(function(name){function directiveNormalize(name){return name.replace(/-([a-z])/g,function(matches){return matches[1].toUpperCase()})}var directiveName=directiveNormalize("ng-"+name);ngEventDirectives[directiveName]=["$parse",function($parse){return{compile:function($element,attr){var fn=$parse(attr[directiveName]);return function(scope,element,attr){var listener=function(event){scope.$apply(function(){fn(scope,{$event:event})})};element.on(name,listener),ComponentCleaner.onDestroy(scope,function(){element.off(name,listener),element=null,ComponentCleaner.destroyScope(scope),scope=null,ComponentCleaner.destroyAttributes(attr),attr=null})}}}}]}),module.config(["$provide",function($provide){var shift=function($delegate){return $delegate.shift(),$delegate};Object.keys(ngEventDirectives).forEach(function(directiveName){$provide.decorator(directiveName+"Directive",["$delegate",shift])})}]),Object.keys(ngEventDirectives).forEach(function(directiveName){module.directive(directiveName,ngEventDirectives[directiveName])})}()}(),function(){"use strict";var util={init:function(){this.ready=!1},addBackButtonListener:function(fn){this._ready?window.document.addEventListener("backbutton",fn,!1):window.document.addEventListener("deviceready",function(){window.document.addEventListener("backbutton",fn,!1)})},removeBackButtonListener:function(fn){this._ready?window.document.removeEventListener("backbutton",fn,!1):window.document.addEventListener("deviceready",function(){window.document.removeEventListener("backbutton",fn,!1)})}};util.init(),angular.module("onsen").service("DeviceBackButtonHandler",function(){this._init=function(){window.ons.isWebView()?window.document.addEventListener("deviceready",function(){util._ready=!0},!1):util._ready=!0,this._bindedCallback=this._callback.bind(this),this.enable()},this._isEnabled=!1,this.enable=function(){this._isEnabled||(util.addBackButtonListener(this._bindedCallback),this._isEnabled=!0)},this.disable=function(){this._isEnabled&&(util.removeBackButtonListener(this._bindedCallback),this._isEnabled=!1)},this.fireDeviceBackButtonEvent=function(){var event=document.createEvent("Event");event.initEvent("backbutton",!0,!0),document.dispatchEvent(event)},this._callback=function(){this._dispatchDeviceBackButtonEvent()},this.create=function(element,callback){if(!(element instanceof angular.element().constructor))throw new Error("element must be an instance of jqLite");if(!(callback instanceof Function))throw new Error("callback must be an instance of Function");var handler={_callback:callback,_element:element,disable:function(){this._element.data("device-backbutton-handler",null)},setListener:function(callback){this._callback=callback},enable:function(){this._element.data("device-backbutton-handler",this)},isEnabled:function(){return this._element.data("device-backbutton-handler")===this},destroy:function(){this._element.data("device-backbutton-handler",null),this._callback=this._element=null}};return handler.enable(),handler},this._dispatchDeviceBackButtonEvent=function(event){function createEvent(element){return{_element:element,callParentHandler:function(){for(var parent=this._element.parent();parent[0];){if(handler=parent.data("device-backbutton-handler"))return handler._callback(createEvent(parent));parent=parent.parent()}}}}var tree=this._captureTree(),element=this._findHandlerLeafElement(tree),handler=element.data("device-backbutton-handler");handler._callback(createEvent(element))},this._dumpParents=function(element){for(;element[0];)console.log(element[0].nodeName.toLowerCase()+"."+element.attr("class")),element=element.parent()},this._captureTree=function(){function createTree(element){return{element:element,children:Array.prototype.concat.apply([],Array.prototype.map.call(element.children(),function(child){if(child=angular.element(child),"none"===child[0].style.display)return[];if(0===child.children().length&&!child.data("device-backbutton-handler"))return[];var result=createTree(child);return 0!==result.children.length||child.data("device-backbutton-handler")?[result]:[]}))}}return createTree(angular.element(document.body))},this._dumpTree=function(node){function _dump(node,level){var pad=new Array(level+1).join(" ");console.log(pad+node.element[0].nodeName.toLowerCase()),node.children.forEach(function(node){_dump(node,level+1)})}_dump(node,0)},this._findHandlerLeafElement=function(tree){function find(node){return 0===node.children.length?node.element:1===node.children.length?find(node.children[0]):node.children.map(function(childNode){return childNode.element}).reduce(function(left,right){if(null===left)return right;var leftZ=parseInt(window.getComputedStyle(left[0],"").zIndex,10),rightZ=parseInt(window.getComputedStyle(right[0],"").zIndex,10);if(!isNaN(leftZ)&&!isNaN(rightZ))return leftZ>rightZ?left:right;throw new Error("Capturing backbutton-handler is failure.")},null)}return find(tree)},this._init()})}(),function(){"use strict";var module=angular.module("onsen");module.factory("$onsen",["$rootScope","$window","$cacheFactory","$document","$templateCache","$http","$q","$onsGlobal","ComponentCleaner","DeviceBackButtonHandler",function($rootScope,$window,$cacheFactory,$document,$templateCache,$http,$q,$onsGlobal,ComponentCleaner,DeviceBackButtonHandler){function createOnsenService(){return{DIRECTIVE_TEMPLATE_URL:"templates",cleaner:ComponentCleaner,DeviceBackButtonHandler:DeviceBackButtonHandler,_defaultDeviceBackButtonHandler:DeviceBackButtonHandler.create(angular.element(document.body),function(){navigator.app.exitApp()}),getDefaultDeviceBackButtonHandler:function(){return this._defaultDeviceBackButtonHandler},isEnabledAutoStatusBarFill:function(){return!!$onsGlobal._config.autoStatusBarFill},shouldFillStatusBar:function(element){if(this.isEnabledAutoStatusBarFill()&&this.isWebView()&&this.isIOS7Above()){if(!(element instanceof HTMLElement))throw new Error("element must be an instance of HTMLElement");for(var debug="ONS-TABBAR"===element.tagName?console.log.bind(console):angular.noop;;){if(element.hasAttribute("no-status-bar-fill"))return!1;if(element=element.parentNode,debug(element),!element||!element.hasAttribute)return!0}}return!1},clearComponent:function(params){params.scope&&ComponentCleaner.destroyScope(params.scope),params.attrs&&ComponentCleaner.destroyAttributes(params.attrs),params.element&&ComponentCleaner.destroyElement(params.element),params.elements&&params.elements.forEach(function(element){ComponentCleaner.destroyElement(element)})},upTo:function(el,tagName){tagName=tagName.toLowerCase();do{if(!el)return null;if(el=el.parentNode,el.tagName.toLowerCase()==tagName)return el}while(el.parentNode);return null},waitForVariables:function(dependencies,callback){unlockerDict.addCallback(dependencies,callback)},findElementeObject:function(element,name){return element.inheritedData(name)},getPageHTMLAsync:function(page){var cache=$templateCache.get(page);if(cache){var deferred=$q.defer(),html="string"==typeof cache?cache:cache[1];return deferred.resolve(this.normalizePageHTML(html)),deferred.promise}return $http({url:page,method:"GET"}).then(function(response){var html=response.data;return this.normalizePageHTML(html)}.bind(this))},normalizePageHTML:function(html){return html=(""+html).trim(),html.match(/^<(ons-page|ons-navigator|ons-tabbar|ons-sliding-menu|ons-split-view)/)||(html="<ons-page>"+html+"</ons-page>"),html},generateModifierTemplater:function(attrs,modifiers){var attrModifiers=attrs&&"string"==typeof attrs.modifier?attrs.modifier.trim().split(/ +/):[];return modifiers=angular.isArray(modifiers)?attrModifiers.concat(modifiers):attrModifiers,function(template){return modifiers.map(function(modifier){return template.replace("*",modifier)}).join(" ")}},addModifierMethods:function(view,template,element){var _tr=function(modifier){return template.replace("*",modifier)},fns={hasModifier:function(modifier){return element.hasClass(_tr(modifier))},removeModifier:function(modifier){element.removeClass(_tr(modifier))},addModifier:function(modifier){element.addClass(_tr(modifier))},setModifier:function(modifier){for(var classes=element.attr("class").split(/\s+/),patt=template.replace("*","."),i=0;i<classes.length;i++){var cls=classes[i];cls.match(patt)&&element.removeClass(cls)}element.addClass(_tr(modifier))},toggleModifier:function(modifier){var cls=_tr(modifier);element.hasClass(cls)?element.removeClass(cls):element.addClass(cls)}},append=function(oldFn,newFn){return"undefined"!=typeof oldFn?function(){return oldFn.apply(null,arguments)||newFn.apply(null,arguments)}:newFn};view.hasModifier=append(view.hasModifier,fns.hasModifier),view.removeModifier=append(view.removeModifier,fns.removeModifier),view.addModifier=append(view.addModifier,fns.addModifier),view.setModifier=append(view.setModifier,fns.setModifier),view.toggleModifier=append(view.toggleModifier,fns.toggleModifier)},removeModifierMethods:function(view){view.hasModifier=view.removeModifier=view.addModifier=view.setModifier=view.toggleModifier=void 0},declareVarAttribute:function(attrs,object){if("string"==typeof attrs["var"]){var varName=attrs["var"];this._defineVar(varName,object),unlockerDict.unlockVarName(varName)}},_registerEventHandler:function(component,eventName){var capitalizedEventName=eventName.charAt(0).toUpperCase()+eventName.slice(1);component.on(eventName,function(event){$onsen.fireComponentEvent(component._element[0],eventName,event);var handler=component._attrs["ons"+capitalizedEventName];handler&&(component._scope.$eval(handler,{$event:event}),component._scope.$evalAsync())})},registerEventHandlers:function(component,eventNames){eventNames=eventNames.trim().split(/\s+/);for(var i=0,l=eventNames.length;l>i;i++){var eventName=eventNames[i];this._registerEventHandler(component,eventName)}},isAndroid:function(){return!!window.navigator.userAgent.match(/android/i)},isIOS:function(){return!!window.navigator.userAgent.match(/(ipad|iphone|ipod touch)/i)},isWebView:function(){return window.ons.isWebView()},isIOS7Above:function(){var ua=window.navigator.userAgent,match=ua.match(/(iPad|iPhone|iPod touch);.*CPU.*OS (\d+)_(\d+)/i),result=match?parseFloat(match[2]+"."+match[3])>=7:!1;return function(){return result}}(),fireComponentEvent:function(dom,eventName,data){data=data||{};var event=document.createEvent("HTMLEvents");for(var key in data)data.hasOwnProperty(key)&&(event[key]=data[key]);event.component=dom?angular.element(dom).data(dom.nodeName.toLowerCase())||null:null,event.initEvent(dom.nodeName.toLowerCase()+":"+eventName,!0,!0),dom.dispatchEvent(event)},_defineVar:function(name,object){function set(container,names,object){for(var name,i=0;i<names.length-1;i++)name=names[i],(void 0===container[name]||null===container[name])&&(container[name]={}),container=container[name];if(container[names[names.length-1]]=object,container[names[names.length-1]]!==object)throw new Error('Cannot set var="'+object._attrs["var"]+'" because it will overwrite a read-only variable.')}var names=name.split(/\./);ons.componentBase&&set(ons.componentBase,names,object),set($rootScope,names,object)}}}function createUnlockerDict(){return{_unlockersDict:{},_unlockedVarDict:{},_addVarLock:function(name,unlocker){if(!(unlocker instanceof Function))throw new Error("unlocker argument must be an instance of Function.");this._unlockersDict[name]?this._unlockersDict[name].push(unlocker):this._unlockersDict[name]=[unlocker]},unlockVarName:function(varName){var unlockers=this._unlockersDict[varName];unlockers&&unlockers.forEach(function(unlock){unlock()}),this._unlockedVarDict[varName]=!0},addCallback:function(dependencies,callback){if(!(callback instanceof Function))throw new Error("callback argument must be an instance of Function.");var doorLock=new DoorLock,self=this;dependencies.forEach(function(varName){if(!self._unlockedVarDict[varName]){var unlock=doorLock.lock();self._addVarLock(varName,unlock)}}),doorLock.isLocked()?doorLock.waitUnlock(callback):callback()}}}var unlockerDict=createUnlockerDict(),$onsen=createOnsenService();return $onsen}])}(),window.animit=function(){"use strict";var Animit=function(element){if(!(this instanceof Animit))return new Animit(element);if(element instanceof HTMLElement)this.elements=[element];else{if("[object Array]"!==Object.prototype.toString.call(element))throw new Error("First argument must be an array or an instance of HTMLElement.");this.elements=element}this.transitionQueue=[],this.lastStyleAttributeDict=[];var self=this;this.elements.forEach(function(element,index){element.hasAttribute("data-animit-orig-style")?self.lastStyleAttributeDict[index]=element.getAttribute("data-animit-orig-style"):(self.lastStyleAttributeDict[index]=element.getAttribute("style"),element.setAttribute("data-animit-orig-style",self.lastStyleAttributeDict[index]||""))})};Animit.prototype={transitionQueue:void 0,element:void 0,play:function(callback){return"function"==typeof callback&&this.transitionQueue.push(function(done){callback(),done()}),this.startAnimation(),this},queue:function(transition,options){var queue=this.transitionQueue;if(transition&&options&&(options.css=transition,transition=new Animit.Transition(options)),transition instanceof Function||transition instanceof Animit.Transition||(transition=new Animit.Transition(transition.css?transition:{css:transition})),transition instanceof Function)queue.push(transition);else{if(!(transition instanceof Animit.Transition))throw new Error("Invalid arguments");queue.push(transition.build())}return this},wait:function(seconds){return this.transitionQueue.push(function(done){setTimeout(done,1e3*seconds)}),this},resetStyle:function(options){function reset(){self.elements.forEach(function(element,index){element.style[Animit.prefix+"Transition"]="none",element.style.transition="none",self.lastStyleAttributeDict[index]?element.setAttribute("style",self.lastStyleAttributeDict[index]):(element.setAttribute("style",""),element.removeAttribute("style"))})}options=options||{};var self=this;if(options.transition&&!options.duration)throw new Error('"options.duration" is required when "options.transition" is enabled.');if(options.transition||options.duration&&options.duration>0){var transitionValue=options.transition||"all "+options.duration+"s "+(options.timing||"linear"),transitionStyle="transition: "+transitionValue+"; -"+Animit.prefix+"-transition: "+transitionValue+";";this.transitionQueue.push(function(done){var elements=this.elements;elements.forEach(function(element,index){element.style[Animit.prefix+"Transition"]=transitionValue,element.style.transition=transitionValue;var styleValue=(self.lastStyleAttributeDict[index]?self.lastStyleAttributeDict[index]+"; ":"")+transitionStyle;element.setAttribute("style",styleValue)});var removeListeners=util.addOnTransitionEnd(elements[0],function(){clearTimeout(timeoutId),reset(),done()}),timeoutId=setTimeout(function(){removeListeners(),reset(),done()},1e3*options.duration*1.4)})}else this.transitionQueue.push(function(done){reset(),done()});return this},startAnimation:function(){return this._dequeueTransition(),this},_dequeueTransition:function(){var transition=this.transitionQueue.shift();if(this._currentTransition)throw new Error("Current transition exists.");this._currentTransition=transition;var self=this,called=!1,done=function(){if(called)throw new Error("Invalid state: This callback is called twice.");called=!0,self._currentTransition=void 0,self._dequeueTransition()};transition&&transition.call(this,done)}},Animit.cssPropertyDict=function(){var styles=window.getComputedStyle(document.documentElement,""),dict={},a="A".charCodeAt(0),z="z".charCodeAt(0);for(var key in styles)if(styles.hasOwnProperty(key)){{key.charCodeAt(0)}a<=key.charCodeAt(0)&&z>=key.charCodeAt(0)&&"cssText"!==key&&"parentText"!==key&&"length"!==key&&(dict[key]=!0)}return dict}(),Animit.hasCssProperty=function(name){return!!Animit.cssPropertyDict[name]},Animit.prefix=function(){var styles=window.getComputedStyle(document.documentElement,""),pre=(Array.prototype.slice.call(styles).join("").match(/-(moz|webkit|ms)-/)||""===styles.OLink&&["","o"])[1];return pre}(),Animit.runAll=function(){for(var i=0;i<arguments.length;i++)arguments[i].play()},Animit.Transition=function(options){this.options=options||{},this.options.duration=this.options.duration||0,this.options.timing=this.options.timing||"linear",this.options.css=this.options.css||{},this.options.property=this.options.property||"all"},Animit.Transition.prototype={build:function(){function createActualCssProps(css){var result={};return Object.keys(css).forEach(function(name){ var value=css[name];name=util.normalizeStyleName(name);var prefixed=Animit.prefix+util.capitalize(name);Animit.cssPropertyDict[name]?result[name]=value:Animit.cssPropertyDict[prefixed]?result[prefixed]=value:(result[prefixed]=value,result[name]=value)}),result}if(0===Object.keys(this.options.css).length)throw new Error("options.css is required.");var css=createActualCssProps(this.options.css);if(this.options.duration>0){var transitionValue=util.buildTransitionValue(this.options),self=this;return function(callback){var elements=this.elements,timeout=1e3*self.options.duration*1.4,removeListeners=util.addOnTransitionEnd(elements[0],function(){clearTimeout(timeoutId),callback()}),timeoutId=setTimeout(function(){removeListeners(),callback()},timeout);elements.forEach(function(element,index){element.style[Animit.prefix+"Transition"]=transitionValue,element.style.transition=transitionValue,Object.keys(css).forEach(function(name){element.style[name]=css[name]})})}}return this.options.duration<=0?function(callback){var elements=this.elements;elements.forEach(function(element,index){element.style[Animit.prefix+"Transition"]="none",element.transition="none",Object.keys(css).forEach(function(name){element.style[name]=css[name]})}),elements.length&&elements[0].offsetHeight,window.requestAnimationFrame?requestAnimationFrame(callback):setTimeout(callback,1e3/30)}:void 0}};var util={normalizeStyleName:function(name){return name=name.replace(/-[a-zA-Z]/g,function(all){return all.slice(1).toUpperCase()}),name.charAt(0).toLowerCase()+name.slice(1)},capitalize:function(str){return str.charAt(0).toUpperCase()+str.slice(1)},buildTransitionValue:function(params){params.property=params.property||"all",params.duration=params.duration||.4,params.timing=params.timing||"linear";var props=params.property.split(/ +/);return props.map(function(prop){return prop+" "+params.duration+"s "+params.timing}).join(", ")},addOnTransitionEnd:function(element,callback){if(!element)return function(){};var fn=function(event){element==event.target&&(event.stopPropagation(),removeListeners(),callback())},removeListeners=function(){util._transitionEndEvents.forEach(function(eventName){element.removeEventListener(eventName,fn)})};return util._transitionEndEvents.forEach(function(eventName){element.addEventListener(eventName,fn,!1)}),removeListeners},_transitionEndEvents:function(){return"webkit"===Animit.prefix||"o"===Animit.prefix||"moz"===Animit.prefix||"ms"===Animit.prefix?[Animit.prefix+"TransitionEnd","transitionend"]:["transitionend"]}()};return Animit}(),window.ons.notification=function(){var createAlertDialog=function(title,message,buttonLabels,primaryButtonIndex,modifier,animation,callback,messageIsHTML,cancelable,promptDialog,autofocus,placeholder){var inputEl,dialogEl=angular.element("<ons-alert-dialog>"),titleEl=angular.element("<div>").addClass("alert-dialog-title").text(title),messageEl=angular.element("<div>").addClass("alert-dialog-content"),footerEl=angular.element("<div>").addClass("alert-dialog-footer");modifier&&dialogEl.attr("modifier",modifier),dialogEl.attr("animation",animation),messageIsHTML?messageEl.html(message):messageEl.text(message),dialogEl.append(titleEl).append(messageEl),promptDialog&&(inputEl=angular.element("<input>").addClass("text-input").attr("placeholder",placeholder).css({width:"100%",marginTop:"10px"}),messageEl.append(inputEl)),dialogEl.append(footerEl),angular.element(document.body).append(dialogEl),ons.compile(dialogEl[0]);var alertDialog=dialogEl.data("ons-alert-dialog");buttonLabels.length<=2&&footerEl.addClass("alert-dialog-footer--one");for(var createButton=function(i){var buttonEl=angular.element("<button>").addClass("alert-dialog-button").text(buttonLabels[i]);i==primaryButtonIndex&&buttonEl.addClass("alert-dialog-button--primal"),buttonLabels.length<=2&&buttonEl.addClass("alert-dialog-button--one"),buttonEl.on("click",function(){buttonEl.off("click"),alertDialog.hide({callback:function(){callback(promptDialog?inputEl.val():i),alertDialog.destroy(),alertDialog=inputEl=buttonEl=null}})}),footerEl.append(buttonEl)},i=0;i<buttonLabels.length;i++)createButton(i);cancelable&&(alertDialog.setCancelable(cancelable),alertDialog.on("cancel",function(){callback(promptDialog?null:-1),setTimeout(function(){alertDialog.destroy(),alertDialog=null,inputEl=null})})),alertDialog.show({callback:function(){promptDialog&&autofocus&&inputEl[0].focus()}}),dialogEl=titleEl=messageEl=footerEl=null};return{alert:function(options){var defaults={buttonLabel:"OK",animation:"default",title:"Alert",callback:function(){}};if(options=angular.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Alert dialog must contain a message.");createAlertDialog(options.title,options.message||options.messageHTML,[options.buttonLabel],0,options.modifier,options.animation,options.callback,options.message?!1:!0,!1,!1,!1)},confirm:function(options){var defaults={buttonLabels:["Cancel","OK"],primaryButtonIndex:1,animation:"default",title:"Confirm",callback:function(){},cancelable:!1};if(options=angular.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Confirm dialog must contain a message.");createAlertDialog(options.title,options.message||options.messageHTML,options.buttonLabels,options.primaryButtonIndex,options.modifier,options.animation,options.callback,options.message?!1:!0,options.cancelable,!1,!1)},prompt:function(options){var defaults={buttonLabel:"OK",animation:"default",title:"Alert",placeholder:"",callback:function(){},cancelable:!1,autofocus:!0};if(options=angular.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Prompt dialog must contain a message.");createAlertDialog(options.title,options.message||options.messageHTML,[options.buttonLabel],0,options.modifier,options.animation,options.callback,options.message?!1:!0,options.cancelable,!0,options.autofocus,options.placeholder)}}}(),window.ons.orientation=function(){function create(){var obj={_isPortrait:!1,isPortrait:function(){return this._isPortrait()},isLandscape:function(){return!this.isPortrait()},_init:function(){return document.addEventListener("DOMContentLoaded",this._onDOMContentLoaded.bind(this),!1),"orientation"in window?window.addEventListener("orientationchange",this._onOrientationChange.bind(this),!1):window.addEventListener("resize",this._onResize.bind(this),!1),this._isPortrait=function(){return window.innerHeight>window.innerWidth},this},_onDOMContentLoaded:function(){this._installIsPortraitImplementation(),this.emit("change",{isPortrait:this.isPortrait()})},_installIsPortraitImplementation:function(){var isPortrait=window.innerWidth<window.innerHeight;this._isPortrait="orientation"in window?window.orientation%180===0?function(){return 0===Math.abs(window.orientation%180)?isPortrait:!isPortrait}:function(){return 90===Math.abs(window.orientation%180)?isPortrait:!isPortrait}:function(){return window.innerHeight>window.innerWidth}},_onOrientationChange:function(){var isPortrait=this._isPortrait(),nIter=0,interval=setInterval(function(){nIter++;var w=window.innerWidth,h=window.innerHeight;isPortrait&&h>=w||!isPortrait&&w>=h?(this.emit("change",{isPortrait:isPortrait}),clearInterval(interval)):50===nIter&&(this.emit("change",{isPortrait:isPortrait}),clearInterval(interval))}.bind(this),20)},_onResize:function(){this.emit("change",{isPortrait:this.isPortrait()})}};return MicroEvent.mixin(obj),obj}return create()._init()}(),function(){"use strict";window.ons.platform={isWebView:function(){return ons.isWebView()},isIOS:function(){return/iPhone|iPad|iPod/i.test(navigator.userAgent)},isAndroid:function(){return/Android/i.test(navigator.userAgent)},isIPhone:function(){return/iPhone/i.test(navigator.userAgent)},isIPad:function(){return/iPad/i.test(navigator.userAgent)},isBlackBerry:function(){return/BlackBerry|RIM Tablet OS|BB10/i.test(navigator.userAgent)},isOpera:function(){return!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0},isFirefox:function(){return"undefined"!=typeof InstallTrigger},isSafari:function(){return Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0},isChrome:function(){return!!window.chrome&&!(window.opera||navigator.userAgent.indexOf(" OPR/")>=0)},isIE:function(){return!1||!!document.documentMode},isIOS7above:function(){if(/iPhone|iPad|iPod/i.test(navigator.userAgent)){var ver=(navigator.userAgent.match(/\b[0-9]+_[0-9]+(?:_[0-9]+)?\b/)||[""])[0].replace(/_/g,".");return parseInt(ver.split(".")[0])>=7}return!1}}}(),function(){"use strict";window.addEventListener("load",function(){FastClick.attach(document.body)},!1),(new Viewport).setup(),Modernizr.testStyles("#modernizr { -webkit-overflow-scrolling:touch }",function(elem,rule){Modernizr.addTest("overflowtouch",window.getComputedStyle&&"touch"==window.getComputedStyle(elem).getPropertyValue("-webkit-overflow-scrolling"))}),window.jQuery&&angular.element===window.jQuery&&console.warn("Onsen UI require jqLite. Load jQuery after loading AngularJS to fix this error. jQuery may break Onsen UI behavior.")}(),function(){"use strict";angular.module("onsen").run(["$templateCache",function($templateCache){for(var templates=window.document.querySelectorAll('script[type="text/ons-template"]'),i=0;i<templates.length;i++){var template=angular.element(templates[i]),id=template.attr("id");"string"==typeof id&&$templateCache.put(id,template.text())}}])}();
components/analytics/iot-analytics/org.wso2.carbon.device.mgt.cdmf.analytics/src/main/resources/carbonapps/GadgetFilteredBy_1.0.0/filtered-by/js/jquery.js
milanperera/carbon-device-mgt-plugins
/*! * jQuery JavaScript Library v1.10.2 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03T13:48Z */ (function( window, undefined ) { // 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+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<10 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.10.2", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.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 splitting on whitespace core_rnotwhite = /\S+/g, // 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) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\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+(?:[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 completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { 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; // scripts is true for back-compat 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 ) { // 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: $(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 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 default length of a jQuery object is 0 length: 0, 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 ) { // 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 ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_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] ] : [] ); }, 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 src, copyIsArray, copy, name, options, 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({ // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), 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 ); } // 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 ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { var key; // 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; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( jQuery.support.ownLast ) { for ( key in obj ) { return core_hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. 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 // keepScripts (optional): If true, will include scripts passed in the html string 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 ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( 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 && jQuery.trim( 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 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; }, // 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 ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( 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, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // 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 ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_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 args, proxy, tmp; 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 || this, 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, raw ) { var i = 0, length = 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 < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); }, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. 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; } }); 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 ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // 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 ); } // detach all dom ready events detach(); // 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 Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.10.2 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // 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(), hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } 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 + "*" ), rsibling = new RegExp( 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" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, 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 : // BMP codepoint high < 0 ? 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 #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 ) && 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]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ 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; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * 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 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.attachEvent && parent !== parent.top ) { parent.attachEvent( "onbeforeunload", 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 = 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><option selected=''></option></select>"; // 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: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + 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 ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? 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 = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // 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 || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else 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 ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; 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 ); } } 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 for ( ; (node = elem[i]); 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 (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 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 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 "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { 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; // 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" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // 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 data, cache, outerCache, dirkey = 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 ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { 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 ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, 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 ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (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; cachedruns = ++matcherCachedRuns; } } // 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 ) && 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 ) ); 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 (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } }); } 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 ); // 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( core_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 // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // 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 action = tuple[ 0 ], 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[ action + "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 = 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( support ) { var all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Finish early in limited (non-browser) environments all = div.getElementsByTagName("*") || []; a = div.getElementsByTagName("a")[ 0 ]; if ( !a || !a.style || !all.length ) { return support; } // 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"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName("tbody").length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName("link").length; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.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 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // 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) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Will be defined later support.inlineBlockNeedsLayout = false; support.shrinkWrapBlocks = false; support.pixelPosition = false; support.deleteExpando = true; support.noCloneEvent = true; support.reliableMarginRight = true; support.boxSizingReliable = true; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: IE<9 // Iteration over object's inherited properties before its own. for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", 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 = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // 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). 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"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height 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%;"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use 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. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })({}); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // 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)) && data === undefined && typeof name === "string" ) { 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 ) { id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { 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 ( typeof name === "string" ) { // 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; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, 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(" "); } } } else { // 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 = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( 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(thisCache) : !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) /* jshint eqeqeq: false */ } else if ( jQuery.support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "applet": true, "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } 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 attrs, name, data = null, i = 0, elem = this[0]; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( name.indexOf("data-") === 0 ) { name = jQuery.camelCase( name.slice(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 ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; }, 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" ); jQuery._removeData( elem, 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 ); }); }, // 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, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; 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 classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; 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( core_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 + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_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 + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } 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( core_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 === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( 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 ? "" : 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 ret, hooks, 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: { option: { get: function( elem ) { // Use proper attribute retrieval(#6932, #12072) var val = jQuery.find.attr( elem, "value" ); return val != null ? val : 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 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; } } }, 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 === core_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( core_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 if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { 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 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; } } } }, 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 ) { // 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/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // 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 if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; jQuery.expr.attrHandle[ name ] = fn; return ret; } : function( elem, name, isXML ) { return isXML ? undefined : elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = // Some attributes are constructed with empty-string values when not defined function( elem, name, isXML ) { var ret; return isXML ? undefined : (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; }; jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ret.specified ? ret.value : undefined; }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // 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 ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || 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 = { 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; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // 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 ( !jQuery.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; }; } }); var rformElems = /^(?:input|select|textarea)$/i, 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 tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( 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 !== core_strundefined && (!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 types = ( types || "" ).match( core_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/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; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, 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 = ( types || "" ).match( core_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; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_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 = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native 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( eventPath.pop(), data ) === false) && 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) if ( ontype && 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; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } 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, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( 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 sel, handleObj, matches, i, 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") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (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; }, 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: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // 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 fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, 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; } }, 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 ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, 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 ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { 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 ) { // Even when returnValue equals to undefined Firefox will still show alert 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 = 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 ] === core_strundefined ) { 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; }; // 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 ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // 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; // 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, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", 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, "changeBubbles" ) ) { 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, "changeBubbles", 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 type, origFn; // 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 isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, 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, ret = [], self = this, len = self.length; 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; }, 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 || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, 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; }, 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++ ) { 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)) ) { cur = ret.push( cur ); break; } } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // 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 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( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); 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 ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); jQuery.extend({ 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; })); }, 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, 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 ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } 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, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), 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, manipulation_rcheckableType = /^(?:checkbox|radio)$/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 = { 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>" ], // 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. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, 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; 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 ); }, 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 ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { 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++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } 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( 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 // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, 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" || jQuery.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, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && 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 ) { 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 || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? 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 = (jQuery.find.attr( elem, "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 elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } 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 fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { 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" && manipulation_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.defaultSelected = 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; } } 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 ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); 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) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, 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; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { 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 || safe.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; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } 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( safe.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 ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, 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 ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); jQuery.fn.extend({ 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(); } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, 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" ]; // 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 ) { // 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 ); } 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 ] = jQuery._data( 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 ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( 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.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, 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(); } }); } }); 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": 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"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.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 ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, 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; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { 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 ) ) { // 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; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, 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; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } 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.support.boxSizing && 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 && ( 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, styles ) ) + "px"; } // Try to determine the default display value of an element function css_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'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); 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 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.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 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 === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && 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 is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || 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 ) { 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" ] ); } } }; } // 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 ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { 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.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( 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 = 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; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; 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 || !manipulation_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(); } }); //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 { // 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 ); } } 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 // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, 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 = /^\/\//, 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 = "*/".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( core_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 deep, key, 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; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, 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"; } // 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; }; // 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.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 // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // 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 (#5866: IE7 issue with protocol-less urls) // 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( core_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 += ( ajax_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_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_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 }); }; }); /* 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 firstDataType, ct, finalDataType, type, 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 }; } // 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 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 || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; 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 ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_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 += ( ajax_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"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // 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 xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { 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( err ) {} // 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, responseHeaders, statusText, responses; // 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 { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !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 ); } 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( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_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() ); } 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 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 ); } 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 ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( 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 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.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" ) ) { 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 = jQuery._data( 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; jQuery._removeData( 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 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: IE <=9 // 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" ? 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, or finishing resolves immediately if ( empty || jQuery._data( 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 = 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 ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( 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; }); } }); // 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 ) ) { jQuery.fx.start(); } }; 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 }; // 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; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 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 !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { 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 offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's 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 // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 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 = /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, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // 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; } ); } } })( window );
src/svg-icons/action/view-stream.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionViewStream = (props) => ( <SvgIcon {...props}> <path d="M4 18h17v-6H4v6zM4 5v6h17V5H4z"/> </SvgIcon> ); ActionViewStream = pure(ActionViewStream); ActionViewStream.displayName = 'ActionViewStream'; ActionViewStream.muiName = 'SvgIcon'; export default ActionViewStream;
ajax/libs/6to5/1.14.7/browser-polyfill.js
vfonic/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){(function(global){var ensureSymbol=function(key){Symbol[key]=Symbol[key]||Symbol()};var ensureProto=function(Constructor,key,val){var proto=Constructor.prototype;proto[key]=proto[key]||val};if(typeof Symbol==="undefined"){require("es6-symbol/implement")}require("es6-shim");require("./transformation/transformers/es6-generators/runtime");ensureSymbol("referenceGet");ensureSymbol("referenceSet");ensureSymbol("referenceDelete");ensureProto(Function,Symbol.referenceGet,function(){return this});ensureProto(Map,Symbol.referenceGet,Map.prototype.get);ensureProto(Map,Symbol.referenceSet,Map.prototype.set);ensureProto(Map,Symbol.referenceDelete,Map.prototype.delete);if(global.WeakMap){ensureProto(WeakMap,Symbol.referenceGet,WeakMap.prototype.get);ensureProto(WeakMap,Symbol.referenceSet,WeakMap.prototype.set);ensureProto(WeakMap,Symbol.referenceDelete,WeakMap.prototype.delete)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./transformation/transformers/es6-generators/runtime":2,"es6-shim":4,"es6-symbol/implement":5}],2:[function(require,module,exports){(function(global){var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var runtime=global.regeneratorRuntime=exports;var hasOwn=Object.prototype.hasOwnProperty;var wrap=runtime.wrap=function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])};var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};var GF=function GeneratorFunction(){};var GFp=function GeneratorFunctionPrototype(){};var Gp=GFp.prototype=Generator.prototype;(GFp.constructor=GF).prototype=Gp.constructor=GFp;var GFName="GeneratorFunction";if(GF.name!==GFName)GF.name=GFName;if(GF.name!==GFName)throw new Error(GFName+" renamed?");runtime.isGeneratorFunction=function(genFun){var ctor=genFun&&genFun.constructor;return ctor?GF.name===ctor.name:false};runtime.mark=function(genFun){genFun.__proto__=GFp;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){var info;var value;try{info=this(arg);value=info.value}catch(error){return reject(error)}if(info.done){resolve(value)}else{Promise.resolve(value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){throw new Error("Generator has already finished")}while(true){var delegate=context.delegate;var info;if(delegate){try{info=delegate.iterator[method](arg);method="next";arg=undefined}catch(uncaught){context.delegate=null;method="throw";arg=uncaught;continue}if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;try{var value=innerFn.call(self,context);state=context.done?GenStateCompleted:GenStateSuspendedYield;info={value:value,done:context.done};if(value===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}catch(thrown){state=GenStateCompleted;if(method==="next"){context.dispatchException(thrown)}else{arg=thrown}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){var iterator=iterable;if(iteratorSymbol in iterable){iterator=iterable[iteratorSymbol]()}else if(!isNaN(iterable.length)){var i=-1;iterator=function next(){while(++i<iterable.length){if(i in iterable){next.value=iterable[i];next.done=false;return next}}next.done=true;return next};iterator.next=iterator}return iterator}runtime.values=values;Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;var thrown;if(record.type==="throw"){thrown=record.arg;resetTryEntry(entry,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],3:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){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")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],4:[function(require,module,exports){(function(process){(function(root,factory){if(typeof define==="function"&&define.amd){define(factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.returnExports=factory()}})(this,function(){"use strict";var isCallableWithoutNew=function(func){try{func()}catch(e){return false}return true};var supportsSubclassing=function(C,f){try{var Sub=function(){C.apply(this,arguments)};if(!Sub.__proto__){return false}Object.setPrototypeOf(Sub,C);Sub.prototype=Object.create(C.prototype,{constructor:{value:C}});return f(Sub)}catch(e){return false}};var arePropertyDescriptorsSupported=function(){try{Object.defineProperty({},"x",{});return true}catch(e){return false}};var startsWithRejectsRegex=function(){var rejectsRegex=false;if(String.prototype.startsWith){try{"/a/".startsWith(/a/)}catch(e){rejectsRegex=true}}return rejectsRegex};var getGlobal=new Function("return this;");var globals=getGlobal();var global_isFinite=globals.isFinite;var supportsDescriptors=!!Object.defineProperty&&arePropertyDescriptorsSupported();var startsWithIsCompliant=startsWithRejectsRegex();var _slice=Array.prototype.slice;var _indexOf=String.prototype.indexOf;var _toString=Object.prototype.toString;var _hasOwnProperty=Object.prototype.hasOwnProperty;var ArrayIterator;var defineProperty=function(object,name,value,force){if(!force&&name in object){return}if(supportsDescriptors){Object.defineProperty(object,name,{configurable:true,enumerable:false,writable:true,value:value})}else{object[name]=value}};var defineProperties=function(object,map){Object.keys(map).forEach(function(name){var method=map[name];defineProperty(object,name,method,false)})};var create=Object.create||function(prototype,properties){function Type(){}Type.prototype=prototype;var object=new Type;if(typeof properties!=="undefined"){defineProperties(object,properties)}return object};var $iterator$=typeof Symbol==="function"&&Symbol.iterator||"_es6-shim iterator_";if(globals.Set&&typeof(new globals.Set)["@@iterator"]==="function"){$iterator$="@@iterator"}var addIterator=function(prototype,impl){if(!impl){impl=function iterator(){return this}}var o={};o[$iterator$]=impl;defineProperties(prototype,o);if(!prototype[$iterator$]&&typeof $iterator$==="symbol"){prototype[$iterator$]=impl}};var isArguments=function isArguments(value){var str=_toString.call(value);var result=str==="[object Arguments]";if(!result){result=str!=="[object Array]"&&value!==null&&typeof value==="object"&&typeof value.length==="number"&&value.length>=0&&_toString.call(value.callee)==="[object Function]"}return result};var emulateES6construct=function(o){if(!ES.TypeIsObject(o)){throw new TypeError("bad object")}if(!o._es6construct){if(o.constructor&&ES.IsCallable(o.constructor["@@create"])){o=o.constructor["@@create"](o)}defineProperties(o,{_es6construct:true})}return o};var ES={CheckObjectCoercible:function(x,optMessage){if(x==null){throw new TypeError(optMessage||"Cannot call method on "+x)}return x},TypeIsObject:function(x){return x!=null&&Object(x)===x},ToObject:function(o,optMessage){return Object(ES.CheckObjectCoercible(o,optMessage))},IsCallable:function(x){return typeof x==="function"&&_toString.call(x)==="[object Function]"},ToInt32:function(x){return x>>0},ToUint32:function(x){return x>>>0},ToInteger:function(value){var number=+value;if(Number.isNaN(number)){return 0}if(number===0||!Number.isFinite(number)){return number}return(number>0?1:-1)*Math.floor(Math.abs(number))},ToLength:function(value){var len=ES.ToInteger(value);if(len<=0){return 0}if(len>Number.MAX_SAFE_INTEGER){return Number.MAX_SAFE_INTEGER}return len},SameValue:function(a,b){if(a===b){if(a===0){return 1/a===1/b}return true}return Number.isNaN(a)&&Number.isNaN(b)},SameValueZero:function(a,b){return a===b||Number.isNaN(a)&&Number.isNaN(b)},IsIterable:function(o){return ES.TypeIsObject(o)&&(typeof o[$iterator$]!=="undefined"||isArguments(o))},GetIterator:function(o){if(isArguments(o)){return new ArrayIterator(o,"value")}var itFn=o[$iterator$];if(!ES.IsCallable(itFn)){throw new TypeError("value is not an iterable")}var it=itFn.call(o);if(!ES.TypeIsObject(it)){throw new TypeError("bad iterator")}return it},IteratorNext:function(it){var result=arguments.length>1?it.next(arguments[1]):it.next();if(!ES.TypeIsObject(result)){throw new TypeError("bad iterator")}return result},Construct:function(C,args){var obj;if(ES.IsCallable(C["@@create"])){obj=C["@@create"]()}else{obj=create(C.prototype||null)}defineProperties(obj,{_es6construct:true});var result=C.apply(obj,args);return ES.TypeIsObject(result)?result:obj}};var numberConversion=function(){function roundToEven(n){var w=Math.floor(n),f=n-w;if(f<.5){return w}if(f>.5){return w+1}return w%2?w+1:w}function packIEEE754(v,ebits,fbits){var bias=(1<<ebits-1)-1,s,e,f,i,bits,str,bytes;if(v!==v){e=(1<<ebits)-1;f=Math.pow(2,fbits-1);s=0}else if(v===Infinity||v===-Infinity){e=(1<<ebits)-1;f=0;s=v<0?1:0}else if(v===0){e=0;f=0;s=1/v===-Infinity?1:0}else{s=v<0;v=Math.abs(v);if(v>=Math.pow(2,1-bias)){e=Math.min(Math.floor(Math.log(v)/Math.LN2),1023);f=roundToEven(v/Math.pow(2,e)*Math.pow(2,fbits));if(f/Math.pow(2,fbits)>=2){e=e+1;f=1}if(e>bias){e=(1<<ebits)-1;f=0}else{e=e+bias;f=f-Math.pow(2,fbits)}}else{e=0;f=roundToEven(v/Math.pow(2,1-bias-fbits))}}bits=[];for(i=fbits;i;i-=1){bits.push(f%2?1:0);f=Math.floor(f/2)}for(i=ebits;i;i-=1){bits.push(e%2?1:0);e=Math.floor(e/2)}bits.push(s?1:0);bits.reverse();str=bits.join("");bytes=[];while(str.length){bytes.push(parseInt(str.slice(0,8),2));str=str.slice(8)}return bytes}function unpackIEEE754(bytes,ebits,fbits){var bits=[],i,j,b,str,bias,s,e,f;for(i=bytes.length;i;i-=1){b=bytes[i-1];for(j=8;j;j-=1){bits.push(b%2?1:0);b=b>>1}}bits.reverse();str=bits.join("");bias=(1<<ebits-1)-1;s=parseInt(str.slice(0,1),2)?-1:1;e=parseInt(str.slice(1,1+ebits),2);f=parseInt(str.slice(1+ebits),2);if(e===(1<<ebits)-1){return f!==0?NaN:s*Infinity}else if(e>0){return s*Math.pow(2,e-bias)*(1+f/Math.pow(2,fbits))}else if(f!==0){return s*Math.pow(2,-(bias-1))*(f/Math.pow(2,fbits))}else{return s<0?-0:0}}function unpackFloat64(b){return unpackIEEE754(b,11,52)}function packFloat64(v){return packIEEE754(v,11,52)}function unpackFloat32(b){return unpackIEEE754(b,8,23)}function packFloat32(v){return packIEEE754(v,8,23)}var conversions={toFloat32:function(num){return unpackFloat32(packFloat32(num))}};if(typeof Float32Array!=="undefined"){var float32array=new Float32Array(1);conversions.toFloat32=function(num){float32array[0]=num;return float32array[0]}}return conversions}();defineProperties(String,{fromCodePoint:function fromCodePoint(_){var result=[];var next;for(var i=0,length=arguments.length;i<length;i++){next=Number(arguments[i]);if(!ES.SameValue(next,ES.ToInteger(next))||next<0||next>1114111){throw new RangeError("Invalid code point "+next)}if(next<65536){result.push(String.fromCharCode(next))}else{next-=65536;result.push(String.fromCharCode((next>>10)+55296));result.push(String.fromCharCode(next%1024+56320))}}return result.join("")},raw:function raw(callSite){var cooked=ES.ToObject(callSite,"bad callSite");var rawValue=cooked.raw;var rawString=ES.ToObject(rawValue,"bad raw value");var len=rawString.length;var literalsegments=ES.ToLength(len);if(literalsegments<=0){return""}var stringElements=[];var nextIndex=0;var nextKey,next,nextSeg,nextSub;while(nextIndex<literalsegments){nextKey=String(nextIndex);next=rawString[nextKey];nextSeg=String(next);stringElements.push(nextSeg);if(nextIndex+1>=literalsegments){break}next=nextIndex+1<arguments.length?arguments[nextIndex+1]:"";nextSub=String(next);stringElements.push(nextSub);nextIndex++}return stringElements.join("")}});if(String.fromCodePoint.length!==1){var originalFromCodePoint=String.fromCodePoint;defineProperty(String,"fromCodePoint",function(_){return originalFromCodePoint.apply(this,arguments)},true)}var StringShims={repeat:function(){var repeat=function(s,times){if(times<1){return""}if(times%2){return repeat(s,times-1)+s}var half=repeat(s,times/2);return half+half};return function(times){var thisStr=String(ES.CheckObjectCoercible(this));times=ES.ToInteger(times);if(times<0||times===Infinity){throw new RangeError("Invalid String#repeat value")}return repeat(thisStr,times)}}(),startsWith:function(searchStr){var thisStr=String(ES.CheckObjectCoercible(this));if(_toString.call(searchStr)==="[object RegExp]"){throw new TypeError('Cannot call method "startsWith" with a regex')}searchStr=String(searchStr);var startArg=arguments.length>1?arguments[1]:void 0;var start=Math.max(ES.ToInteger(startArg),0);return thisStr.slice(start,start+searchStr.length)===searchStr},endsWith:function(searchStr){var thisStr=String(ES.CheckObjectCoercible(this));if(_toString.call(searchStr)==="[object RegExp]"){throw new TypeError('Cannot call method "endsWith" with a regex')}searchStr=String(searchStr);var thisLen=thisStr.length;var posArg=arguments.length>1?arguments[1]:void 0;var pos=typeof posArg==="undefined"?thisLen:ES.ToInteger(posArg);var end=Math.min(Math.max(pos,0),thisLen);return thisStr.slice(end-searchStr.length,end)===searchStr},includes:function includes(searchString){var position=arguments.length>1?arguments[1]:void 0;return _indexOf.call(this,searchString,position)!==-1},codePointAt:function(pos){var thisStr=String(ES.CheckObjectCoercible(this));var position=ES.ToInteger(pos);var length=thisStr.length;if(position<0||position>=length){return}var first=thisStr.charCodeAt(position);var isEnd=position+1===length;if(first<55296||first>56319||isEnd){return first}var second=thisStr.charCodeAt(position+1);if(second<56320||second>57343){return first}return(first-55296)*1024+(second-56320)+65536}};defineProperties(String.prototype,StringShims);var hasStringTrimBug="…".trim().length!==1;if(hasStringTrimBug){var originalStringTrim=String.prototype.trim;delete String.prototype.trim;var ws=[" \n \f\r   ᠎    ","          \u2028","\u2029"].join("");var trimRegexp=new RegExp("(^["+ws+"]+)|(["+ws+"]+$)","g");defineProperties(String.prototype,{trim:function(){if(typeof this==="undefined"||this===null){throw new TypeError("can't convert "+this+" to object")}return String(this).replace(trimRegexp,"")}})}var StringIterator=function(s){this._s=String(ES.CheckObjectCoercible(s));this._i=0};StringIterator.prototype.next=function(){var s=this._s,i=this._i;if(typeof s==="undefined"||i>=s.length){this._s=void 0;return{value:void 0,done:true}}var first=s.charCodeAt(i),second,len;if(first<55296||first>56319||i+1==s.length){len=1}else{second=s.charCodeAt(i+1);len=second<56320||second>57343?1:2}this._i=i+len;return{value:s.substr(i,len),done:false}};addIterator(StringIterator.prototype);addIterator(String.prototype,function(){return new StringIterator(this)});if(!startsWithIsCompliant){String.prototype.startsWith=StringShims.startsWith;String.prototype.endsWith=StringShims.endsWith}var ArrayShims={from:function(iterable){var mapFn=arguments.length>1?arguments[1]:void 0;var list=ES.ToObject(iterable,"bad iterable");if(typeof mapFn!=="undefined"&&!ES.IsCallable(mapFn)){throw new TypeError("Array.from: when provided, the second argument must be a function")}var hasThisArg=arguments.length>2;var thisArg=hasThisArg?arguments[2]:void 0;var usingIterator=ES.IsIterable(list);var length;var result,i,value;if(usingIterator){i=0;result=ES.IsCallable(this)?Object(new this):[];var it=usingIterator?ES.GetIterator(list):null;var iterationValue;do{iterationValue=ES.IteratorNext(it);if(!iterationValue.done){value=iterationValue.value;if(mapFn){result[i]=hasThisArg?mapFn.call(thisArg,value,i):mapFn(value,i)}else{result[i]=value}i+=1}}while(!iterationValue.done);length=i}else{length=ES.ToLength(list.length);result=ES.IsCallable(this)?Object(new this(length)):new Array(length);for(i=0;i<length;++i){value=list[i];if(mapFn){result[i]=hasThisArg?mapFn.call(thisArg,value,i):mapFn(value,i)}else{result[i]=value}}}result.length=length;return result},of:function(){return Array.from(arguments)}};defineProperties(Array,ArrayShims);var arrayFromSwallowsNegativeLengths=function(){try{return Array.from({length:-1}).length===0}catch(e){return false}};if(!arrayFromSwallowsNegativeLengths()){defineProperty(Array,"from",ArrayShims.from,true)}ArrayIterator=function(array,kind){this.i=0;this.array=array;this.kind=kind};defineProperties(ArrayIterator.prototype,{next:function(){var i=this.i,array=this.array;if(!(this instanceof ArrayIterator)){throw new TypeError("Not an ArrayIterator")}if(typeof array!=="undefined"){var len=ES.ToLength(array.length);for(;i<len;i++){var kind=this.kind;var retval;if(kind==="key"){retval=i}else if(kind==="value"){retval=array[i]}else if(kind==="entry"){retval=[i,array[i]]}this.i=i+1;return{value:retval,done:false}}}this.array=void 0;return{value:void 0,done:true}}});addIterator(ArrayIterator.prototype);var ArrayPrototypeShims={copyWithin:function(target,start){var end=arguments[2];var o=ES.ToObject(this);var len=ES.ToLength(o.length);target=ES.ToInteger(target);start=ES.ToInteger(start);var to=target<0?Math.max(len+target,0):Math.min(target,len);var from=start<0?Math.max(len+start,0):Math.min(start,len);end=typeof end==="undefined"?len:ES.ToInteger(end);var fin=end<0?Math.max(len+end,0):Math.min(end,len);var count=Math.min(fin-from,len-to);var direction=1;if(from<to&&to<from+count){direction=-1;from+=count-1;to+=count-1}while(count>0){if(_hasOwnProperty.call(o,from)){o[to]=o[from]}else{delete o[from]}from+=direction;to+=direction;count-=1}return o},fill:function(value){var start=arguments.length>1?arguments[1]:void 0;var end=arguments.length>2?arguments[2]:void 0;var O=ES.ToObject(this);var len=ES.ToLength(O.length);start=ES.ToInteger(typeof start==="undefined"?0:start);end=ES.ToInteger(typeof end==="undefined"?len:end);var relativeStart=start<0?Math.max(len+start,0):Math.min(start,len);var relativeEnd=end<0?len+end:end;for(var i=relativeStart;i<len&&i<relativeEnd;++i){O[i]=value}return O},find:function find(predicate){var list=ES.ToObject(this);var length=ES.ToLength(list.length);if(!ES.IsCallable(predicate)){throw new TypeError("Array#find: predicate must be a function")}var thisArg=arguments.length>1?arguments[1]:null;for(var i=0,value;i<length;i++){value=list[i];if(thisArg){if(predicate.call(thisArg,value,i,list)){return value}}else{if(predicate(value,i,list)){return value}}}return},findIndex:function findIndex(predicate){var list=ES.ToObject(this);var length=ES.ToLength(list.length);if(!ES.IsCallable(predicate)){throw new TypeError("Array#findIndex: predicate must be a function")}var thisArg=arguments.length>1?arguments[1]:null;for(var i=0;i<length;i++){if(thisArg){if(predicate.call(thisArg,list[i],i,list)){return i}}else{if(predicate(list[i],i,list)){return i}}}return-1},keys:function(){return new ArrayIterator(this,"key")},values:function(){return new ArrayIterator(this,"value")},entries:function(){return new ArrayIterator(this,"entry")}};if(Array.prototype.keys&&!ES.IsCallable([1].keys().next)){delete Array.prototype.keys}if(Array.prototype.entries&&!ES.IsCallable([1].entries().next)){delete Array.prototype.entries}if(Array.prototype.keys&&Array.prototype.entries&&!Array.prototype.values&&Array.prototype[$iterator$]){defineProperties(Array.prototype,{values:Array.prototype[$iterator$]})}defineProperties(Array.prototype,ArrayPrototypeShims);addIterator(Array.prototype,function(){return this.values()});if(Object.getPrototypeOf){addIterator(Object.getPrototypeOf([].values()))}var maxSafeInteger=Math.pow(2,53)-1;defineProperties(Number,{MAX_SAFE_INTEGER:maxSafeInteger,MIN_SAFE_INTEGER:-maxSafeInteger,EPSILON:2.220446049250313e-16,parseInt:globals.parseInt,parseFloat:globals.parseFloat,isFinite:function(value){return typeof value==="number"&&global_isFinite(value)},isInteger:function(value){return Number.isFinite(value)&&ES.ToInteger(value)===value},isSafeInteger:function(value){return Number.isInteger(value)&&Math.abs(value)<=Number.MAX_SAFE_INTEGER},isNaN:function(value){return value!==value}});if(![,1].find(function(item,idx){return idx===0})){defineProperty(Array.prototype,"find",ArrayPrototypeShims.find,true)}if([,1].findIndex(function(item,idx){return idx===0})!==0){defineProperty(Array.prototype,"findIndex",ArrayPrototypeShims.findIndex,true)}if(supportsDescriptors){defineProperties(Object,{getPropertyDescriptor:function(subject,name){var pd=Object.getOwnPropertyDescriptor(subject,name);var proto=Object.getPrototypeOf(subject);while(typeof pd==="undefined"&&proto!==null){pd=Object.getOwnPropertyDescriptor(proto,name);proto=Object.getPrototypeOf(proto)}return pd},getPropertyNames:function(subject){var result=Object.getOwnPropertyNames(subject);var proto=Object.getPrototypeOf(subject);var addProperty=function(property){if(result.indexOf(property)===-1){result.push(property)}};while(proto!==null){Object.getOwnPropertyNames(proto).forEach(addProperty);proto=Object.getPrototypeOf(proto)}return result}});defineProperties(Object,{assign:function(target,source){if(!ES.TypeIsObject(target)){throw new TypeError("target must be an object")}return Array.prototype.reduce.call(arguments,function(target,source){return Object.keys(Object(source)).reduce(function(target,key){target[key]=source[key];return target},target)})},is:function(a,b){return ES.SameValue(a,b)},setPrototypeOf:function(Object,magic){var set;var checkArgs=function(O,proto){if(!ES.TypeIsObject(O)){throw new TypeError("cannot set prototype on a non-object")}if(!(proto===null||ES.TypeIsObject(proto))){throw new TypeError("can only set prototype to an object or null"+proto)}};var setPrototypeOf=function(O,proto){checkArgs(O,proto);set.call(O,proto);return O};try{set=Object.getOwnPropertyDescriptor(Object.prototype,magic).set;set.call({},null)}catch(e){if(Object.prototype!=={}[magic]){return}set=function(proto){this[magic]=proto};setPrototypeOf.polyfill=setPrototypeOf(setPrototypeOf({},null),Object.prototype)instanceof Object}return setPrototypeOf}(Object,"__proto__")})}if(Object.setPrototypeOf&&Object.getPrototypeOf&&Object.getPrototypeOf(Object.setPrototypeOf({},null))!==null&&Object.getPrototypeOf(Object.create(null))===null){(function(){var FAKENULL=Object.create(null);var gpo=Object.getPrototypeOf,spo=Object.setPrototypeOf;Object.getPrototypeOf=function(o){var result=gpo(o);return result===FAKENULL?null:result};Object.setPrototypeOf=function(o,p){if(p===null){p=FAKENULL}return spo(o,p)};Object.setPrototypeOf.polyfill=false})()}try{Object.keys("foo")}catch(e){var originalObjectKeys=Object.keys;Object.keys=function(obj){return originalObjectKeys(ES.ToObject(obj))}}var MathShims={acosh:function(value){value=Number(value);if(Number.isNaN(value)||value<1){return NaN}if(value===1){return 0}if(value===Infinity){return value}return Math.log(value+Math.sqrt(value*value-1))},asinh:function(value){value=Number(value);if(value===0||!global_isFinite(value)){return value}return value<0?-Math.asinh(-value):Math.log(value+Math.sqrt(value*value+1))},atanh:function(value){value=Number(value);if(Number.isNaN(value)||value<-1||value>1){return NaN}if(value===-1){return-Infinity}if(value===1){return Infinity}if(value===0){return value}return.5*Math.log((1+value)/(1-value))},cbrt:function(value){value=Number(value);if(value===0){return value}var negate=value<0,result;if(negate){value=-value}result=Math.pow(value,1/3);return negate?-result:result},clz32:function(value){value=Number(value);var number=ES.ToUint32(value);if(number===0){return 32}return 32-number.toString(2).length},cosh:function(value){value=Number(value);if(value===0){return 1}if(Number.isNaN(value)){return NaN}if(!global_isFinite(value)){return Infinity}if(value<0){value=-value}if(value>21){return Math.exp(value)/2}return(Math.exp(value)+Math.exp(-value))/2},expm1:function(value){value=Number(value);if(value===-Infinity){return-1}if(!global_isFinite(value)||value===0){return value}return Math.exp(value)-1},hypot:function(x,y){var anyNaN=false;var allZero=true;var anyInfinity=false;var numbers=[];Array.prototype.every.call(arguments,function(arg){var num=Number(arg);if(Number.isNaN(num)){anyNaN=true}else if(num===Infinity||num===-Infinity){anyInfinity=true}else if(num!==0){allZero=false}if(anyInfinity){return false}else if(!anyNaN){numbers.push(Math.abs(num))}return true});if(anyInfinity){return Infinity}if(anyNaN){return NaN}if(allZero){return 0}numbers.sort(function(a,b){return b-a});var largest=numbers[0];var divided=numbers.map(function(number){return number/largest});var sum=divided.reduce(function(sum,number){return sum+=number*number},0);return largest*Math.sqrt(sum)},log2:function(value){return Math.log(value)*Math.LOG2E},log10:function(value){return Math.log(value)*Math.LOG10E},log1p:function(value){value=Number(value);if(value<-1||Number.isNaN(value)){return NaN}if(value===0||value===Infinity){return value}if(value===-1){return-Infinity}var result=0;var n=50;if(value<0||value>1){return Math.log(1+value)}for(var i=1;i<n;i++){if(i%2===0){result-=Math.pow(value,i)/i}else{result+=Math.pow(value,i)/i}}return result},sign:function(value){var number=+value;if(number===0){return number}if(Number.isNaN(number)){return number}return number<0?-1:1},sinh:function(value){value=Number(value);if(!global_isFinite(value)||value===0){return value}return(Math.exp(value)-Math.exp(-value))/2},tanh:function(value){value=Number(value);if(Number.isNaN(value)||value===0){return value}if(value===Infinity){return 1}if(value===-Infinity){return-1}return(Math.exp(value)-Math.exp(-value))/(Math.exp(value)+Math.exp(-value))},trunc:function(value){var number=Number(value);return number<0?-Math.floor(-number):Math.floor(number)},imul:function(x,y){x=ES.ToUint32(x);y=ES.ToUint32(y);var ah=x>>>16&65535;var al=x&65535;var bh=y>>>16&65535;var bl=y&65535;return al*bl+(ah*bl+al*bh<<16>>>0)|0},fround:function(x){if(x===0||x===Infinity||x===-Infinity||Number.isNaN(x)){return x}var num=Number(x);return numberConversion.toFloat32(num) }};defineProperties(Math,MathShims);if(Math.imul(4294967295,5)!==-5){Math.imul=MathShims.imul}var PromiseShim=function(){var Promise,Promise$prototype;ES.IsPromise=function(promise){if(!ES.TypeIsObject(promise)){return false}if(!promise._promiseConstructor){return false}if(typeof promise._status==="undefined"){return false}return true};var PromiseCapability=function(C){if(!ES.IsCallable(C)){throw new TypeError("bad promise constructor")}var capability=this;var resolver=function(resolve,reject){capability.resolve=resolve;capability.reject=reject};capability.promise=ES.Construct(C,[resolver]);if(!capability.promise._es6construct){throw new TypeError("bad promise constructor")}if(!(ES.IsCallable(capability.resolve)&&ES.IsCallable(capability.reject))){throw new TypeError("bad promise constructor")}};var setTimeout=globals.setTimeout;var makeZeroTimeout;if(typeof window!=="undefined"&&ES.IsCallable(window.postMessage)){makeZeroTimeout=function(){var timeouts=[];var messageName="zero-timeout-message";var setZeroTimeout=function(fn){timeouts.push(fn);window.postMessage(messageName,"*")};var handleMessage=function(event){if(event.source==window&&event.data==messageName){event.stopPropagation();if(timeouts.length===0){return}var fn=timeouts.shift();fn()}};window.addEventListener("message",handleMessage,true);return setZeroTimeout}}var makePromiseAsap=function(){var P=globals.Promise;return P&&P.resolve&&function(task){return P.resolve().then(task)}};var enqueue=ES.IsCallable(globals.setImmediate)?globals.setImmediate.bind(globals):typeof process==="object"&&process.nextTick?process.nextTick:makePromiseAsap()||(ES.IsCallable(makeZeroTimeout)?makeZeroTimeout():function(task){setTimeout(task,0)});var triggerPromiseReactions=function(reactions,x){reactions.forEach(function(reaction){enqueue(function(){var handler=reaction.handler;var capability=reaction.capability;var resolve=capability.resolve;var reject=capability.reject;try{var result=handler(x);if(result===capability.promise){throw new TypeError("self resolution")}var updateResult=updatePromiseFromPotentialThenable(result,capability);if(!updateResult){resolve(result)}}catch(e){reject(e)}})})};var updatePromiseFromPotentialThenable=function(x,capability){if(!ES.TypeIsObject(x)){return false}var resolve=capability.resolve;var reject=capability.reject;try{var then=x.then;if(!ES.IsCallable(then)){return false}then.call(x,resolve,reject)}catch(e){reject(e)}return true};var promiseResolutionHandler=function(promise,onFulfilled,onRejected){return function(x){if(x===promise){return onRejected(new TypeError("self resolution"))}var C=promise._promiseConstructor;var capability=new PromiseCapability(C);var updateResult=updatePromiseFromPotentialThenable(x,capability);if(updateResult){return capability.promise.then(onFulfilled,onRejected)}else{return onFulfilled(x)}}};Promise=function(resolver){var promise=this;promise=emulateES6construct(promise);if(!promise._promiseConstructor){throw new TypeError("bad promise")}if(typeof promise._status!=="undefined"){throw new TypeError("promise already initialized")}if(!ES.IsCallable(resolver)){throw new TypeError("not a valid resolver")}promise._status="unresolved";promise._resolveReactions=[];promise._rejectReactions=[];var resolve=function(resolution){if(promise._status!=="unresolved"){return}var reactions=promise._resolveReactions;promise._result=resolution;promise._resolveReactions=void 0;promise._rejectReactions=void 0;promise._status="has-resolution";triggerPromiseReactions(reactions,resolution)};var reject=function(reason){if(promise._status!=="unresolved"){return}var reactions=promise._rejectReactions;promise._result=reason;promise._resolveReactions=void 0;promise._rejectReactions=void 0;promise._status="has-rejection";triggerPromiseReactions(reactions,reason)};try{resolver(resolve,reject)}catch(e){reject(e)}return promise};Promise$prototype=Promise.prototype;defineProperties(Promise,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Promise$prototype;obj=obj||create(prototype);defineProperties(obj,{_status:void 0,_result:void 0,_resolveReactions:void 0,_rejectReactions:void 0,_promiseConstructor:void 0});obj._promiseConstructor=constructor;return obj}});var _promiseAllResolver=function(index,values,capability,remaining){var done=false;return function(x){if(done){return}done=true;values[index]=x;if(--remaining.count===0){var resolve=capability.resolve;resolve(values)}}};Promise.all=function(iterable){var C=this;var capability=new PromiseCapability(C);var resolve=capability.resolve;var reject=capability.reject;try{if(!ES.IsIterable(iterable)){throw new TypeError("bad iterable")}var it=ES.GetIterator(iterable);var values=[],remaining={count:1};for(var index=0;;index++){var next=ES.IteratorNext(it);if(next.done){break}var nextPromise=C.resolve(next.value);var resolveElement=_promiseAllResolver(index,values,capability,remaining);remaining.count++;nextPromise.then(resolveElement,capability.reject)}if(--remaining.count===0){resolve(values)}}catch(e){reject(e)}return capability.promise};Promise.race=function(iterable){var C=this;var capability=new PromiseCapability(C);var resolve=capability.resolve;var reject=capability.reject;try{if(!ES.IsIterable(iterable)){throw new TypeError("bad iterable")}var it=ES.GetIterator(iterable);while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextPromise=C.resolve(next.value);nextPromise.then(resolve,reject)}}catch(e){reject(e)}return capability.promise};Promise.reject=function(reason){var C=this;var capability=new PromiseCapability(C);var reject=capability.reject;reject(reason);return capability.promise};Promise.resolve=function(v){var C=this;if(ES.IsPromise(v)){var constructor=v._promiseConstructor;if(constructor===C){return v}}var capability=new PromiseCapability(C);var resolve=capability.resolve;resolve(v);return capability.promise};Promise.prototype["catch"]=function(onRejected){return this.then(void 0,onRejected)};Promise.prototype.then=function(onFulfilled,onRejected){var promise=this;if(!ES.IsPromise(promise)){throw new TypeError("not a promise")}var C=this.constructor;var capability=new PromiseCapability(C);if(!ES.IsCallable(onRejected)){onRejected=function(e){throw e}}if(!ES.IsCallable(onFulfilled)){onFulfilled=function(x){return x}}var resolutionHandler=promiseResolutionHandler(promise,onFulfilled,onRejected);var resolveReaction={capability:capability,handler:resolutionHandler};var rejectReaction={capability:capability,handler:onRejected};switch(promise._status){case"unresolved":promise._resolveReactions.push(resolveReaction);promise._rejectReactions.push(rejectReaction);break;case"has-resolution":triggerPromiseReactions([resolveReaction],promise._result);break;case"has-rejection":triggerPromiseReactions([rejectReaction],promise._result);break;default:throw new TypeError("unexpected")}return capability.promise};return Promise}();if(globals.Promise){delete globals.Promise.accept;delete globals.Promise.defer;delete globals.Promise.prototype.chain}defineProperties(globals,{Promise:PromiseShim});var promiseSupportsSubclassing=supportsSubclassing(globals.Promise,function(S){return S.resolve(42)instanceof S});var promiseIgnoresNonFunctionThenCallbacks=function(){try{globals.Promise.reject(42).then(null,5).then(null,function(){});return true}catch(ex){return false}}();var promiseRequiresObjectContext=function(){try{Promise.call(3,function(){})}catch(e){return true}return false}();if(!promiseSupportsSubclassing||!promiseIgnoresNonFunctionThenCallbacks||!promiseRequiresObjectContext){globals.Promise=PromiseShim}var testOrder=function(a){var b=Object.keys(a.reduce(function(o,k){o[k]=true;return o},{}));return a.join(":")===b.join(":")};var preservesInsertionOrder=testOrder(["z","a","bb"]);var preservesNumericInsertionOrder=testOrder(["z",1,"a","3",2]);if(supportsDescriptors){var fastkey=function fastkey(key){if(!preservesInsertionOrder){return null}var type=typeof key;if(type==="string"){return"$"+key}else if(type==="number"){if(!preservesNumericInsertionOrder){return"n"+key}return key}return null};var emptyObject=function emptyObject(){return Object.create?Object.create(null):{}};var collectionShims={Map:function(){var empty={};function MapEntry(key,value){this.key=key;this.value=value;this.next=null;this.prev=null}MapEntry.prototype.isRemoved=function(){return this.key===empty};function MapIterator(map,kind){this.head=map._head;this.i=this.head;this.kind=kind}MapIterator.prototype={next:function(){var i=this.i,kind=this.kind,head=this.head,result;if(typeof this.i==="undefined"){return{value:void 0,done:true}}while(i.isRemoved()&&i!==head){i=i.prev}while(i.next!==head){i=i.next;if(!i.isRemoved()){if(kind==="key"){result=i.key}else if(kind==="value"){result=i.value}else{result=[i.key,i.value]}this.i=i;return{value:result,done:false}}}this.i=void 0;return{value:void 0,done:true}}};addIterator(MapIterator.prototype);function Map(iterable){var map=this;if(!ES.TypeIsObject(map)){throw new TypeError("Map does not accept arguments when called as a function")}map=emulateES6construct(map);if(!map._es6map){throw new TypeError("bad map")}var head=new MapEntry(null,null);head.next=head.prev=head;defineProperties(map,{_head:head,_storage:emptyObject(),_size:0});if(typeof iterable!=="undefined"&&iterable!==null){var it=ES.GetIterator(iterable);var adder=map.set;if(!ES.IsCallable(adder)){throw new TypeError("bad map")}while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextItem=next.value;if(!ES.TypeIsObject(nextItem)){throw new TypeError("expected iterable of pairs")}adder.call(map,nextItem[0],nextItem[1])}}return map}var Map$prototype=Map.prototype;defineProperties(Map,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Map$prototype;obj=obj||create(prototype);defineProperties(obj,{_es6map:true});return obj}});Object.defineProperty(Map.prototype,"size",{configurable:true,enumerable:false,get:function(){if(typeof this._size==="undefined"){throw new TypeError("size method called on incompatible Map")}return this._size}});defineProperties(Map.prototype,{get:function(key){var fkey=fastkey(key);if(fkey!==null){var entry=this._storage[fkey];if(entry){return entry.value}else{return}}var head=this._head,i=head;while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){return i.value}}return},has:function(key){var fkey=fastkey(key);if(fkey!==null){return typeof this._storage[fkey]!=="undefined"}var head=this._head,i=head;while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){return true}}return false},set:function(key,value){var head=this._head,i=head,entry;var fkey=fastkey(key);if(fkey!==null){if(typeof this._storage[fkey]!=="undefined"){this._storage[fkey].value=value;return this}else{entry=this._storage[fkey]=new MapEntry(key,value);i=head.prev}}while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){i.value=value;return this}}entry=entry||new MapEntry(key,value);if(ES.SameValue(-0,key)){entry.key=+0}entry.next=this._head;entry.prev=this._head.prev;entry.prev.next=entry;entry.next.prev=entry;this._size+=1;return this},"delete":function(key){var head=this._head,i=head;var fkey=fastkey(key);if(fkey!==null){if(typeof this._storage[fkey]==="undefined"){return false}i=this._storage[fkey].prev;delete this._storage[fkey]}while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){i.key=i.value=empty;i.prev.next=i.next;i.next.prev=i.prev;this._size-=1;return true}}return false},clear:function(){this._size=0;this._storage=emptyObject();var head=this._head,i=head,p=i.next;while((i=p)!==head){i.key=i.value=empty;p=i.next;i.next=i.prev=head}head.next=head.prev=head},keys:function(){return new MapIterator(this,"key")},values:function(){return new MapIterator(this,"value")},entries:function(){return new MapIterator(this,"key+value")},forEach:function(callback){var context=arguments.length>1?arguments[1]:null;var it=this.entries();for(var entry=it.next();!entry.done;entry=it.next()){if(context){callback.call(context,entry.value[1],entry.value[0],this)}else{callback(entry.value[1],entry.value[0],this)}}}});addIterator(Map.prototype,function(){return this.entries()});return Map}(),Set:function(){var SetShim=function Set(iterable){var set=this;if(!ES.TypeIsObject(set)){throw new TypeError("Set does not accept arguments when called as a function")}set=emulateES6construct(set);if(!set._es6set){throw new TypeError("bad set")}defineProperties(set,{"[[SetData]]":null,_storage:emptyObject()});if(typeof iterable!=="undefined"&&iterable!==null){var it=ES.GetIterator(iterable);var adder=set.add;if(!ES.IsCallable(adder)){throw new TypeError("bad set")}while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextItem=next.value;adder.call(set,nextItem)}}return set};var Set$prototype=SetShim.prototype;defineProperties(SetShim,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Set$prototype;obj=obj||create(prototype);defineProperties(obj,{_es6set:true});return obj}});var ensureMap=function ensureMap(set){if(!set["[[SetData]]"]){var m=set["[[SetData]]"]=new collectionShims.Map;Object.keys(set._storage).forEach(function(k){if(k.charCodeAt(0)===36){k=k.slice(1)}else if(k.charAt(0)==="n"){k=+k.slice(1)}else{k=+k}m.set(k,k)});set._storage=null}};Object.defineProperty(SetShim.prototype,"size",{configurable:true,enumerable:false,get:function(){if(typeof this._storage==="undefined"){throw new TypeError("size method called on incompatible Set")}ensureMap(this);return this["[[SetData]]"].size}});defineProperties(SetShim.prototype,{has:function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){return!!this._storage[fkey]}ensureMap(this);return this["[[SetData]]"].has(key)},add:function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){this._storage[fkey]=true;return this}ensureMap(this);this["[[SetData]]"].set(key,key);return this},"delete":function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){var hasFKey=_hasOwnProperty.call(this._storage,fkey);return delete this._storage[fkey]&&hasFKey}ensureMap(this);return this["[[SetData]]"]["delete"](key)},clear:function(){if(this._storage){this._storage=emptyObject();return}return this["[[SetData]]"].clear()},values:function(){ensureMap(this);return this["[[SetData]]"].values()},entries:function(){ensureMap(this);return this["[[SetData]]"].entries()},forEach:function(callback){var context=arguments.length>1?arguments[1]:null;var entireSet=this;ensureMap(entireSet);this["[[SetData]]"].forEach(function(value,key){if(context){callback.call(context,key,key,entireSet)}else{callback(key,key,entireSet)}})}});defineProperty(SetShim,"keys",SetShim.values,true);addIterator(SetShim.prototype,function(){return this.values()});return SetShim}()};defineProperties(globals,collectionShims);if(globals.Map||globals.Set){if(typeof globals.Map.prototype.clear!=="function"||(new globals.Set).size!==0||(new globals.Map).size!==0||typeof globals.Map.prototype.keys!=="function"||typeof globals.Set.prototype.keys!=="function"||typeof globals.Map.prototype.forEach!=="function"||typeof globals.Set.prototype.forEach!=="function"||isCallableWithoutNew(globals.Map)||isCallableWithoutNew(globals.Set)||!supportsSubclassing(globals.Map,function(M){var m=new M([]);m.set(42,42);return m instanceof M})){globals.Map=collectionShims.Map;globals.Set=collectionShims.Set}}if(globals.Set.prototype.keys!==globals.Set.prototype.values){defineProperty(globals.Set.prototype,"keys",globals.Set.prototype.values,true)}addIterator(Object.getPrototypeOf((new globals.Map).keys()));addIterator(Object.getPrototypeOf((new globals.Set).keys()))}return globals})}).call(this,require("_process"))},{_process:3}],5:[function(require,module,exports){"use strict";if(!require("./is-implemented")()){Object.defineProperty(require("es5-ext/global"),"Symbol",{value:require("./polyfill"),configurable:true,enumerable:false,writable:true})}},{"./is-implemented":6,"./polyfill":21,"es5-ext/global":8}],6:[function(require,module,exports){"use strict";module.exports=function(){var symbol;if(typeof Symbol!=="function")return false;symbol=Symbol("test symbol");try{String(symbol)}catch(e){return false}if(typeof Symbol.iterator==="symbol")return true;if(typeof Symbol.isConcatSpreadable!=="object")return false;if(typeof Symbol.isRegExp!=="object")return false;if(typeof Symbol.iterator!=="object")return false;if(typeof Symbol.toPrimitive!=="object")return false;if(typeof Symbol.toStringTag!=="object")return false;if(typeof Symbol.unscopables!=="object")return false;return true}},{}],7:[function(require,module,exports){"use strict";var assign=require("es5-ext/object/assign"),normalizeOpts=require("es5-ext/object/normalize-options"),isCallable=require("es5-ext/object/is-callable"),contains=require("es5-ext/string/#/contains"),d;d=module.exports=function(dscr,value){var c,e,w,options,desc;if(arguments.length<2||typeof dscr!=="string"){options=value;value=dscr;dscr=null}else{options=arguments[2]}if(dscr==null){c=w=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e");w=contains.call(dscr,"w")}desc={value:value,configurable:c,enumerable:e,writable:w};return!options?desc:assign(normalizeOpts(options),desc)};d.gs=function(dscr,get,set){var c,e,options,desc;if(typeof dscr!=="string"){options=set;set=get;get=dscr;dscr=null}else{options=arguments[3]}if(get==null){get=undefined}else if(!isCallable(get)){options=get;get=set=undefined}else if(set==null){set=undefined}else if(!isCallable(set)){options=set;set=undefined}if(dscr==null){c=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e")}desc={get:get,set:set,configurable:c,enumerable:e};return!options?desc:assign(normalizeOpts(options),desc)}},{"es5-ext/object/assign":9,"es5-ext/object/is-callable":12,"es5-ext/object/normalize-options":16,"es5-ext/string/#/contains":18}],8:[function(require,module,exports){"use strict";module.exports=new Function("return this")()},{}],9:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.assign:require("./shim")},{"./is-implemented":10,"./shim":11}],10:[function(require,module,exports){"use strict";module.exports=function(){var assign=Object.assign,obj;if(typeof assign!=="function")return false;obj={foo:"raz"};assign(obj,{bar:"dwa"},{trzy:"trzy"});return obj.foo+obj.bar+obj.trzy==="razdwatrzy"}},{}],11:[function(require,module,exports){"use strict";var keys=require("../keys"),value=require("../valid-value"),max=Math.max;module.exports=function(dest,src){var error,i,l=max(arguments.length,2),assign;dest=Object(value(dest));assign=function(key){try{dest[key]=src[key]}catch(e){if(!error)error=e}};for(i=1;i<l;++i){src=arguments[i];keys(src).forEach(assign)}if(error!==undefined)throw error;return dest}},{"../keys":13,"../valid-value":17}],12:[function(require,module,exports){"use strict";module.exports=function(obj){return typeof obj==="function"}},{}],13:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.keys:require("./shim")},{"./is-implemented":14,"./shim":15}],14:[function(require,module,exports){"use strict";module.exports=function(){try{Object.keys("primitive");return true}catch(e){return false}}},{}],15:[function(require,module,exports){"use strict";var keys=Object.keys;module.exports=function(object){return keys(object==null?object:Object(object))}},{}],16:[function(require,module,exports){"use strict";var assign=require("./assign"),forEach=Array.prototype.forEach,create=Object.create,getPrototypeOf=Object.getPrototypeOf,process;process=function(src,obj){var proto=getPrototypeOf(src);return assign(proto?process(proto,obj):obj,src)};module.exports=function(options){var result=create(null);forEach.call(arguments,function(options){if(options==null)return;process(Object(options),result)});return result}},{"./assign":9}],17:[function(require,module,exports){"use strict";module.exports=function(value){if(value==null)throw new TypeError("Cannot use null or undefined");return value}},{}],18:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?String.prototype.contains:require("./shim")},{"./is-implemented":19,"./shim":20}],19:[function(require,module,exports){"use strict";var str="razdwatrzy";module.exports=function(){if(typeof str.contains!=="function")return false;return str.contains("dwa")===true&&str.contains("foo")===false}},{}],20:[function(require,module,exports){"use strict";var indexOf=String.prototype.indexOf;module.exports=function(searchString){return indexOf.call(this,searchString,arguments[1])>-1}},{}],21:[function(require,module,exports){"use strict";var d=require("d"),create=Object.create,defineProperties=Object.defineProperties,generateName,Symbol;generateName=function(){var created=create(null);return function(desc){var postfix=0;while(created[desc+(postfix||"")])++postfix;desc+=postfix||"";created[desc]=true;return"@@"+desc}}();module.exports=Symbol=function(description){var symbol;if(this instanceof Symbol){throw new TypeError("TypeError: Symbol is not a constructor")}symbol=create(Symbol.prototype);description=description===undefined?"":String(description);return defineProperties(symbol,{__description__:d("",description),__name__:d("",generateName(description))})};Object.defineProperties(Symbol,{create:d("",Symbol("create")),hasInstance:d("",Symbol("hasInstance")),isConcatSpreadable:d("",Symbol("isConcatSpreadable")),isRegExp:d("",Symbol("isRegExp")),iterator:d("",Symbol("iterator")),toPrimitive:d("",Symbol("toPrimitive")),toStringTag:d("",Symbol("toStringTag")),unscopables:d("",Symbol("unscopables"))});defineProperties(Symbol.prototype,{properToString:d(function(){return"Symbol ("+this.__description__+")"}),toString:d("",function(){return this.__name__})});Object.defineProperty(Symbol.prototype,Symbol.toPrimitive,d("",function(hint){throw new TypeError("Conversion of symbol objects is not allowed")}));Object.defineProperty(Symbol.prototype,Symbol.toStringTag,d("c","Symbol"))},{d:7}]},{},[1]);
dapp/src/shared/components/app/header.js
airalab/DAO-IPCI
import React from 'react' import { Link } from 'react-router' import { translate } from 'react-i18next' import _ from 'lodash' import Add from '../../containers/add' const Header = function Header(props) { return ( <div> <nav className="navbar navbar-default navbar-fixed-top"> <div className="container"> <div className="navbar-header"> <Link className="navbar-brand navbar-link" to="/"> <img src="assets/img/ipci-logo.svg" className="inline-mid" alt="" /> <span className="inline-mid"><strong>DAO</strong> IPCI</span> </Link> <button className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navcol-1"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar" /> <span className="icon-bar" /> <span className="icon-bar" /> </button> </div> <div className="collapse navbar-collapse" id="navcol-1"> <p className="navbar-text">Program:</p> <ul className="nav navbar-nav"> <li className="dropdown"> <a className="dropdown-toggle" data-toggle="dropdown" aria-expanded="false" href=""> <strong>IPCI</strong><span className="caret" /> </a> <ul className="dropdown-menu" role="menu"> {props.programms.map((item, index) => <li key={index} className={(item.address === props.dao_address) ? 'disabled' : ''} role="presentation"> <a href="" onClick={(e) => { e.preventDefault(); props.setDaoAddress(item.address); }}>{item.name}</a> </li> )} <li role="separator" className="divider"> <span style={{ display: 'none' }} /> </li> <li role="presentation"> <a href="" data-toggle="modal" data-target="#about"> <strong>Add new program</strong> <i className="fa fa-magic inline-mid m-l-10" /> </a> </li> </ul> </li> </ul> <p className="text-uppercase navbar-text" id="navbar-program-text" /> <ul className="nav navbar-nav navbar-right"> <li className="dropdown"> <a className="dropdown-toggle" data-toggle="dropdown" aria-expanded="false" href=""> {_.upperFirst(props.language)} <span className="caret" /> </a> <ul className="dropdown-menu" role="menu"> <li className={(props.language === 'en') ? 'disabled' : ''} role="presentation"> <a href="" onClick={(e) => { e.preventDefault(); props.setLanguage('en'); }}>English</a> </li> <li className={(props.language === 'ru') ? 'disabled' : ''} role="presentation"> <a href="" onClick={(e) => { e.preventDefault(); props.setLanguage('ru'); }}>Русский</a> </li> </ul> </li> <li className="dropdown"> <a className="dropdown-toggle" data-toggle="dropdown" aria-expanded="false" href=""> {(props.role !== '') ? props.t(props.role) : props.t('user')} <span className="caret" /> </a> <ul className="dropdown-menu" role="menu"> <li className={(props.role === 'operator') ? 'disabled' : ''} role="presentation"><Link to="/operator">{props.t('operator')}</Link></li> <li className={(props.role === 'issuer') ? 'disabled' : ''} role="presentation"><Link to="/issuer">{props.t('issuer')}</Link></li> <li className={(props.role === 'auditor') ? 'disabled' : ''} role="presentation"><Link to="/auditor">{props.t('auditor')}</Link></li> <li className={(props.role === 'complier') ? 'disabled' : ''} role="presentation"><Link to="/complier">{props.t('complier')}</Link></li> <li className={(props.role === 'user') ? 'disabled' : ''} role="presentation"><Link to="/user">{props.t('user')}</Link></li> </ul> </li> <li role="presentation"><Link to="/txs">{props.t('txs')}</Link></li> <li className="dropdown"> <a className="dropdown-toggle" data-toggle="dropdown" aria-expanded="false" href=""> {props.t('IoT')} <span className="caret" /> </a> <ul className="dropdown-menu" role="menu"> <li role="presentation"><Link to="/iot/chile">{props.t('Chile case')}</Link></li> </ul> </li> </ul> </div> </div> </nav> <div id="about" className="modal fade"> <div className="modal-dialog"> <div className="modal-content"> <div id="modal-about"> <div className="modal-header"> <button className="close" data-dismiss="modal"><span aria-hidden="true">×</span></button> <h4 className="modal-title">You are watching program 'IPCI' </h4> </div> <div className="modal-body"> {props.dao_address && <div> <p><strong>Programs leger Ethereum smart contract address: </strong></p> <p>{props.dao_address}</p> <hr /> </div> } <p><strong>Add new program:</strong></p> <Add /> </div> </div> </div> </div> </div> </div> ) } export default translate()(Header)
ajax/libs/shariff/1.16.0/shariff.complete.js
jonobr1/cdnjs
/*! * shariff - v1.16.0 - 13.07.2015 * https://github.com/heiseonline/shariff * Copyright (c) 2015 Ines Pauer, Philipp Busse, Sebastian Hilbig, Erich Kramer, Deniz Sesli * Licensed under the MIT license */ (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ (function (global){ !function(e){function o(e){throw RangeError(T[e])}function n(e,o){for(var n=e.length,r=[];n--;)r[n]=o(e[n]);return r}function r(e,o){var r=e.split("@"),t="";r.length>1&&(t=r[0]+"@",e=r[1]),e=e.replace(S,".");var u=e.split("."),i=n(u,o).join(".");return t+i}function t(e){for(var o,n,r=[],t=0,u=e.length;u>t;)o=e.charCodeAt(t++),o>=55296&&56319>=o&&u>t?(n=e.charCodeAt(t++),56320==(64512&n)?r.push(((1023&o)<<10)+(1023&n)+65536):(r.push(o),t--)):r.push(o);return r}function u(e){return n(e,function(e){var o="";return e>65535&&(e-=65536,o+=P(e>>>10&1023|55296),e=56320|1023&e),o+=P(e)}).join("")}function i(e){return 10>e-48?e-22:26>e-65?e-65:26>e-97?e-97:b}function f(e,o){return e+22+75*(26>e)-((0!=o)<<5)}function c(e,o,n){var r=0;for(e=n?M(e/j):e>>1,e+=M(e/o);e>L*C>>1;r+=b)e=M(e/L);return M(r+(L+1)*e/(e+m))}function l(e){var n,r,t,f,l,s,d,a,p,h,v=[],g=e.length,w=0,m=I,j=A;for(r=e.lastIndexOf(E),0>r&&(r=0),t=0;r>t;++t)e.charCodeAt(t)>=128&&o("not-basic"),v.push(e.charCodeAt(t));for(f=r>0?r+1:0;g>f;){for(l=w,s=1,d=b;f>=g&&o("invalid-input"),a=i(e.charCodeAt(f++)),(a>=b||a>M((x-w)/s))&&o("overflow"),w+=a*s,p=j>=d?y:d>=j+C?C:d-j,!(p>a);d+=b)h=b-p,s>M(x/h)&&o("overflow"),s*=h;n=v.length+1,j=c(w-l,n,0==l),M(w/n)>x-m&&o("overflow"),m+=M(w/n),w%=n,v.splice(w++,0,m)}return u(v)}function s(e){var n,r,u,i,l,s,d,a,p,h,v,g,w,m,j,F=[];for(e=t(e),g=e.length,n=I,r=0,l=A,s=0;g>s;++s)v=e[s],128>v&&F.push(P(v));for(u=i=F.length,i&&F.push(E);g>u;){for(d=x,s=0;g>s;++s)v=e[s],v>=n&&d>v&&(d=v);for(w=u+1,d-n>M((x-r)/w)&&o("overflow"),r+=(d-n)*w,n=d,s=0;g>s;++s)if(v=e[s],n>v&&++r>x&&o("overflow"),v==n){for(a=r,p=b;h=l>=p?y:p>=l+C?C:p-l,!(h>a);p+=b)j=a-h,m=b-h,F.push(P(f(h+j%m,0))),a=M(j/m);F.push(P(f(a,0))),l=c(r,w,u==i),r=0,++u}++r,++n}return F.join("")}function d(e){return r(e,function(e){return F.test(e)?l(e.slice(4).toLowerCase()):e})}function a(e){return r(e,function(e){return O.test(e)?"xn--"+s(e):e})}var p="object"==typeof exports&&exports&&!exports.nodeType&&exports,h="object"==typeof module&&module&&!module.nodeType&&module,v="object"==typeof global&&global;(v.global===v||v.window===v||v.self===v)&&(e=v);var g,w,x=2147483647,b=36,y=1,C=26,m=38,j=700,A=72,I=128,E="-",F=/^xn--/,O=/[^\x20-\x7E]/,S=/[\x2E\u3002\uFF0E\uFF61]/g,T={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},L=b-y,M=Math.floor,P=String.fromCharCode;if(g={version:"1.3.2",ucs2:{decode:t,encode:u},decode:l,encode:s,toASCII:a,toUnicode:d},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return g});else if(p&&h)if(module.exports==p)h.exports=g;else for(w in g)g.hasOwnProperty(w)&&(p[w]=g[w]);else e.punycode=g}(this); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],2:[function(require,module,exports){ "use strict";function hasOwnProperty(r,e){return Object.prototype.hasOwnProperty.call(r,e)}module.exports=function(r,e,t,n){e=e||"&",t=t||"=";var o={};if("string"!=typeof r||0===r.length)return o;var a=/\+/g;r=r.split(e);var s=1e3;n&&"number"==typeof n.maxKeys&&(s=n.maxKeys);var p=r.length;s>0&&p>s&&(p=s);for(var y=0;p>y;++y){var u,c,i,l,f=r[y].replace(a,"%20"),v=f.indexOf(t);v>=0?(u=f.substr(0,v),c=f.substr(v+1)):(u=f,c=""),i=decodeURIComponent(u),l=decodeURIComponent(c),hasOwnProperty(o,i)?isArray(o[i])?o[i].push(l):o[i]=[o[i],l]:o[i]=l}return o};var isArray=Array.isArray||function(r){return"[object Array]"===Object.prototype.toString.call(r)}; },{}],3:[function(require,module,exports){ "use strict";function map(r,e){if(r.map)return r.map(e);for(var t=[],n=0;n<r.length;n++)t.push(e(r[n],n));return t}var stringifyPrimitive=function(r){switch(typeof r){case"string":return r;case"boolean":return r?"true":"false";case"number":return isFinite(r)?r:"";default:return""}};module.exports=function(r,e,t,n){return e=e||"&",t=t||"=",null===r&&(r=void 0),"object"==typeof r?map(objectKeys(r),function(n){var i=encodeURIComponent(stringifyPrimitive(n))+t;return isArray(r[n])?map(r[n],function(r){return i+encodeURIComponent(stringifyPrimitive(r))}).join(e):i+encodeURIComponent(stringifyPrimitive(r[n]))}).join(e):n?encodeURIComponent(stringifyPrimitive(n))+t+encodeURIComponent(stringifyPrimitive(r)):""};var isArray=Array.isArray||function(r){return"[object Array]"===Object.prototype.toString.call(r)},objectKeys=Object.keys||function(r){var e=[];for(var t in r)Object.prototype.hasOwnProperty.call(r,t)&&e.push(t);return e}; },{}],4:[function(require,module,exports){ "use strict";exports.decode=exports.parse=require("./decode"),exports.encode=exports.stringify=require("./encode"); },{"./decode":2,"./encode":3}],5:[function(require,module,exports){ function Url(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function urlParse(t,s,e){if(t&&isObject(t)&&t instanceof Url)return t;var h=new Url;return h.parse(t,s,e),h}function urlFormat(t){return isString(t)&&(t=urlParse(t)),t instanceof Url?t.format():Url.prototype.format.call(t)}function urlResolve(t,s){return urlParse(t,!1,!0).resolve(s)}function urlResolveObject(t,s){return t?urlParse(t,!1,!0).resolveObject(s):s}function isString(t){return"string"==typeof t}function isObject(t){return"object"==typeof t&&null!==t}function isNull(t){return null===t}function isNullOrUndefined(t){return null==t}var punycode=require("punycode");exports.parse=urlParse,exports.resolve=urlResolve,exports.resolveObject=urlResolveObject,exports.format=urlFormat,exports.Url=Url;var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,delims=["<",">",'"',"`"," ","\r","\n"," "],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=require("querystring");Url.prototype.parse=function(t,s,e){if(!isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var h=t;h=h.trim();var r=protocolPattern.exec(h);if(r){r=r[0];var o=r.toLowerCase();this.protocol=o,h=h.substr(r.length)}if(e||r||h.match(/^\/\/[^@\/]+@[^@\/]+/)){var a="//"===h.substr(0,2);!a||r&&hostlessProtocol[r]||(h=h.substr(2),this.slashes=!0)}if(!hostlessProtocol[r]&&(a||r&&!slashedProtocol[r])){for(var n=-1,i=0;i<hostEndingChars.length;i++){var l=h.indexOf(hostEndingChars[i]);-1!==l&&(-1===n||n>l)&&(n=l)}var c,u;u=-1===n?h.lastIndexOf("@"):h.lastIndexOf("@",n),-1!==u&&(c=h.slice(0,u),h=h.slice(u+1),this.auth=decodeURIComponent(c)),n=-1;for(var i=0;i<nonHostChars.length;i++){var l=h.indexOf(nonHostChars[i]);-1!==l&&(-1===n||n>l)&&(n=l)}-1===n&&(n=h.length),this.host=h.slice(0,n),h=h.slice(n),this.parseHost(),this.hostname=this.hostname||"";var p="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!p)for(var f=this.hostname.split(/\./),i=0,m=f.length;m>i;i++){var v=f[i];if(v&&!v.match(hostnamePartPattern)){for(var g="",y=0,d=v.length;d>y;y++)g+=v.charCodeAt(y)>127?"x":v[y];if(!g.match(hostnamePartPattern)){var P=f.slice(0,i),b=f.slice(i+1),j=v.match(hostnamePartStart);j&&(P.push(j[1]),b.unshift(j[2])),b.length&&(h="/"+b.join(".")+h),this.hostname=P.join(".");break}}}if(this.hostname.length>hostnameMaxLen?this.hostname="":this.hostname=this.hostname.toLowerCase(),!p){for(var O=this.hostname.split("."),q=[],i=0;i<O.length;++i){var x=O[i];q.push(x.match(/[^A-Za-z0-9_-]/)?"xn--"+punycode.encode(x):x)}this.hostname=q.join(".")}var U=this.port?":"+this.port:"",C=this.hostname||"";this.host=C+U,this.href+=this.host,p&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==h[0]&&(h="/"+h))}if(!unsafeProtocol[o])for(var i=0,m=autoEscape.length;m>i;i++){var A=autoEscape[i],E=encodeURIComponent(A);E===A&&(E=escape(A)),h=h.split(A).join(E)}var w=h.indexOf("#");-1!==w&&(this.hash=h.substr(w),h=h.slice(0,w));var R=h.indexOf("?");if(-1!==R?(this.search=h.substr(R),this.query=h.substr(R+1),s&&(this.query=querystring.parse(this.query)),h=h.slice(0,R)):s&&(this.search="",this.query={}),h&&(this.pathname=h),slashedProtocol[o]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var U=this.pathname||"",x=this.search||"";this.path=U+x}return this.href=this.format(),this},Url.prototype.format=function(){var t=this.auth||"";t&&(t=encodeURIComponent(t),t=t.replace(/%3A/i,":"),t+="@");var s=this.protocol||"",e=this.pathname||"",h=this.hash||"",r=!1,o="";this.host?r=t+this.host:this.hostname&&(r=t+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(r+=":"+this.port)),this.query&&isObject(this.query)&&Object.keys(this.query).length&&(o=querystring.stringify(this.query));var a=this.search||o&&"?"+o||"";return s&&":"!==s.substr(-1)&&(s+=":"),this.slashes||(!s||slashedProtocol[s])&&r!==!1?(r="//"+(r||""),e&&"/"!==e.charAt(0)&&(e="/"+e)):r||(r=""),h&&"#"!==h.charAt(0)&&(h="#"+h),a&&"?"!==a.charAt(0)&&(a="?"+a),e=e.replace(/[?#]/g,function(t){return encodeURIComponent(t)}),a=a.replace("#","%23"),s+r+e+a+h},Url.prototype.resolve=function(t){return this.resolveObject(urlParse(t,!1,!0)).format()},Url.prototype.resolveObject=function(t){if(isString(t)){var s=new Url;s.parse(t,!1,!0),t=s}var e=new Url;if(Object.keys(this).forEach(function(t){e[t]=this[t]},this),e.hash=t.hash,""===t.href)return e.href=e.format(),e;if(t.slashes&&!t.protocol)return Object.keys(t).forEach(function(s){"protocol"!==s&&(e[s]=t[s])}),slashedProtocol[e.protocol]&&e.hostname&&!e.pathname&&(e.path=e.pathname="/"),e.href=e.format(),e;if(t.protocol&&t.protocol!==e.protocol){if(!slashedProtocol[t.protocol])return Object.keys(t).forEach(function(s){e[s]=t[s]}),e.href=e.format(),e;if(e.protocol=t.protocol,t.host||hostlessProtocol[t.protocol])e.pathname=t.pathname;else{for(var h=(t.pathname||"").split("/");h.length&&!(t.host=h.shift()););t.host||(t.host=""),t.hostname||(t.hostname=""),""!==h[0]&&h.unshift(""),h.length<2&&h.unshift(""),e.pathname=h.join("/")}if(e.search=t.search,e.query=t.query,e.host=t.host||"",e.auth=t.auth,e.hostname=t.hostname||t.host,e.port=t.port,e.pathname||e.search){var r=e.pathname||"",o=e.search||"";e.path=r+o}return e.slashes=e.slashes||t.slashes,e.href=e.format(),e}var a=e.pathname&&"/"===e.pathname.charAt(0),n=t.host||t.pathname&&"/"===t.pathname.charAt(0),i=n||a||e.host&&t.pathname,l=i,c=e.pathname&&e.pathname.split("/")||[],h=t.pathname&&t.pathname.split("/")||[],u=e.protocol&&!slashedProtocol[e.protocol];if(u&&(e.hostname="",e.port=null,e.host&&(""===c[0]?c[0]=e.host:c.unshift(e.host)),e.host="",t.protocol&&(t.hostname=null,t.port=null,t.host&&(""===h[0]?h[0]=t.host:h.unshift(t.host)),t.host=null),i=i&&(""===h[0]||""===c[0])),n)e.host=t.host||""===t.host?t.host:e.host,e.hostname=t.hostname||""===t.hostname?t.hostname:e.hostname,e.search=t.search,e.query=t.query,c=h;else if(h.length)c||(c=[]),c.pop(),c=c.concat(h),e.search=t.search,e.query=t.query;else if(!isNullOrUndefined(t.search)){if(u){e.hostname=e.host=c.shift();var p=e.host&&e.host.indexOf("@")>0?e.host.split("@"):!1;p&&(e.auth=p.shift(),e.host=e.hostname=p.shift())}return e.search=t.search,e.query=t.query,isNull(e.pathname)&&isNull(e.search)||(e.path=(e.pathname?e.pathname:"")+(e.search?e.search:"")),e.href=e.format(),e}if(!c.length)return e.pathname=null,e.search?e.path="/"+e.search:e.path=null,e.href=e.format(),e;for(var f=c.slice(-1)[0],m=(e.host||t.host)&&("."===f||".."===f)||""===f,v=0,g=c.length;g>=0;g--)f=c[g],"."==f?c.splice(g,1):".."===f?(c.splice(g,1),v++):v&&(c.splice(g,1),v--);if(!i&&!l)for(;v--;v)c.unshift("..");!i||""===c[0]||c[0]&&"/"===c[0].charAt(0)||c.unshift(""),m&&"/"!==c.join("/").substr(-1)&&c.push("");var y=""===c[0]||c[0]&&"/"===c[0].charAt(0);if(u){e.hostname=e.host=y?"":c.length?c.shift():"";var p=e.host&&e.host.indexOf("@")>0?e.host.split("@"):!1;p&&(e.auth=p.shift(),e.host=e.hostname=p.shift())}return i=i||e.host&&c.length,i&&!y&&c.unshift(""),c.length?e.pathname=c.join("/"):(e.pathname=null,e.path=null),isNull(e.pathname)&&isNull(e.search)||(e.path=(e.pathname?e.pathname:"")+(e.search?e.search:"")),e.auth=t.auth||e.auth,e.slashes=e.slashes||t.slashes,e.href=e.format(),e},Url.prototype.parseHost=function(){var t=this.host,s=portPattern.exec(t);s&&(s=s[0],":"!==s&&(this.port=s.substr(1)),t=t.substr(0,t.length-s.length)),t&&(this.hostname=t)}; },{"punycode":1,"querystring":4}],6:[function(require,module,exports){ !function(e,t){"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){function n(e){var t="length"in e&&e.length,n=ie.type(e);return"function"===n||ie.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e}function r(e,t,n){if(ie.isFunction(t))return ie.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return ie.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(fe.test(t))return ie.filter(t,e,n);t=ie.filter(t,e)}return ie.grep(e,function(e){return ie.inArray(e,t)>=0!==n})}function i(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function o(e){var t=xe[e]={};return ie.each(e.match(be)||[],function(e,n){t[n]=!0}),t}function a(){he.addEventListener?(he.removeEventListener("DOMContentLoaded",s,!1),e.removeEventListener("load",s,!1)):(he.detachEvent("onreadystatechange",s),e.detachEvent("onload",s))}function s(){(he.addEventListener||"load"===event.type||"complete"===he.readyState)&&(a(),ie.ready())}function u(e,t,n){if(void 0===n&&1===e.nodeType){var r="data-"+t.replace(Ee,"-$1").toLowerCase();if(n=e.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:Ne.test(n)?ie.parseJSON(n):n}catch(i){}ie.data(e,t,n)}else n=void 0}return n}function l(e){var t;for(t in e)if(("data"!==t||!ie.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function c(e,t,n,r){if(ie.acceptData(e)){var i,o,a=ie.expando,s=e.nodeType,u=s?ie.cache:e,l=s?e[a]:e[a]&&a;if(l&&u[l]&&(r||u[l].data)||void 0!==n||"string"!=typeof t)return l||(l=s?e[a]=J.pop()||ie.guid++:a),u[l]||(u[l]=s?{}:{toJSON:ie.noop}),("object"==typeof t||"function"==typeof t)&&(r?u[l]=ie.extend(u[l],t):u[l].data=ie.extend(u[l].data,t)),o=u[l],r||(o.data||(o.data={}),o=o.data),void 0!==n&&(o[ie.camelCase(t)]=n),"string"==typeof t?(i=o[t],null==i&&(i=o[ie.camelCase(t)])):i=o,i}}function d(e,t,n){if(ie.acceptData(e)){var r,i,o=e.nodeType,a=o?ie.cache:e,s=o?e[ie.expando]:ie.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){ie.isArray(t)?t=t.concat(ie.map(t,ie.camelCase)):t in r?t=[t]:(t=ie.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;for(;i--;)delete r[t[i]];if(n?!l(r):!ie.isEmptyObject(r))return}(n||(delete a[s].data,l(a[s])))&&(o?ie.cleanData([e],!0):ne.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}function f(){return!0}function p(){return!1}function h(){try{return he.activeElement}catch(e){}}function m(e){var t=Fe.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function g(e,t){var n,r,i=0,o=typeof e.getElementsByTagName!==Ce?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==Ce?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],n=e.childNodes||e;null!=(r=n[i]);i++)!t||ie.nodeName(r,t)?o.push(r):ie.merge(o,g(r,t));return void 0===t||t&&ie.nodeName(e,t)?ie.merge([e],o):o}function v(e){je.test(e.type)&&(e.defaultChecked=e.checked)}function y(e,t){return ie.nodeName(e,"table")&&ie.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function b(e){return e.type=(null!==ie.find.attr(e,"type"))+"/"+e.type,e}function x(e){var t=Ve.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function w(e,t){for(var n,r=0;null!=(n=e[r]);r++)ie._data(n,"globalEval",!t||ie._data(t[r],"globalEval"))}function T(e,t){if(1===t.nodeType&&ie.hasData(e)){var n,r,i,o=ie._data(e),a=ie._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)ie.event.add(t,n,s[n][r])}a.data&&(a.data=ie.extend({},a.data))}}function C(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!ne.noCloneEvent&&t[ie.expando]){i=ie._data(t);for(r in i.events)ie.removeEvent(t,r,i.handle);t.removeAttribute(ie.expando)}"script"===n&&t.text!==e.text?(b(t).text=e.text,x(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),ne.html5Clone&&e.innerHTML&&!ie.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&je.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}function N(t,n){var r,i=ie(n.createElement(t)).appendTo(n.body),o=e.getDefaultComputedStyle&&(r=e.getDefaultComputedStyle(i[0]))?r.display:ie.css(i[0],"display");return i.detach(),o}function E(e){var t=he,n=Ze[e];return n||(n=N(e,t),"none"!==n&&n||(Ke=(Ke||ie("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=(Ke[0].contentWindow||Ke[0].contentDocument).document,t.write(),t.close(),n=N(e,t),Ke.detach()),Ze[e]=n),n}function k(e,t){return{get:function(){var n=e();if(null!=n)return n?void delete this.get:(this.get=t).apply(this,arguments)}}}function S(e,t){if(t in e)return t;for(var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=ft.length;i--;)if(t=ft[i]+n,t in e)return t;return r}function A(e,t){for(var n,r,i,o=[],a=0,s=e.length;s>a;a++)r=e[a],r.style&&(o[a]=ie._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&Ae(r)&&(o[a]=ie._data(r,"olddisplay",E(r.nodeName)))):(i=Ae(r),(n&&"none"!==n||!i)&&ie._data(r,"olddisplay",i?n:ie.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}function D(e,t,n){var r=ut.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function j(e,t,n,r,i){for(var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;4>o;o+=2)"margin"===n&&(a+=ie.css(e,n+Se[o],!0,i)),r?("content"===n&&(a-=ie.css(e,"padding"+Se[o],!0,i)),"margin"!==n&&(a-=ie.css(e,"border"+Se[o]+"Width",!0,i))):(a+=ie.css(e,"padding"+Se[o],!0,i),"padding"!==n&&(a+=ie.css(e,"border"+Se[o]+"Width",!0,i)));return a}function L(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=et(e),a=ne.boxSizing&&"border-box"===ie.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=tt(e,t,o),(0>i||null==i)&&(i=e.style[t]),rt.test(i))return i;r=a&&(ne.boxSizingReliable()||i===e.style[t]),i=parseFloat(i)||0}return i+j(e,t,n||(a?"border":"content"),r,o)+"px"}function H(e,t,n,r,i){return new H.prototype.init(e,t,n,r,i)}function q(){return setTimeout(function(){pt=void 0}),pt=ie.now()}function _(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Se[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function M(e,t,n){for(var r,i=(bt[t]||[]).concat(bt["*"]),o=0,a=i.length;a>o;o++)if(r=i[o].call(n,t,e))return r}function F(e,t,n){var r,i,o,a,s,u,l,c,d=this,f={},p=e.style,h=e.nodeType&&Ae(e),m=ie._data(e,"fxshow");n.queue||(s=ie._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,u=s.empty.fire,s.empty.fire=function(){s.unqueued||u()}),s.unqueued++,d.always(function(){d.always(function(){s.unqueued--,ie.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],l=ie.css(e,"display"),c="none"===l?ie._data(e,"olddisplay")||E(e.nodeName):l,"inline"===c&&"none"===ie.css(e,"float")&&(ne.inlineBlockNeedsLayout&&"inline"!==E(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",ne.shrinkWrapBlocks()||d.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],mt.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(h?"hide":"show")){if("show"!==i||!m||void 0===m[r])continue;h=!0}f[r]=m&&m[r]||ie.style(e,r)}else l=void 0;if(ie.isEmptyObject(f))"inline"===("none"===l?E(e.nodeName):l)&&(p.display=l);else{m?"hidden"in m&&(h=m.hidden):m=ie._data(e,"fxshow",{}),o&&(m.hidden=!h),h?ie(e).show():d.done(function(){ie(e).hide()}),d.done(function(){var t;ie._removeData(e,"fxshow");for(t in f)ie.style(e,t,f[t])});for(r in f)a=M(h?m[r]:0,r,d),r in m||(m[r]=a.start,h&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function O(e,t){var n,r,i,o,a;for(n in e)if(r=ie.camelCase(n),i=t[r],o=e[n],ie.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=ie.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}function B(e,t,n){var r,i,o=0,a=yt.length,s=ie.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;for(var t=pt||q(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:ie.extend({},t),opts:ie.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:pt||q(),duration:n.duration,tweens:[],createTween:function(t,n){var r=ie.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(O(c,l.opts.specialEasing);a>o;o++)if(r=yt[o].call(l,e,c,l.opts))return r;return ie.map(c,M,l),ie.isFunction(l.opts.start)&&l.opts.start.call(e,l),ie.fx.timer(ie.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function P(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(be)||[];if(ie.isFunction(n))for(;r=o[i++];)"+"===r.charAt(0)?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function R(e,t,n,r){function i(s){var u;return o[s]=!0,ie.each(e[s]||[],function(e,s){var l=s(t,n,r);return"string"!=typeof l||a||o[l]?a?!(u=l):void 0:(t.dataTypes.unshift(l),i(l),!1)}),u}var o={},a=e===zt;return i(t.dataTypes[0])||!o["*"]&&i("*")}function W(e,t){var n,r,i=ie.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((i[r]?e:n||(n={}))[r]=t[r]);return n&&ie.extend(!0,e,n),e}function $(e,t,n){for(var r,i,o,a,s=e.contents,u=e.dataTypes;"*"===u[0];)u.shift(),void 0===i&&(i=e.mimeType||t.getResponseHeader("Content-Type"));if(i)for(a in s)if(s[a]&&s[a].test(i)){u.unshift(a);break}if(u[0]in n)o=u[0];else{for(a in n){if(!u[0]||e.converters[a+" "+u[0]]){o=a;break}r||(r=a)}o=o||r}return o?(o!==u[0]&&u.unshift(o),n[o]):void 0}function z(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];for(o=c.shift();o;)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(a=l[u+" "+o]||l["* "+o],!a)for(i in l)if(s=i.split(" "),s[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){a===!0?a=l[i]:l[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(d){return{state:"parsererror",error:a?d:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}function I(e,t,n,r){var i;if(ie.isArray(t))ie.each(t,function(t,i){n||Vt.test(e)?r(e,i):I(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==ie.type(t))r(e,t);else for(i in t)I(e+"["+i+"]",t[i],n,r)}function X(){try{return new e.XMLHttpRequest}catch(t){}}function U(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function V(e){return ie.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var J=[],Y=J.slice,G=J.concat,Q=J.push,K=J.indexOf,Z={},ee=Z.toString,te=Z.hasOwnProperty,ne={},re="1.11.3",ie=function(e,t){return new ie.fn.init(e,t)},oe=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,ae=/^-ms-/,se=/-([\da-z])/gi,ue=function(e,t){return t.toUpperCase()};ie.fn=ie.prototype={jquery:re,constructor:ie,selector:"",length:0,toArray:function(){return Y.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:Y.call(this)},pushStack:function(e){var t=ie.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return ie.each(this,e,t)},map:function(e){return this.pushStack(ie.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(Y.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Q,sort:J.sort,splice:J.splice},ie.extend=ie.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||ie.isFunction(a)||(a={}),s===u&&(a=this,s--);u>s;s++)if(null!=(i=arguments[s]))for(r in i)e=a[r],n=i[r],a!==n&&(l&&n&&(ie.isPlainObject(n)||(t=ie.isArray(n)))?(t?(t=!1,o=e&&ie.isArray(e)?e:[]):o=e&&ie.isPlainObject(e)?e:{},a[r]=ie.extend(l,o,n)):void 0!==n&&(a[r]=n));return a},ie.extend({expando:"jQuery"+(re+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===ie.type(e)},isArray:Array.isArray||function(e){return"array"===ie.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!ie.isArray(e)&&e-parseFloat(e)+1>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==ie.type(e)||e.nodeType||ie.isWindow(e))return!1;try{if(e.constructor&&!te.call(e,"constructor")&&!te.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}if(ne.ownLast)for(t in e)return te.call(e,t);for(t in e);return void 0===t||te.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?Z[ee.call(e)]||"object":typeof e},globalEval:function(t){t&&ie.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(ae,"ms-").replace(se,ue)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,r){var i,o=0,a=e.length,s=n(e);if(r){if(s)for(;a>o&&(i=t.apply(e[o],r),i!==!1);o++);else for(o in e)if(i=t.apply(e[o],r),i===!1)break}else if(s)for(;a>o&&(i=t.call(e[o],o,e[o]),i!==!1);o++);else for(o in e)if(i=t.call(e[o],o,e[o]),i===!1)break;return e},trim:function(e){return null==e?"":(e+"").replace(oe,"")},makeArray:function(e,t){var r=t||[];return null!=e&&(n(Object(e))?ie.merge(r,"string"==typeof e?[e]:e):Q.call(r,e)),r},inArray:function(e,t,n){var r;if(t){if(K)return K.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;n>r;)e[i++]=t[r++];if(n!==n)for(;void 0!==t[r];)e[i++]=t[r++];return e.length=i,e},grep:function(e,t,n){for(var r,i=[],o=0,a=e.length,s=!n;a>o;o++)r=!t(e[o],o),r!==s&&i.push(e[o]);return i},map:function(e,t,r){var i,o=0,a=e.length,s=n(e),u=[];if(s)for(;a>o;o++)i=t(e[o],o,r),null!=i&&u.push(i);else for(o in e)i=t(e[o],o,r),null!=i&&u.push(i);return G.apply([],u)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(i=e[t],t=e,e=i),ie.isFunction(e)?(n=Y.call(arguments,2),r=function(){return e.apply(t||this,n.concat(Y.call(arguments)))},r.guid=e.guid=e.guid||ie.guid++,r):void 0},now:function(){return+new Date},support:ne}),ie.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){Z["[object "+t+"]"]=t.toLowerCase()});var le=function(e){function t(e,t,n,r){var i,o,a,s,u,l,d,p,h,m;if((t?t.ownerDocument||t:R)!==H&&L(t),t=t||H,n=n||[],s=t.nodeType,"string"!=typeof e||!e||1!==s&&9!==s&&11!==s)return n;if(!r&&_){if(11!==s&&(i=ye.exec(e)))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&B(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return K.apply(n,t.getElementsByTagName(e)),n;if((a=i[3])&&w.getElementsByClassName)return K.apply(n,t.getElementsByClassName(a)),n}if(w.qsa&&(!M||!M.test(e))){if(p=d=P,h=t,m=1!==s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){for(l=E(e),(d=t.getAttribute("id"))?p=d.replace(xe,"\\$&"):t.setAttribute("id",p),p="[id='"+p+"'] ",u=l.length;u--;)l[u]=p+f(l[u]);h=be.test(e)&&c(t.parentNode)||t,m=l.join(",")}if(m)try{return K.apply(n,h.querySelectorAll(m)),n}catch(g){}finally{d||t.removeAttribute("id")}}}return S(e.replace(ue,"$1"),t,n,r)}function n(){function e(n,r){return t.push(n+" ")>T.cacheLength&&delete e[t.shift()],e[n+" "]=r}var t=[];return e}function r(e){return e[P]=!0,e}function i(e){var t=H.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function o(e,t){for(var n=e.split("|"),r=e.length;r--;)T.attrHandle[n[r]]=t}function a(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||V)-(~e.sourceIndex||V);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function s(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function u(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function l(e){return r(function(t){return t=+t,r(function(n,r){for(var i,o=e([],n.length,t),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function c(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function d(){}function f(e){for(var t=0,n=e.length,r="";n>t;t++)r+=e[t].value;return r}function p(e,t,n){var r=t.dir,i=n&&"parentNode"===r,o=$++;return t.first?function(t,n,o){for(;t=t[r];)if(1===t.nodeType||i)return e(t,n,o)}:function(t,n,a){var s,u,l=[W,o];if(a){for(;t=t[r];)if((1===t.nodeType||i)&&e(t,n,a))return!0}else for(;t=t[r];)if(1===t.nodeType||i){if(u=t[P]||(t[P]={}),(s=u[r])&&s[0]===W&&s[1]===o)return l[2]=s[2];if(u[r]=l,l[2]=e(t,n,a))return!0}}}function h(e){return e.length>1?function(t,n,r){for(var i=e.length;i--;)if(!e[i](t,n,r))return!1;return!0}:e[0]}function m(e,n,r){for(var i=0,o=n.length;o>i;i++)t(e,n[i],r);return r}function g(e,t,n,r,i){for(var o,a=[],s=0,u=e.length,l=null!=t;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function v(e,t,n,i,o,a){return i&&!i[P]&&(i=v(i)),o&&!o[P]&&(o=v(o,a)),r(function(r,a,s,u){var l,c,d,f=[],p=[],h=a.length,v=r||m(t||"*",s.nodeType?[s]:s,[]),y=!e||!r&&t?v:g(v,f,e,s,u),b=n?o||(r?e:h||i)?[]:a:y;if(n&&n(y,b,s,u),i)for(l=g(b,p),i(l,[],s,u),c=l.length;c--;)(d=l[c])&&(b[p[c]]=!(y[p[c]]=d));if(r){if(o||e){if(o){for(l=[],c=b.length;c--;)(d=b[c])&&l.push(y[c]=d);o(null,b=[],l,u)}for(c=b.length;c--;)(d=b[c])&&(l=o?ee(r,d):f[c])>-1&&(r[l]=!(a[l]=d))}}else b=g(b===a?b.splice(h,b.length):b),o?o(null,a,b,u):K.apply(a,b)})}function y(e){for(var t,n,r,i=e.length,o=T.relative[e[0].type],a=o||T.relative[" "],s=o?1:0,u=p(function(e){return e===t},a,!0),l=p(function(e){return ee(t,e)>-1},a,!0),c=[function(e,n,r){var i=!o&&(r||n!==A)||((t=n).nodeType?u(e,n,r):l(e,n,r));return t=null,i}];i>s;s++)if(n=T.relative[e[s].type])c=[p(h(c),n)];else{if(n=T.filter[e[s].type].apply(null,e[s].matches),n[P]){for(r=++s;i>r&&!T.relative[e[r].type];r++);return v(s>1&&h(c),s>1&&f(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace(ue,"$1"),n,r>s&&y(e.slice(s,r)),i>r&&y(e=e.slice(r)),i>r&&f(e))}c.push(n)}return h(c)}function b(e,n){var i=n.length>0,o=e.length>0,a=function(r,a,s,u,l){var c,d,f,p=0,h="0",m=r&&[],v=[],y=A,b=r||o&&T.find.TAG("*",l),x=W+=null==y?1:Math.random()||.1,w=b.length;for(l&&(A=a!==H&&a);h!==w&&null!=(c=b[h]);h++){if(o&&c){for(d=0;f=e[d++];)if(f(c,a,s)){u.push(c);break}l&&(W=x)}i&&((c=!f&&c)&&p--,r&&m.push(c))}if(p+=h,i&&h!==p){for(d=0;f=n[d++];)f(m,v,a,s);if(r){if(p>0)for(;h--;)m[h]||v[h]||(v[h]=G.call(u));v=g(v)}K.apply(u,v),l&&!r&&v.length>0&&p+n.length>1&&t.uniqueSort(u)}return l&&(W=x,A=y),m};return i?r(a):a}var x,w,T,C,N,E,k,S,A,D,j,L,H,q,_,M,F,O,B,P="sizzle"+1*new Date,R=e.document,W=0,$=0,z=n(),I=n(),X=n(),U=function(e,t){return e===t&&(j=!0),0},V=1<<31,J={}.hasOwnProperty,Y=[],G=Y.pop,Q=Y.push,K=Y.push,Z=Y.slice,ee=function(e,t){for(var n=0,r=e.length;r>n;n++)if(e[n]===t)return n;return-1},te="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",ne="[\\x20\\t\\r\\n\\f]",re="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ie=re.replace("w","w#"),oe="\\["+ne+"*("+re+")(?:"+ne+"*([*^$|!~]?=)"+ne+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+ie+"))|)"+ne+"*\\]",ae=":("+re+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+oe+")*)|.*)\\)|)",se=new RegExp(ne+"+","g"),ue=new RegExp("^"+ne+"+|((?:^|[^\\\\])(?:\\\\.)*)"+ne+"+$","g"),le=new RegExp("^"+ne+"*,"+ne+"*"),ce=new RegExp("^"+ne+"*([>+~]|"+ne+")"+ne+"*"),de=new RegExp("="+ne+"*([^\\]'\"]*?)"+ne+"*\\]","g"),fe=new RegExp(ae),pe=new RegExp("^"+ie+"$"),he={ID:new RegExp("^#("+re+")"),CLASS:new RegExp("^\\.("+re+")"),TAG:new RegExp("^("+re.replace("w","w*")+")"),ATTR:new RegExp("^"+oe),PSEUDO:new RegExp("^"+ae),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ne+"*(even|odd|(([+-]|)(\\d*)n|)"+ne+"*(?:([+-]|)"+ne+"*(\\d+)|))"+ne+"*\\)|)","i"),bool:new RegExp("^(?:"+te+")$","i"),needsContext:new RegExp("^"+ne+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ne+"*((?:-\\d)?\\d*)"+ne+"*\\)|)(?=[^-]|$)","i")},me=/^(?:input|select|textarea|button)$/i,ge=/^h\d$/i,ve=/^[^{]+\{\s*\[native \w/,ye=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,be=/[+~]/,xe=/'|\\/g,we=new RegExp("\\\\([\\da-f]{1,6}"+ne+"?|("+ne+")|.)","ig"),Te=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},Ce=function(){L()};try{K.apply(Y=Z.call(R.childNodes),R.childNodes),Y[R.childNodes.length].nodeType}catch(Ne){K={apply:Y.length?function(e,t){Q.apply(e,Z.call(t))}:function(e,t){for(var n=e.length,r=0;e[n++]=t[r++];);e.length=n-1}}}w=t.support={},N=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},L=t.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:R;return r!==H&&9===r.nodeType&&r.documentElement?(H=r,q=r.documentElement,n=r.defaultView,n&&n!==n.top&&(n.addEventListener?n.addEventListener("unload",Ce,!1):n.attachEvent&&n.attachEvent("onunload",Ce)),_=!N(r),w.attributes=i(function(e){return e.className="i",!e.getAttribute("className")}),w.getElementsByTagName=i(function(e){return e.appendChild(r.createComment("")),!e.getElementsByTagName("*").length}),w.getElementsByClassName=ve.test(r.getElementsByClassName),w.getById=i(function(e){return q.appendChild(e).id=P,!r.getElementsByName||!r.getElementsByName(P).length}),w.getById?(T.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&_){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},T.filter.ID=function(e){var t=e.replace(we,Te);return function(e){return e.getAttribute("id")===t}}):(delete T.find.ID,T.filter.ID=function(e){var t=e.replace(we,Te);return function(e){var n="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}}),T.find.TAG=w.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):w.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){for(;n=o[i++];)1===n.nodeType&&r.push(n);return r}return o},T.find.CLASS=w.getElementsByClassName&&function(e,t){return _?t.getElementsByClassName(e):void 0},F=[],M=[],(w.qsa=ve.test(r.querySelectorAll))&&(i(function(e){q.appendChild(e).innerHTML="<a id='"+P+"'></a><select id='"+P+"-\f]' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&M.push("[*^$]="+ne+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||M.push("\\["+ne+"*(?:value|"+te+")"),e.querySelectorAll("[id~="+P+"-]").length||M.push("~="),e.querySelectorAll(":checked").length||M.push(":checked"),e.querySelectorAll("a#"+P+"+*").length||M.push(".#.+[+~]")}),i(function(e){var t=r.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&M.push("name"+ne+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||M.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),M.push(",.*:")})),(w.matchesSelector=ve.test(O=q.matches||q.webkitMatchesSelector||q.mozMatchesSelector||q.oMatchesSelector||q.msMatchesSelector))&&i(function(e){w.disconnectedMatch=O.call(e,"div"),O.call(e,"[s!='']:x"),F.push("!=",ae)}),M=M.length&&new RegExp(M.join("|")),F=F.length&&new RegExp(F.join("|")),t=ve.test(q.compareDocumentPosition),B=t||ve.test(q.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},U=t?function(e,t){if(e===t)return j=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n?n:(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&n||!w.sortDetached&&t.compareDocumentPosition(e)===n?e===r||e.ownerDocument===R&&B(R,e)?-1:t===r||t.ownerDocument===R&&B(R,t)?1:D?ee(D,e)-ee(D,t):0:4&n?-1:1)}:function(e,t){if(e===t)return j=!0,0;var n,i=0,o=e.parentNode,s=t.parentNode,u=[e],l=[t];if(!o||!s)return e===r?-1:t===r?1:o?-1:s?1:D?ee(D,e)-ee(D,t):0;if(o===s)return a(e,t);for(n=e;n=n.parentNode;)u.unshift(n);for(n=t;n=n.parentNode;)l.unshift(n);for(;u[i]===l[i];)i++;return i?a(u[i],l[i]):u[i]===R?-1:l[i]===R?1:0},r):H},t.matches=function(e,n){return t(e,null,null,n)},t.matchesSelector=function(e,n){if((e.ownerDocument||e)!==H&&L(e),n=n.replace(de,"='$1']"),!(!w.matchesSelector||!_||F&&F.test(n)||M&&M.test(n)))try{var r=O.call(e,n);if(r||w.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(i){}return t(n,H,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==H&&L(e),B(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==H&&L(e);var n=T.attrHandle[t.toLowerCase()],r=n&&J.call(T.attrHandle,t.toLowerCase())?n(e,t,!_):void 0;return void 0!==r?r:w.attributes||!_?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,n=[],r=0,i=0;if(j=!w.detectDuplicates,D=!w.sortStable&&e.slice(0),e.sort(U),j){for(;t=e[i++];)t===e[i]&&(r=n.push(i));for(;r--;)e.splice(n[r],1)}return D=null,e},C=t.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=C(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r++];)n+=C(t);return n},T=t.selectors={cacheLength:50,createPseudo:r,match:he,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(we,Te),e[3]=(e[3]||e[4]||e[5]||"").replace(we,Te),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||t.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&t.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return he.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&fe.test(n)&&(t=E(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(we,Te).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=z[e+" "];return t||(t=new RegExp("(^|"+ne+")"+e+"("+ne+"|$)"))&&z(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,n,r){return function(i){var o=t.attr(i,e);return null==o?"!="===n:n?(o+="","="===n?o===r:"!="===n?o!==r:"^="===n?r&&0===o.indexOf(r):"*="===n?r&&o.indexOf(r)>-1:"$="===n?r&&o.slice(-r.length)===r:"~="===n?(" "+o.replace(se," ")+" ").indexOf(r)>-1:"|="===n?o===r||o.slice(0,r.length+1)===r+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,d,f,p,h,m=o!==a?"nextSibling":"previousSibling",g=t.parentNode,v=s&&t.nodeName.toLowerCase(),y=!u&&!s;if(g){if(o){for(;m;){for(d=t;d=d[m];)if(s?d.nodeName.toLowerCase()===v:1===d.nodeType)return!1;h=m="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?g.firstChild:g.lastChild],a&&y){for(c=g[P]||(g[P]={}),l=c[e]||[],p=l[0]===W&&l[1],f=l[0]===W&&l[2],d=p&&g.childNodes[p];d=++p&&d&&d[m]||(f=p=0)||h.pop();)if(1===d.nodeType&&++f&&d===t){c[e]=[W,p,f];break}}else if(y&&(l=(t[P]||(t[P]={}))[e])&&l[0]===W)f=l[1];else for(;(d=++p&&d&&d[m]||(f=p=0)||h.pop())&&((s?d.nodeName.toLowerCase()!==v:1!==d.nodeType)||!++f||(y&&((d[P]||(d[P]={}))[e]=[W,f]),d!==t)););return f-=i,f===r||f%r===0&&f/r>=0}}},PSEUDO:function(e,n){var i,o=T.pseudos[e]||T.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return o[P]?o(n):o.length>1?(i=[e,e,"",n],T.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,i=o(e,n),a=i.length;a--;)r=ee(e,i[a]),e[r]=!(t[r]=i[a])}):function(e){return o(e,0,i)}):o}},pseudos:{not:r(function(e){var t=[],n=[],i=k(e.replace(ue,"$1"));return i[P]?r(function(e,t,n,r){for(var o,a=i(e,null,r,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,r,o){return t[0]=e,i(t,null,o,n),t[0]=null,!n.pop()}}),has:r(function(e){return function(n){return t(e,n).length>0}}),contains:r(function(e){return e=e.replace(we,Te),function(t){return(t.textContent||t.innerText||C(t)).indexOf(e)>-1}}),lang:r(function(e){return pe.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(we,Te).toLowerCase(),function(t){var n;do if(n=_?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===q},focus:function(e){return e===H.activeElement&&(!H.hasFocus||H.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!T.pseudos.empty(e)},header:function(e){return ge.test(e.nodeName)},input:function(e){return me.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:l(function(){return[0]}),last:l(function(e,t){return[t-1]}),eq:l(function(e,t,n){return[0>n?n+t:n]}),even:l(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:l(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:l(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:l(function(e,t,n){for(var r=0>n?n+t:n;++r<t;)e.push(r);return e})}},T.pseudos.nth=T.pseudos.eq;for(x in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})T.pseudos[x]=s(x);for(x in{submit:!0,reset:!0})T.pseudos[x]=u(x);return d.prototype=T.filters=T.pseudos,T.setFilters=new d,E=t.tokenize=function(e,n){var r,i,o,a,s,u,l,c=I[e+" "];if(c)return n?0:c.slice(0);for(s=e,u=[],l=T.preFilter;s;){(!r||(i=le.exec(s)))&&(i&&(s=s.slice(i[0].length)||s),u.push(o=[])),r=!1,(i=ce.exec(s))&&(r=i.shift(),o.push({value:r,type:i[0].replace(ue," ")}),s=s.slice(r.length));for(a in T.filter)!(i=he[a].exec(s))||l[a]&&!(i=l[a](i))||(r=i.shift(), o.push({value:r,type:a,matches:i}),s=s.slice(r.length));if(!r)break}return n?s.length:s?t.error(e):I(e,u).slice(0)},k=t.compile=function(e,t){var n,r=[],i=[],o=X[e+" "];if(!o){for(t||(t=E(e)),n=t.length;n--;)o=y(t[n]),o[P]?r.push(o):i.push(o);o=X(e,b(i,r)),o.selector=e}return o},S=t.select=function(e,t,n,r){var i,o,a,s,u,l="function"==typeof e&&e,d=!r&&E(e=l.selector||e);if(n=n||[],1===d.length){if(o=d[0]=d[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&w.getById&&9===t.nodeType&&_&&T.relative[o[1].type]){if(t=(T.find.ID(a.matches[0].replace(we,Te),t)||[])[0],!t)return n;l&&(t=t.parentNode),e=e.slice(o.shift().value.length)}for(i=he.needsContext.test(e)?0:o.length;i--&&(a=o[i],!T.relative[s=a.type]);)if((u=T.find[s])&&(r=u(a.matches[0].replace(we,Te),be.test(o[0].type)&&c(t.parentNode)||t))){if(o.splice(i,1),e=r.length&&f(o),!e)return K.apply(n,r),n;break}}return(l||k(e,d))(r,t,!_,n,be.test(e)&&c(t.parentNode)||t),n},w.sortStable=P.split("").sort(U).join("")===P,w.detectDuplicates=!!j,L(),w.sortDetached=i(function(e){return 1&e.compareDocumentPosition(H.createElement("div"))}),i(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,n){return n?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),w.attributes&&i(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||o("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),i(function(e){return null==e.getAttribute("disabled")})||o(te,function(e,t,n){var r;return n?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),t}(e);ie.find=le,ie.expr=le.selectors,ie.expr[":"]=ie.expr.pseudos,ie.unique=le.uniqueSort,ie.text=le.getText,ie.isXMLDoc=le.isXML,ie.contains=le.contains;var ce=ie.expr.match.needsContext,de=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,fe=/^.[^:#\[\.,]*$/;ie.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?ie.find.matchesSelector(r,e)?[r]:[]:ie.find.matches(e,ie.grep(t,function(e){return 1===e.nodeType}))},ie.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(ie(e).filter(function(){for(t=0;i>t;t++)if(ie.contains(r[t],this))return!0}));for(t=0;i>t;t++)ie.find(e,r[t],n);return n=this.pushStack(i>1?ie.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},filter:function(e){return this.pushStack(r(this,e||[],!1))},not:function(e){return this.pushStack(r(this,e||[],!0))},is:function(e){return!!r(this,"string"==typeof e&&ce.test(e)?ie(e):e||[],!1).length}});var pe,he=e.document,me=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,ge=ie.fn.init=function(e,t){var n,r;if(!e)return this;if("string"==typeof e){if(n="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:me.exec(e),!n||!n[1]&&t)return!t||t.jquery?(t||pe).find(e):this.constructor(t).find(e);if(n[1]){if(t=t instanceof ie?t[0]:t,ie.merge(this,ie.parseHTML(n[1],t&&t.nodeType?t.ownerDocument||t:he,!0)),de.test(n[1])&&ie.isPlainObject(t))for(n in t)ie.isFunction(this[n])?this[n](t[n]):this.attr(n,t[n]);return this}if(r=he.getElementById(n[2]),r&&r.parentNode){if(r.id!==n[2])return pe.find(e);this.length=1,this[0]=r}return this.context=he,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):ie.isFunction(e)?"undefined"!=typeof pe.ready?pe.ready(e):e(ie):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),ie.makeArray(e,this))};ge.prototype=ie.fn,pe=ie(he);var ve=/^(?:parents|prev(?:Until|All))/,ye={children:!0,contents:!0,next:!0,prev:!0};ie.extend({dir:function(e,t,n){for(var r=[],i=e[t];i&&9!==i.nodeType&&(void 0===n||1!==i.nodeType||!ie(i).is(n));)1===i.nodeType&&r.push(i),i=i[t];return r},sibling:function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}}),ie.fn.extend({has:function(e){var t,n=ie(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(ie.contains(this,n[t]))return!0})},closest:function(e,t){for(var n,r=0,i=this.length,o=[],a=ce.test(e)||"string"!=typeof e?ie(e,t||this.context):0;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&ie.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?ie.unique(o):o)},index:function(e){return e?"string"==typeof e?ie.inArray(this[0],ie(e)):ie.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(ie.unique(ie.merge(this.get(),ie(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),ie.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return ie.dir(e,"parentNode")},parentsUntil:function(e,t,n){return ie.dir(e,"parentNode",n)},next:function(e){return i(e,"nextSibling")},prev:function(e){return i(e,"previousSibling")},nextAll:function(e){return ie.dir(e,"nextSibling")},prevAll:function(e){return ie.dir(e,"previousSibling")},nextUntil:function(e,t,n){return ie.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return ie.dir(e,"previousSibling",n)},siblings:function(e){return ie.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return ie.sibling(e.firstChild)},contents:function(e){return ie.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:ie.merge([],e.childNodes)}},function(e,t){ie.fn[e]=function(n,r){var i=ie.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=ie.filter(r,i)),this.length>1&&(ye[e]||(i=ie.unique(i)),ve.test(e)&&(i=i.reverse())),this.pushStack(i)}});var be=/\S+/g,xe={};ie.Callbacks=function(e){e="string"==typeof e?xe[e]||o(e):ie.extend({},e);var t,n,r,i,a,s,u=[],l=!e.once&&[],c=function(o){for(n=e.memory&&o,r=!0,a=s||0,s=0,i=u.length,t=!0;u&&i>a;a++)if(u[a].apply(o[0],o[1])===!1&&e.stopOnFalse){n=!1;break}t=!1,u&&(l?l.length&&c(l.shift()):n?u=[]:d.disable())},d={add:function(){if(u){var r=u.length;!function o(t){ie.each(t,function(t,n){var r=ie.type(n);"function"===r?e.unique&&d.has(n)||u.push(n):n&&n.length&&"string"!==r&&o(n)})}(arguments),t?i=u.length:n&&(s=r,c(n))}return this},remove:function(){return u&&ie.each(arguments,function(e,n){for(var r;(r=ie.inArray(n,u,r))>-1;)u.splice(r,1),t&&(i>=r&&i--,a>=r&&a--)}),this},has:function(e){return e?ie.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],i=0,this},disable:function(){return u=l=n=void 0,this},disabled:function(){return!u},lock:function(){return l=void 0,n||d.disable(),this},locked:function(){return!l},fireWith:function(e,n){return!u||r&&!l||(n=n||[],n=[e,n.slice?n.slice():n],t?l.push(n):c(n)),this},fire:function(){return d.fireWith(this,arguments),this},fired:function(){return!!r}};return d},ie.extend({Deferred:function(e){var t=[["resolve","done",ie.Callbacks("once memory"),"resolved"],["reject","fail",ie.Callbacks("once memory"),"rejected"],["notify","progress",ie.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return ie.Deferred(function(n){ie.each(t,function(t,o){var a=ie.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&ie.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[o[0]+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?ie.extend(e,r):r}},i={};return r.pipe=r.then,ie.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t,n,r,i=0,o=Y.call(arguments),a=o.length,s=1!==a||e&&ie.isFunction(e.promise)?a:0,u=1===s?e:ie.Deferred(),l=function(e,n,r){return function(i){n[e]=this,r[e]=arguments.length>1?Y.call(arguments):i,r===t?u.notifyWith(n,r):--s||u.resolveWith(n,r)}};if(a>1)for(t=new Array(a),n=new Array(a),r=new Array(a);a>i;i++)o[i]&&ie.isFunction(o[i].promise)?o[i].promise().done(l(i,r,o)).fail(u.reject).progress(l(i,n,t)):--s;return s||u.resolveWith(r,o),u.promise()}});var we;ie.fn.ready=function(e){return ie.ready.promise().done(e),this},ie.extend({isReady:!1,readyWait:1,holdReady:function(e){e?ie.readyWait++:ie.ready(!0)},ready:function(e){if(e===!0?!--ie.readyWait:!ie.isReady){if(!he.body)return setTimeout(ie.ready);ie.isReady=!0,e!==!0&&--ie.readyWait>0||(we.resolveWith(he,[ie]),ie.fn.triggerHandler&&(ie(he).triggerHandler("ready"),ie(he).off("ready")))}}}),ie.ready.promise=function(t){if(!we)if(we=ie.Deferred(),"complete"===he.readyState)setTimeout(ie.ready);else if(he.addEventListener)he.addEventListener("DOMContentLoaded",s,!1),e.addEventListener("load",s,!1);else{he.attachEvent("onreadystatechange",s),e.attachEvent("onload",s);var n=!1;try{n=null==e.frameElement&&he.documentElement}catch(r){}n&&n.doScroll&&!function i(){if(!ie.isReady){try{n.doScroll("left")}catch(e){return setTimeout(i,50)}a(),ie.ready()}}()}return we.promise(t)};var Te,Ce="undefined";for(Te in ie(ne))break;ne.ownLast="0"!==Te,ne.inlineBlockNeedsLayout=!1,ie(function(){var e,t,n,r;n=he.getElementsByTagName("body")[0],n&&n.style&&(t=he.createElement("div"),r=he.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),typeof t.style.zoom!==Ce&&(t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",ne.inlineBlockNeedsLayout=e=3===t.offsetWidth,e&&(n.style.zoom=1)),n.removeChild(r))}),function(){var e=he.createElement("div");if(null==ne.deleteExpando){ne.deleteExpando=!0;try{delete e.test}catch(t){ne.deleteExpando=!1}}e=null}(),ie.acceptData=function(e){var t=ie.noData[(e.nodeName+" ").toLowerCase()],n=+e.nodeType||1;return 1!==n&&9!==n?!1:!t||t!==!0&&e.getAttribute("classid")===t};var Ne=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Ee=/([A-Z])/g;ie.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?ie.cache[e[ie.expando]]:e[ie.expando],!!e&&!l(e)},data:function(e,t,n){return c(e,t,n)},removeData:function(e,t){return d(e,t)},_data:function(e,t,n){return c(e,t,n,!0)},_removeData:function(e,t){return d(e,t,!0)}}),ie.fn.extend({data:function(e,t){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===e){if(this.length&&(i=ie.data(o),1===o.nodeType&&!ie._data(o,"parsedAttrs"))){for(n=a.length;n--;)a[n]&&(r=a[n].name,0===r.indexOf("data-")&&(r=ie.camelCase(r.slice(5)),u(o,r,i[r])));ie._data(o,"parsedAttrs",!0)}return i}return"object"==typeof e?this.each(function(){ie.data(this,e)}):arguments.length>1?this.each(function(){ie.data(this,e,t)}):o?u(o,e,ie.data(o,e)):void 0},removeData:function(e){return this.each(function(){ie.removeData(this,e)})}}),ie.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=ie._data(e,t),n&&(!r||ie.isArray(n)?r=ie._data(e,t,ie.makeArray(n)):r.push(n)),r||[]):void 0},dequeue:function(e,t){t=t||"fx";var n=ie.queue(e,t),r=n.length,i=n.shift(),o=ie._queueHooks(e,t),a=function(){ie.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return ie._data(e,n)||ie._data(e,n,{empty:ie.Callbacks("once memory").add(function(){ie._removeData(e,t+"queue"),ie._removeData(e,n)})})}}),ie.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?ie.queue(this[0],e):void 0===t?this:this.each(function(){var n=ie.queue(this,e,t);ie._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&ie.dequeue(this,e)})},dequeue:function(e){return this.each(function(){ie.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=ie.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";a--;)n=ie._data(o[a],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var ke=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Se=["Top","Right","Bottom","Left"],Ae=function(e,t){return e=t||e,"none"===ie.css(e,"display")||!ie.contains(e.ownerDocument,e)},De=ie.access=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===ie.type(n)){i=!0;for(s in n)ie.access(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,ie.isFunction(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(ie(e),n)})),t))for(;u>s;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:l?t.call(e):u?t(e[0],n):o},je=/^(?:checkbox|radio)$/i;!function(){var e=he.createElement("input"),t=he.createElement("div"),n=he.createDocumentFragment();if(t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",ne.leadingWhitespace=3===t.firstChild.nodeType,ne.tbody=!t.getElementsByTagName("tbody").length,ne.htmlSerialize=!!t.getElementsByTagName("link").length,ne.html5Clone="<:nav></:nav>"!==he.createElement("nav").cloneNode(!0).outerHTML,e.type="checkbox",e.checked=!0,n.appendChild(e),ne.appendChecked=e.checked,t.innerHTML="<textarea>x</textarea>",ne.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue,n.appendChild(t),t.innerHTML="<input type='radio' checked='checked' name='t'/>",ne.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked,ne.noCloneEvent=!0,t.attachEvent&&(t.attachEvent("onclick",function(){ne.noCloneEvent=!1}),t.cloneNode(!0).click()),null==ne.deleteExpando){ne.deleteExpando=!0;try{delete t.test}catch(r){ne.deleteExpando=!1}}}(),function(){var t,n,r=he.createElement("div");for(t in{submit:!0,change:!0,focusin:!0})n="on"+t,(ne[t+"Bubbles"]=n in e)||(r.setAttribute(n,"t"),ne[t+"Bubbles"]=r.attributes[n].expando===!1);r=null}();var Le=/^(?:input|select|textarea)$/i,He=/^key/,qe=/^(?:mouse|pointer|contextmenu)|click/,_e=/^(?:focusinfocus|focusoutblur)$/,Me=/^([^.]*)(?:\.(.+)|)$/;ie.event={global:{},add:function(e,t,n,r,i){var o,a,s,u,l,c,d,f,p,h,m,g=ie._data(e);if(g){for(n.handler&&(u=n,n=u.handler,i=u.selector),n.guid||(n.guid=ie.guid++),(a=g.events)||(a=g.events={}),(c=g.handle)||(c=g.handle=function(e){return typeof ie===Ce||e&&ie.event.triggered===e.type?void 0:ie.event.dispatch.apply(c.elem,arguments)},c.elem=e),t=(t||"").match(be)||[""],s=t.length;s--;)o=Me.exec(t[s])||[],p=m=o[1],h=(o[2]||"").split(".").sort(),p&&(l=ie.event.special[p]||{},p=(i?l.delegateType:l.bindType)||p,l=ie.event.special[p]||{},d=ie.extend({type:p,origType:m,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&ie.expr.match.needsContext.test(i),namespace:h.join(".")},u),(f=a[p])||(f=a[p]=[],f.delegateCount=0,l.setup&&l.setup.call(e,r,h,c)!==!1||(e.addEventListener?e.addEventListener(p,c,!1):e.attachEvent&&e.attachEvent("on"+p,c))),l.add&&(l.add.call(e,d),d.handler.guid||(d.handler.guid=n.guid)),i?f.splice(f.delegateCount++,0,d):f.push(d),ie.event.global[p]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,d,f,p,h,m,g=ie.hasData(e)&&ie._data(e);if(g&&(c=g.events)){for(t=(t||"").match(be)||[""],l=t.length;l--;)if(s=Me.exec(t[l])||[],p=m=s[1],h=(s[2]||"").split(".").sort(),p){for(d=ie.event.special[p]||{},p=(r?d.delegateType:d.bindType)||p,f=c[p]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;o--;)a=f[o],!i&&m!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,d.remove&&d.remove.call(e,a));u&&!f.length&&(d.teardown&&d.teardown.call(e,h,g.handle)!==!1||ie.removeEvent(e,p,g.handle),delete c[p])}else for(p in c)ie.event.remove(e,p+t[l],n,r,!0);ie.isEmptyObject(c)&&(delete g.handle,ie._removeData(e,"events"))}},trigger:function(t,n,r,i){var o,a,s,u,l,c,d,f=[r||he],p=te.call(t,"type")?t.type:t,h=te.call(t,"namespace")?t.namespace.split("."):[];if(s=c=r=r||he,3!==r.nodeType&&8!==r.nodeType&&!_e.test(p+ie.event.triggered)&&(p.indexOf(".")>=0&&(h=p.split("."),p=h.shift(),h.sort()),a=p.indexOf(":")<0&&"on"+p,t=t[ie.expando]?t:new ie.Event(p,"object"==typeof t&&t),t.isTrigger=i?2:3,t.namespace=h.join("."),t.namespace_re=t.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=r),n=null==n?[t]:ie.makeArray(n,[t]),l=ie.event.special[p]||{},i||!l.trigger||l.trigger.apply(r,n)!==!1)){if(!i&&!l.noBubble&&!ie.isWindow(r)){for(u=l.delegateType||p,_e.test(u+p)||(s=s.parentNode);s;s=s.parentNode)f.push(s),c=s;c===(r.ownerDocument||he)&&f.push(c.defaultView||c.parentWindow||e)}for(d=0;(s=f[d++])&&!t.isPropagationStopped();)t.type=d>1?u:l.bindType||p,o=(ie._data(s,"events")||{})[t.type]&&ie._data(s,"handle"),o&&o.apply(s,n),o=a&&s[a],o&&o.apply&&ie.acceptData(s)&&(t.result=o.apply(s,n),t.result===!1&&t.preventDefault());if(t.type=p,!i&&!t.isDefaultPrevented()&&(!l._default||l._default.apply(f.pop(),n)===!1)&&ie.acceptData(r)&&a&&r[p]&&!ie.isWindow(r)){c=r[a],c&&(r[a]=null),ie.event.triggered=p;try{r[p]()}catch(m){}ie.event.triggered=void 0,c&&(r[a]=c)}return t.result}},dispatch:function(e){e=ie.event.fix(e);var t,n,r,i,o,a=[],s=Y.call(arguments),u=(ie._data(this,"events")||{})[e.type]||[],l=ie.event.special[e.type]||{};if(s[0]=e,e.delegateTarget=this,!l.preDispatch||l.preDispatch.call(this,e)!==!1){for(a=ie.event.handlers.call(this,e,u),t=0;(i=a[t++])&&!e.isPropagationStopped();)for(e.currentTarget=i.elem,o=0;(r=i.handlers[o++])&&!e.isImmediatePropagationStopped();)(!e.namespace_re||e.namespace_re.test(r.namespace))&&(e.handleObj=r,e.data=r.data,n=((ie.event.special[r.origType]||{}).handle||r.handler).apply(i.elem,s),void 0!==n&&(e.result=n)===!1&&(e.preventDefault(),e.stopPropagation()));return l.postDispatch&&l.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,a=[],s=t.delegateCount,u=e.target;if(s&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(i=[],o=0;s>o;o++)r=t[o],n=r.selector+" ",void 0===i[n]&&(i[n]=r.needsContext?ie(n,this).index(u)>=0:ie.find(n,this,null,[u]).length),i[n]&&i.push(r);i.length&&a.push({elem:u,handlers:i})}return s<t.length&&a.push({elem:this,handlers:t.slice(s)}),a},fix:function(e){if(e[ie.expando])return e;var t,n,r,i=e.type,o=e,a=this.fixHooks[i];for(a||(this.fixHooks[i]=a=qe.test(i)?this.mouseHooks:He.test(i)?this.keyHooks:{}),r=a.props?this.props.concat(a.props):this.props,e=new ie.Event(o),t=r.length;t--;)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||he),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,a.filter?a.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,o=t.button,a=t.fromElement;return null==e.pageX&&null!=t.clientX&&(r=e.target.ownerDocument||he,i=r.documentElement,n=r.body,e.pageX=t.clientX+(i&&i.scrollLeft||n&&n.scrollLeft||0)-(i&&i.clientLeft||n&&n.clientLeft||0),e.pageY=t.clientY+(i&&i.scrollTop||n&&n.scrollTop||0)-(i&&i.clientTop||n&&n.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?t.toElement:a),e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==h()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===h()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return ie.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(e){return ie.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=ie.extend(new ie.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?ie.event.trigger(i,null,t):ie.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},ie.removeEvent=he.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]===Ce&&(e[r]=null),e.detachEvent(r,n))},ie.Event=function(e,t){return this instanceof ie.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?f:p):this.type=e,t&&ie.extend(this,t),this.timeStamp=e&&e.timeStamp||ie.now(),void(this[ie.expando]=!0)):new ie.Event(e,t)},ie.Event.prototype={isDefaultPrevented:p,isPropagationStopped:p,isImmediatePropagationStopped:p,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=f,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=f,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=f,e&&e.stopImmediatePropagation&&e.stopImmediatePropagation(),this.stopPropagation()}},ie.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){ie.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!ie.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),ne.submitBubbles||(ie.event.special.submit={setup:function(){return ie.nodeName(this,"form")?!1:void ie.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,n=ie.nodeName(t,"input")||ie.nodeName(t,"button")?t.form:void 0;n&&!ie._data(n,"submitBubbles")&&(ie.event.add(n,"submit._submit",function(e){e._submit_bubble=!0}),ie._data(n,"submitBubbles",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&ie.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return ie.nodeName(this,"form")?!1:void ie.event.remove(this,"._submit")}}),ne.changeBubbles||(ie.event.special.change={setup:function(){return Le.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(ie.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),ie.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),ie.event.simulate("change",this,e,!0)})),!1):void ie.event.add(this,"beforeactivate._change",function(e){var t=e.target;Le.test(t.nodeName)&&!ie._data(t,"changeBubbles")&&(ie.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||ie.event.simulate("change",this.parentNode,e,!0)}),ie._data(t,"changeBubbles",!0))})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return ie.event.remove(this,"._change"),!Le.test(this.nodeName)}}),ne.focusinBubbles||ie.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){ie.event.simulate(t,e.target,ie.event.fix(e),!0)};ie.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=ie._data(r,t);i||r.addEventListener(e,n,!0),ie._data(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=ie._data(r,t)-1;i?ie._data(r,t,i):(r.removeEventListener(e,n,!0),ie._removeData(r,t))}}}),ie.fn.extend({on:function(e,t,n,r,i){var o,a;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=void 0);for(o in e)this.on(o,t,n,e[o],i);return this}if(null==n&&null==r?(r=t,n=t=void 0):null==r&&("string"==typeof t?(r=n,n=void 0):(r=n,n=t,t=void 0)),r===!1)r=p;else if(!r)return this;return 1===i&&(a=r,r=function(e){return ie().off(e),a.apply(this,arguments)},r.guid=a.guid||(a.guid=ie.guid++)),this.each(function(){ie.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,ie(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=void 0),n===!1&&(n=p),this.each(function(){ie.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){ie.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?ie.event.trigger(e,t,n,!0):void 0}});var Fe="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Oe=/ jQuery\d+="(?:null|\d+)"/g,Be=new RegExp("<(?:"+Fe+")[\\s/>]","i"),Pe=/^\s+/,Re=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,We=/<([\w:]+)/,$e=/<tbody/i,ze=/<|&#?\w+;/,Ie=/<(?:script|style|link)/i,Xe=/checked\s*(?:[^=]|=\s*.checked.)/i,Ue=/^$|\/(?:java|ecma)script/i,Ve=/^true\/(.*)/,Je=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Ye={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:ne.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Ge=m(he),Qe=Ge.appendChild(he.createElement("div"));Ye.optgroup=Ye.option,Ye.tbody=Ye.tfoot=Ye.colgroup=Ye.caption=Ye.thead,Ye.th=Ye.td,ie.extend({clone:function(e,t,n){var r,i,o,a,s,u=ie.contains(e.ownerDocument,e);if(ne.html5Clone||ie.isXMLDoc(e)||!Be.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Qe.innerHTML=e.outerHTML,Qe.removeChild(o=Qe.firstChild)),!(ne.noCloneEvent&&ne.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||ie.isXMLDoc(e)))for(r=g(o),s=g(e),a=0;null!=(i=s[a]);++a)r[a]&&C(i,r[a]);if(t)if(n)for(s=s||g(e),r=r||g(o),a=0;null!=(i=s[a]);a++)T(i,r[a]);else T(e,o);return r=g(o,"script"),r.length>0&&w(r,!u&&g(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){for(var i,o,a,s,u,l,c,d=e.length,f=m(t),p=[],h=0;d>h;h++)if(o=e[h],o||0===o)if("object"===ie.type(o))ie.merge(p,o.nodeType?[o]:o);else if(ze.test(o)){for(s=s||f.appendChild(t.createElement("div")),u=(We.exec(o)||["",""])[1].toLowerCase(),c=Ye[u]||Ye._default,s.innerHTML=c[1]+o.replace(Re,"<$1></$2>")+c[2],i=c[0];i--;)s=s.lastChild;if(!ne.leadingWhitespace&&Pe.test(o)&&p.push(t.createTextNode(Pe.exec(o)[0])),!ne.tbody)for(o="table"!==u||$e.test(o)?"<table>"!==c[1]||$e.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;i--;)ie.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l);for(ie.merge(p,s.childNodes),s.textContent="";s.firstChild;)s.removeChild(s.firstChild);s=f.lastChild}else p.push(t.createTextNode(o));for(s&&f.removeChild(s),ne.appendChecked||ie.grep(g(p,"input"),v),h=0;o=p[h++];)if((!r||-1===ie.inArray(o,r))&&(a=ie.contains(o.ownerDocument,o),s=g(f.appendChild(o),"script"),a&&w(s),n))for(i=0;o=s[i++];)Ue.test(o.type||"")&&n.push(o);return s=null,f},cleanData:function(e,t){for(var n,r,i,o,a=0,s=ie.expando,u=ie.cache,l=ne.deleteExpando,c=ie.event.special;null!=(n=e[a]);a++)if((t||ie.acceptData(n))&&(i=n[s],o=i&&u[i])){if(o.events)for(r in o.events)c[r]?ie.event.remove(n,r):ie.removeEvent(n,r,o.handle);u[i]&&(delete u[i],l?delete n[s]:typeof n.removeAttribute!==Ce?n.removeAttribute(s):n[s]=null,J.push(i))}}}),ie.fn.extend({text:function(e){return De(this,function(e){return void 0===e?ie.text(this):this.empty().append((this[0]&&this[0].ownerDocument||he).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=y(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=y(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var n,r=e?ie.filter(e,this):this,i=0;null!=(n=r[i]);i++)t||1!==n.nodeType||ie.cleanData(g(n)),n.parentNode&&(t&&ie.contains(n.ownerDocument,n)&&w(g(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&ie.cleanData(g(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&ie.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return ie.clone(this,e,t)})},html:function(e){return De(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Oe,""):void 0;if(!("string"!=typeof e||Ie.test(e)||!ne.htmlSerialize&&Be.test(e)||!ne.leadingWhitespace&&Pe.test(e)||Ye[(We.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Re,"<$1></$2>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(ie.cleanData(g(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];return this.domManip(arguments,function(t){e=this.parentNode,ie.cleanData(g(this)),e&&e.replaceChild(t,this)}),e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=G.apply([],e);var n,r,i,o,a,s,u=0,l=this.length,c=this,d=l-1,f=e[0],p=ie.isFunction(f);if(p||l>1&&"string"==typeof f&&!ne.checkClone&&Xe.test(f))return this.each(function(n){var r=c.eq(n);p&&(e[0]=f.call(this,n,r.html())),r.domManip(e,t)});if(l&&(s=ie.buildFragment(e,this[0].ownerDocument,!1,this),n=s.firstChild,1===s.childNodes.length&&(s=n),n)){for(o=ie.map(g(s,"script"),b),i=o.length;l>u;u++)r=s,u!==d&&(r=ie.clone(r,!0,!0),i&&ie.merge(o,g(r,"script"))),t.call(this[u],r,u);if(i)for(a=o[o.length-1].ownerDocument,ie.map(o,x),u=0;i>u;u++)r=o[u],Ue.test(r.type||"")&&!ie._data(r,"globalEval")&&ie.contains(a,r)&&(r.src?ie._evalUrl&&ie._evalUrl(r.src):ie.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Je,"")));s=n=null}return this}}),ie.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){ie.fn[e]=function(e){for(var n,r=0,i=[],o=ie(e),a=o.length-1;a>=r;r++)n=r===a?this:this.clone(!0),ie(o[r])[t](n),Q.apply(i,n.get());return this.pushStack(i)}});var Ke,Ze={};!function(){var e;ne.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,n,r;return n=he.getElementsByTagName("body")[0],n&&n.style?(t=he.createElement("div"),r=he.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),typeof t.style.zoom!==Ce&&(t.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",t.appendChild(he.createElement("div")).style.width="5px",e=3!==t.offsetWidth),n.removeChild(r),e):void 0}}();var et,tt,nt=/^margin/,rt=new RegExp("^("+ke+")(?!px)[a-z%]+$","i"),it=/^(top|right|bottom|left)$/;e.getComputedStyle?(et=function(t){return t.ownerDocument.defaultView.opener?t.ownerDocument.defaultView.getComputedStyle(t,null):e.getComputedStyle(t,null)},tt=function(e,t,n){var r,i,o,a,s=e.style;return n=n||et(e),a=n?n.getPropertyValue(t)||n[t]:void 0,n&&(""!==a||ie.contains(e.ownerDocument,e)||(a=ie.style(e,t)),rt.test(a)&&nt.test(t)&&(r=s.width,i=s.minWidth, o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0===a?a:a+""}):he.documentElement.currentStyle&&(et=function(e){return e.currentStyle},tt=function(e,t,n){var r,i,o,a,s=e.style;return n=n||et(e),a=n?n[t]:void 0,null==a&&s&&s[t]&&(a=s[t]),rt.test(a)&&!it.test(t)&&(r=s.left,i=e.runtimeStyle,o=i&&i.left,o&&(i.left=e.currentStyle.left),s.left="fontSize"===t?"1em":a,a=s.pixelLeft+"px",s.left=r,o&&(i.left=o)),void 0===a?a:a+""||"auto"}),function(){function t(){var t,n,r,i;n=he.getElementsByTagName("body")[0],n&&n.style&&(t=he.createElement("div"),r=he.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),t.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",o=a=!1,u=!0,e.getComputedStyle&&(o="1%"!==(e.getComputedStyle(t,null)||{}).top,a="4px"===(e.getComputedStyle(t,null)||{width:"4px"}).width,i=t.appendChild(he.createElement("div")),i.style.cssText=t.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",t.style.width="1px",u=!parseFloat((e.getComputedStyle(i,null)||{}).marginRight),t.removeChild(i)),t.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=t.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",s=0===i[0].offsetHeight,s&&(i[0].style.display="",i[1].style.display="none",s=0===i[0].offsetHeight),n.removeChild(r))}var n,r,i,o,a,s,u;n=he.createElement("div"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",i=n.getElementsByTagName("a")[0],r=i&&i.style,r&&(r.cssText="float:left;opacity:.5",ne.opacity="0.5"===r.opacity,ne.cssFloat=!!r.cssFloat,n.style.backgroundClip="content-box",n.cloneNode(!0).style.backgroundClip="",ne.clearCloneStyle="content-box"===n.style.backgroundClip,ne.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing,ie.extend(ne,{reliableHiddenOffsets:function(){return null==s&&t(),s},boxSizingReliable:function(){return null==a&&t(),a},pixelPosition:function(){return null==o&&t(),o},reliableMarginRight:function(){return null==u&&t(),u}}))}(),ie.swap=function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i};var ot=/alpha\([^)]*\)/i,at=/opacity\s*=\s*([^)]*)/,st=/^(none|table(?!-c[ea]).+)/,ut=new RegExp("^("+ke+")(.*)$","i"),lt=new RegExp("^([+-])=("+ke+")","i"),ct={position:"absolute",visibility:"hidden",display:"block"},dt={letterSpacing:"0",fontWeight:"400"},ft=["Webkit","O","Moz","ms"];ie.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=tt(e,"opacity");return""===n?"1":n}}}},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":ne.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=ie.camelCase(t),u=e.style;if(t=ie.cssProps[s]||(ie.cssProps[s]=S(u,s)),a=ie.cssHooks[t]||ie.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:u[t];if(o=typeof n,"string"===o&&(i=lt.exec(n))&&(n=(i[1]+1)*i[2]+parseFloat(ie.css(e,t)),o="number"),null!=n&&n===n&&("number"!==o||ie.cssNumber[s]||(n+="px"),ne.clearCloneStyle||""!==n||0!==t.indexOf("background")||(u[t]="inherit"),!(a&&"set"in a&&void 0===(n=a.set(e,n,r)))))try{u[t]=n}catch(l){}}},css:function(e,t,n,r){var i,o,a,s=ie.camelCase(t);return t=ie.cssProps[s]||(ie.cssProps[s]=S(e.style,s)),a=ie.cssHooks[t]||ie.cssHooks[s],a&&"get"in a&&(o=a.get(e,!0,n)),void 0===o&&(o=tt(e,t,r)),"normal"===o&&t in dt&&(o=dt[t]),""===n||n?(i=parseFloat(o),n===!0||ie.isNumeric(i)?i||0:o):o}}),ie.each(["height","width"],function(e,t){ie.cssHooks[t]={get:function(e,n,r){return n?st.test(ie.css(e,"display"))&&0===e.offsetWidth?ie.swap(e,ct,function(){return L(e,t,r)}):L(e,t,r):void 0},set:function(e,n,r){var i=r&&et(e);return D(e,n,r?j(e,t,r,ne.boxSizing&&"border-box"===ie.css(e,"boxSizing",!1,i),i):0)}}}),ne.opacity||(ie.cssHooks.opacity={get:function(e,t){return at.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=ie.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===ie.trim(o.replace(ot,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=ot.test(o)?o.replace(ot,i):o+" "+i)}}),ie.cssHooks.marginRight=k(ne.reliableMarginRight,function(e,t){return t?ie.swap(e,{display:"inline-block"},tt,[e,"marginRight"]):void 0}),ie.each({margin:"",padding:"",border:"Width"},function(e,t){ie.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];4>r;r++)i[e+Se[r]+t]=o[r]||o[r-2]||o[0];return i}},nt.test(e)||(ie.cssHooks[e+t].set=D)}),ie.fn.extend({css:function(e,t){return De(this,function(e,t,n){var r,i,o={},a=0;if(ie.isArray(t)){for(r=et(e),i=t.length;i>a;a++)o[t[a]]=ie.css(e,t[a],!1,r);return o}return void 0!==n?ie.style(e,t,n):ie.css(e,t)},e,t,arguments.length>1)},show:function(){return A(this,!0)},hide:function(){return A(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){Ae(this)?ie(this).show():ie(this).hide()})}}),ie.Tween=H,H.prototype={constructor:H,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(ie.cssNumber[n]?"":"px")},cur:function(){var e=H.propHooks[this.prop];return e&&e.get?e.get(this):H.propHooks._default.get(this)},run:function(e){var t,n=H.propHooks[this.prop];return this.options.duration?this.pos=t=ie.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):H.propHooks._default.set(this),this}},H.prototype.init.prototype=H.prototype,H.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=ie.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){ie.fx.step[e.prop]?ie.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[ie.cssProps[e.prop]]||ie.cssHooks[e.prop])?ie.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},H.propHooks.scrollTop=H.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},ie.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},ie.fx=H.prototype.init,ie.fx.step={};var pt,ht,mt=/^(?:toggle|show|hide)$/,gt=new RegExp("^(?:([+-])=|)("+ke+")([a-z%]*)$","i"),vt=/queueHooks$/,yt=[F],bt={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=gt.exec(t),o=i&&i[3]||(ie.cssNumber[e]?"":"px"),a=(ie.cssNumber[e]||"px"!==o&&+r)&&gt.exec(ie.css(n.elem,e)),s=1,u=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,ie.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--u)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};ie.Animation=ie.extend(B,{tweener:function(e,t){ie.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var n,r=0,i=e.length;i>r;r++)n=e[r],bt[n]=bt[n]||[],bt[n].unshift(t)},prefilter:function(e,t){t?yt.unshift(e):yt.push(e)}}),ie.speed=function(e,t,n){var r=e&&"object"==typeof e?ie.extend({},e):{complete:n||!n&&t||ie.isFunction(e)&&e,duration:e,easing:n&&t||t&&!ie.isFunction(t)&&t};return r.duration=ie.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in ie.fx.speeds?ie.fx.speeds[r.duration]:ie.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){ie.isFunction(r.old)&&r.old.call(this),r.queue&&ie.dequeue(this,r.queue)},r},ie.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Ae).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=ie.isEmptyObject(e),o=ie.speed(t,n,r),a=function(){var t=B(this,ie.extend({},e),o);(i||ie._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=ie.timers,a=ie._data(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&vt.test(i)&&r(a[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));(t||!n)&&ie.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=ie._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=ie.timers,a=r?r.length:0;for(n.finish=!0,ie.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}}),ie.each(["toggle","show","hide"],function(e,t){var n=ie.fn[t];ie.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(_(t,!0),e,r,i)}}),ie.each({slideDown:_("show"),slideUp:_("hide"),slideToggle:_("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){ie.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),ie.timers=[],ie.fx.tick=function(){var e,t=ie.timers,n=0;for(pt=ie.now();n<t.length;n++)e=t[n],e()||t[n]!==e||t.splice(n--,1);t.length||ie.fx.stop(),pt=void 0},ie.fx.timer=function(e){ie.timers.push(e),e()?ie.fx.start():ie.timers.pop()},ie.fx.interval=13,ie.fx.start=function(){ht||(ht=setInterval(ie.fx.tick,ie.fx.interval))},ie.fx.stop=function(){clearInterval(ht),ht=null},ie.fx.speeds={slow:600,fast:200,_default:400},ie.fn.delay=function(e,t){return e=ie.fx?ie.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},function(){var e,t,n,r,i;t=he.createElement("div"),t.setAttribute("className","t"),t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",r=t.getElementsByTagName("a")[0],n=he.createElement("select"),i=n.appendChild(he.createElement("option")),e=t.getElementsByTagName("input")[0],r.style.cssText="top:1px",ne.getSetAttribute="t"!==t.className,ne.style=/top/.test(r.getAttribute("style")),ne.hrefNormalized="/a"===r.getAttribute("href"),ne.checkOn=!!e.value,ne.optSelected=i.selected,ne.enctype=!!he.createElement("form").enctype,n.disabled=!0,ne.optDisabled=!i.disabled,e=he.createElement("input"),e.setAttribute("value",""),ne.input=""===e.getAttribute("value"),e.value="t",e.setAttribute("type","radio"),ne.radioValue="t"===e.value}();var xt=/\r/g;ie.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=ie.isFunction(e),this.each(function(n){var i;1===this.nodeType&&(i=r?e.call(this,n,ie(this).val()):e,null==i?i="":"number"==typeof i?i+="":ie.isArray(i)&&(i=ie.map(i,function(e){return null==e?"":e+""})),t=ie.valHooks[this.type]||ie.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return t=ie.valHooks[i.type]||ie.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:(n=i.value,"string"==typeof n?n.replace(xt,""):null==n?"":n)}}}),ie.extend({valHooks:{option:{get:function(e){var t=ie.find.attr(e,"value");return null!=t?t:ie.trim(ie.text(e))}},select:{get:function(e){for(var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(ne.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&ie.nodeName(n.parentNode,"optgroup"))){if(t=ie(n).val(),o)return t;a.push(t)}return a},set:function(e,t){for(var n,r,i=e.options,o=ie.makeArray(t),a=i.length;a--;)if(r=i[a],ie.inArray(ie.valHooks.option.get(r),o)>=0)try{r.selected=n=!0}catch(s){r.scrollHeight}else r.selected=!1;return n||(e.selectedIndex=-1),i}}}}),ie.each(["radio","checkbox"],function(){ie.valHooks[this]={set:function(e,t){return ie.isArray(t)?e.checked=ie.inArray(ie(e).val(),t)>=0:void 0}},ne.checkOn||(ie.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var wt,Tt,Ct=ie.expr.attrHandle,Nt=/^(?:checked|selected)$/i,Et=ne.getSetAttribute,kt=ne.input;ie.fn.extend({attr:function(e,t){return De(this,ie.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){ie.removeAttr(this,e)})}}),ie.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o)return typeof e.getAttribute===Ce?ie.prop(e,t,n):(1===o&&ie.isXMLDoc(e)||(t=t.toLowerCase(),r=ie.attrHooks[t]||(ie.expr.match.bool.test(t)?Tt:wt)),void 0===n?r&&"get"in r&&null!==(i=r.get(e,t))?i:(i=ie.find.attr(e,t),null==i?void 0:i):null!==n?r&&"set"in r&&void 0!==(i=r.set(e,n,t))?i:(e.setAttribute(t,n+""),n):void ie.removeAttr(e,t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(be);if(o&&1===e.nodeType)for(;n=o[i++];)r=ie.propFix[n]||n,ie.expr.match.bool.test(n)?kt&&Et||!Nt.test(n)?e[r]=!1:e[ie.camelCase("default-"+n)]=e[r]=!1:ie.attr(e,n,""),e.removeAttribute(Et?n:r)},attrHooks:{type:{set:function(e,t){if(!ne.radioValue&&"radio"===t&&ie.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}}}),Tt={set:function(e,t,n){return t===!1?ie.removeAttr(e,n):kt&&Et||!Nt.test(n)?e.setAttribute(!Et&&ie.propFix[n]||n,n):e[ie.camelCase("default-"+n)]=e[n]=!0,n}},ie.each(ie.expr.match.bool.source.match(/\w+/g),function(e,t){var n=Ct[t]||ie.find.attr;Ct[t]=kt&&Et||!Nt.test(t)?function(e,t,r){var i,o;return r||(o=Ct[t],Ct[t]=i,i=null!=n(e,t,r)?t.toLowerCase():null,Ct[t]=o),i}:function(e,t,n){return n?void 0:e[ie.camelCase("default-"+t)]?t.toLowerCase():null}}),kt&&Et||(ie.attrHooks.value={set:function(e,t,n){return ie.nodeName(e,"input")?void(e.defaultValue=t):wt&&wt.set(e,t,n)}}),Et||(wt={set:function(e,t,n){var r=e.getAttributeNode(n);return r||e.setAttributeNode(r=e.ownerDocument.createAttribute(n)),r.value=t+="","value"===n||t===e.getAttribute(n)?t:void 0}},Ct.id=Ct.name=Ct.coords=function(e,t,n){var r;return n?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null},ie.valHooks.button={get:function(e,t){var n=e.getAttributeNode(t);return n&&n.specified?n.value:void 0},set:wt.set},ie.attrHooks.contenteditable={set:function(e,t,n){wt.set(e,""===t?!1:t,n)}},ie.each(["width","height"],function(e,t){ie.attrHooks[t]={set:function(e,n){return""===n?(e.setAttribute(t,"auto"),n):void 0}}})),ne.style||(ie.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var St=/^(?:input|select|textarea|button|object)$/i,At=/^(?:a|area)$/i;ie.fn.extend({prop:function(e,t){return De(this,ie.prop,e,t,arguments.length>1)},removeProp:function(e){return e=ie.propFix[e]||e,this.each(function(){try{this[e]=void 0,delete this[e]}catch(t){}})}}),ie.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,a=e.nodeType;if(e&&3!==a&&8!==a&&2!==a)return o=1!==a||!ie.isXMLDoc(e),o&&(t=ie.propFix[t]||t,i=ie.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=ie.find.attr(e,"tabindex");return t?parseInt(t,10):St.test(e.nodeName)||At.test(e.nodeName)&&e.href?0:-1}}}}),ne.hrefNormalized||ie.each(["href","src"],function(e,t){ie.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),ne.optSelected||(ie.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),ie.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ie.propFix[this.toLowerCase()]=this}),ne.enctype||(ie.propFix.enctype="encoding");var Dt=/[\t\r\n\f]/g;ie.fn.extend({addClass:function(e){var t,n,r,i,o,a,s=0,u=this.length,l="string"==typeof e&&e;if(ie.isFunction(e))return this.each(function(t){ie(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(be)||[];u>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(Dt," "):" ")){for(o=0;i=t[o++];)r.indexOf(" "+i+" ")<0&&(r+=i+" ");a=ie.trim(r),n.className!==a&&(n.className=a)}return this},removeClass:function(e){var t,n,r,i,o,a,s=0,u=this.length,l=0===arguments.length||"string"==typeof e&&e;if(ie.isFunction(e))return this.each(function(t){ie(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(be)||[];u>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(Dt," "):"")){for(o=0;i=t[o++];)for(;r.indexOf(" "+i+" ")>=0;)r=r.replace(" "+i+" "," ");a=e?ie.trim(r):"",n.className!==a&&(n.className=a)}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):ie.isFunction(e)?this.each(function(n){ie(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n)for(var t,r=0,i=ie(this),o=e.match(be)||[];t=o[r++];)i.hasClass(t)?i.removeClass(t):i.addClass(t);else(n===Ce||"boolean"===n)&&(this.className&&ie._data(this,"__className__",this.className),this.className=this.className||e===!1?"":ie._data(this,"__className__")||"")})},hasClass:function(e){for(var t=" "+e+" ",n=0,r=this.length;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(Dt," ").indexOf(t)>=0)return!0;return!1}}),ie.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){ie.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),ie.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var jt=ie.now(),Lt=/\?/,Ht=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;ie.parseJSON=function(t){if(e.JSON&&e.JSON.parse)return e.JSON.parse(t+"");var n,r=null,i=ie.trim(t+"");return i&&!ie.trim(i.replace(Ht,function(e,t,i,o){return n&&t&&(r=0),0===r?e:(n=i||t,r+=!o-!i,"")}))?Function("return "+i)():ie.error("Invalid JSON: "+t)},ie.parseXML=function(t){var n,r;if(!t||"string"!=typeof t)return null;try{e.DOMParser?(r=new DOMParser,n=r.parseFromString(t,"text/xml")):(n=new ActiveXObject("Microsoft.XMLDOM"),n.async="false",n.loadXML(t))}catch(i){n=void 0}return n&&n.documentElement&&!n.getElementsByTagName("parsererror").length||ie.error("Invalid XML: "+t),n};var qt,_t,Mt=/#.*$/,Ft=/([?&])_=[^&]*/,Ot=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Bt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Pt=/^(?:GET|HEAD)$/,Rt=/^\/\//,Wt=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,$t={},zt={},It="*/".concat("*");try{_t=location.href}catch(Xt){_t=he.createElement("a"),_t.href="",_t=_t.href}qt=Wt.exec(_t.toLowerCase())||[],ie.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:_t,type:"GET",isLocal:Bt.test(qt[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":It,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":ie.parseJSON,"text xml":ie.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?W(W(e,ie.ajaxSettings),t):W(ie.ajaxSettings,e)},ajaxPrefilter:P($t),ajaxTransport:P(zt),ajax:function(e,t){function n(e,t,n,r){var i,c,v,y,x,T=t;2!==b&&(b=2,s&&clearTimeout(s),l=void 0,a=r||"",w.readyState=e>0?4:0,i=e>=200&&300>e||304===e,n&&(y=$(d,w,n)),y=z(d,y,w,i),i?(d.ifModified&&(x=w.getResponseHeader("Last-Modified"),x&&(ie.lastModified[o]=x),x=w.getResponseHeader("etag"),x&&(ie.etag[o]=x)),204===e||"HEAD"===d.type?T="nocontent":304===e?T="notmodified":(T=y.state,c=y.data,v=y.error,i=!v)):(v=T,(e||!T)&&(T="error",0>e&&(e=0))),w.status=e,w.statusText=(t||T)+"",i?h.resolveWith(f,[c,T,w]):h.rejectWith(f,[w,T,v]),w.statusCode(g),g=void 0,u&&p.trigger(i?"ajaxSuccess":"ajaxError",[w,d,i?c:v]),m.fireWith(f,[w,T]),u&&(p.trigger("ajaxComplete",[w,d]),--ie.active||ie.event.trigger("ajaxStop")))}"object"==typeof e&&(t=e,e=void 0),t=t||{};var r,i,o,a,s,u,l,c,d=ie.ajaxSetup({},t),f=d.context||d,p=d.context&&(f.nodeType||f.jquery)?ie(f):ie.event,h=ie.Deferred(),m=ie.Callbacks("once memory"),g=d.statusCode||{},v={},y={},b=0,x="canceled",w={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c)for(c={};t=Ot.exec(a);)c[t[1].toLowerCase()]=t[2];t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=y[n]=y[n]||e,v[e]=t),this},overrideMimeType:function(e){return b||(d.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)g[t]=[g[t],e[t]];else w.always(e[w.status]);return this},abort:function(e){var t=e||x;return l&&l.abort(t),n(0,t),this}};if(h.promise(w).complete=m.add,w.success=w.done,w.error=w.fail,d.url=((e||d.url||_t)+"").replace(Mt,"").replace(Rt,qt[1]+"//"),d.type=t.method||t.type||d.method||d.type,d.dataTypes=ie.trim(d.dataType||"*").toLowerCase().match(be)||[""],null==d.crossDomain&&(r=Wt.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]===qt[1]&&r[2]===qt[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(qt[3]||("http:"===qt[1]?"80":"443")))),d.data&&d.processData&&"string"!=typeof d.data&&(d.data=ie.param(d.data,d.traditional)),R($t,d,t,w),2===b)return w;u=ie.event&&d.global,u&&0===ie.active++&&ie.event.trigger("ajaxStart"),d.type=d.type.toUpperCase(),d.hasContent=!Pt.test(d.type),o=d.url,d.hasContent||(d.data&&(o=d.url+=(Lt.test(o)?"&":"?")+d.data,delete d.data),d.cache===!1&&(d.url=Ft.test(o)?o.replace(Ft,"$1_="+jt++):o+(Lt.test(o)?"&":"?")+"_="+jt++)),d.ifModified&&(ie.lastModified[o]&&w.setRequestHeader("If-Modified-Since",ie.lastModified[o]),ie.etag[o]&&w.setRequestHeader("If-None-Match",ie.etag[o])),(d.data&&d.hasContent&&d.contentType!==!1||t.contentType)&&w.setRequestHeader("Content-Type",d.contentType),w.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+("*"!==d.dataTypes[0]?", "+It+"; q=0.01":""):d.accepts["*"]);for(i in d.headers)w.setRequestHeader(i,d.headers[i]);if(d.beforeSend&&(d.beforeSend.call(f,w,d)===!1||2===b))return w.abort();x="abort";for(i in{success:1,error:1,complete:1})w[i](d[i]);if(l=R(zt,d,t,w)){w.readyState=1,u&&p.trigger("ajaxSend",[w,d]),d.async&&d.timeout>0&&(s=setTimeout(function(){w.abort("timeout")},d.timeout));try{b=1,l.send(v,n)}catch(T){if(!(2>b))throw T;n(-1,T)}}else n(-1,"No Transport");return w},getJSON:function(e,t,n){return ie.get(e,t,n,"json")},getScript:function(e,t){return ie.get(e,void 0,t,"script")}}),ie.each(["get","post"],function(e,t){ie[t]=function(e,n,r,i){return ie.isFunction(n)&&(i=i||r,r=n,n=void 0),ie.ajax({url:e,type:t,dataType:i,data:n,success:r})}}),ie._evalUrl=function(e){return ie.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},ie.fn.extend({wrapAll:function(e){if(ie.isFunction(e))return this.each(function(t){ie(this).wrapAll(e.call(this,t))});if(this[0]){var t=ie(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return ie.isFunction(e)?this.each(function(t){ie(this).wrapInner(e.call(this,t))}):this.each(function(){var t=ie(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=ie.isFunction(e);return this.each(function(n){ie(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){ie.nodeName(this,"body")||ie(this).replaceWith(this.childNodes)}).end()}}),ie.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!ne.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||ie.css(e,"display"))},ie.expr.filters.visible=function(e){return!ie.expr.filters.hidden(e)};var Ut=/%20/g,Vt=/\[\]$/,Jt=/\r?\n/g,Yt=/^(?:submit|button|image|reset|file)$/i,Gt=/^(?:input|select|textarea|keygen)/i;ie.param=function(e,t){var n,r=[],i=function(e,t){t=ie.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=ie.ajaxSettings&&ie.ajaxSettings.traditional),ie.isArray(e)||e.jquery&&!ie.isPlainObject(e))ie.each(e,function(){i(this.name,this.value)});else for(n in e)I(n,e[n],t,i);return r.join("&").replace(Ut,"+")},ie.fn.extend({serialize:function(){return ie.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=ie.prop(this,"elements");return e?ie.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!ie(this).is(":disabled")&&Gt.test(this.nodeName)&&!Yt.test(e)&&(this.checked||!je.test(e))}).map(function(e,t){var n=ie(this).val();return null==n?null:ie.isArray(n)?ie.map(n,function(e){return{name:t.name,value:e.replace(Jt,"\r\n")}}):{name:t.name,value:n.replace(Jt,"\r\n")}}).get()}}),ie.ajaxSettings.xhr=void 0!==e.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&X()||U()}:X;var Qt=0,Kt={},Zt=ie.ajaxSettings.xhr();e.attachEvent&&e.attachEvent("onunload",function(){for(var e in Kt)Kt[e](void 0,!0)}),ne.cors=!!Zt&&"withCredentials"in Zt,Zt=ne.ajax=!!Zt,Zt&&ie.ajaxTransport(function(e){if(!e.crossDomain||ne.cors){var t;return{send:function(n,r){var i,o=e.xhr(),a=++Qt;if(o.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(i in e.xhrFields)o[i]=e.xhrFields[i];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType),e.crossDomain||n["X-Requested-With"]||(n["X-Requested-With"]="XMLHttpRequest");for(i in n)void 0!==n[i]&&o.setRequestHeader(i,n[i]+"");o.send(e.hasContent&&e.data||null),t=function(n,i){var s,u,l;if(t&&(i||4===o.readyState))if(delete Kt[a],t=void 0,o.onreadystatechange=ie.noop,i)4!==o.readyState&&o.abort();else{l={},s=o.status,"string"==typeof o.responseText&&(l.text=o.responseText);try{u=o.statusText}catch(c){u=""}s||!e.isLocal||e.crossDomain?1223===s&&(s=204):s=l.text?200:404}l&&r(s,u,l,o.getAllResponseHeaders())},e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=Kt[a]=t:t()},abort:function(){t&&t(void 0,!0)}}}}),ie.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return ie.globalEval(e),e}}}),ie.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),ie.ajaxTransport("script",function(e){if(e.crossDomain){var t,n=he.head||ie("head")[0]||he.documentElement;return{send:function(r,i){t=he.createElement("script"),t.async=!0,e.scriptCharset&&(t.charset=e.scriptCharset),t.src=e.url,t.onload=t.onreadystatechange=function(e,n){(n||!t.readyState||/loaded|complete/.test(t.readyState))&&(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),t=null,n||i(200,"success"))},n.insertBefore(t,n.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var en=[],tn=/(=)\?(?=&|$)|\?\?/;ie.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=en.pop()||ie.expando+"_"+jt++;return this[e]=!0,e}}),ie.ajaxPrefilter("json jsonp",function(t,n,r){var i,o,a,s=t.jsonp!==!1&&(tn.test(t.url)?"url":"string"==typeof t.data&&!(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&tn.test(t.data)&&"data");return s||"jsonp"===t.dataTypes[0]?(i=t.jsonpCallback=ie.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,s?t[s]=t[s].replace(tn,"$1"+i):t.jsonp!==!1&&(t.url+=(Lt.test(t.url)?"&":"?")+t.jsonp+"="+i),t.converters["script json"]=function(){return a||ie.error(i+" was not called"),a[0]},t.dataTypes[0]="json",o=e[i],e[i]=function(){a=arguments},r.always(function(){e[i]=o,t[i]&&(t.jsonpCallback=n.jsonpCallback,en.push(i)),a&&ie.isFunction(o)&&o(a[0]),a=o=void 0}),"script"):void 0}),ie.parseHTML=function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||he;var r=de.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=ie.buildFragment([e],t,i),i&&i.length&&ie(i).remove(),ie.merge([],r.childNodes))};var nn=ie.fn.load;ie.fn.load=function(e,t,n){if("string"!=typeof e&&nn)return nn.apply(this,arguments);var r,i,o,a=this,s=e.indexOf(" ");return s>=0&&(r=ie.trim(e.slice(s,e.length)),e=e.slice(0,s)),ie.isFunction(t)?(n=t,t=void 0):t&&"object"==typeof t&&(o="POST"),a.length>0&&ie.ajax({url:e,type:o,dataType:"html",data:t}).done(function(e){i=arguments,a.html(r?ie("<div>").append(ie.parseHTML(e)).find(r):e)}).complete(n&&function(e,t){a.each(n,i||[e.responseText,t,e])}),this},ie.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ie.fn[t]=function(e){return this.on(t,e)}}),ie.expr.filters.animated=function(e){return ie.grep(ie.timers,function(t){return e===t.elem}).length};var rn=e.document.documentElement;ie.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l,c=ie.css(e,"position"),d=ie(e),f={};"static"===c&&(e.style.position="relative"),s=d.offset(),o=ie.css(e,"top"),u=ie.css(e,"left"),l=("absolute"===c||"fixed"===c)&&ie.inArray("auto",[o,u])>-1,l?(r=d.position(),a=r.top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),ie.isFunction(t)&&(t=t.call(e,n,s)),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):d.css(f)}},ie.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){ie.offset.setOffset(this,e,t)});var t,n,r={top:0,left:0},i=this[0],o=i&&i.ownerDocument;if(o)return t=o.documentElement,ie.contains(t,i)?(typeof i.getBoundingClientRect!==Ce&&(r=i.getBoundingClientRect()),n=V(o),{top:r.top+(n.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(n.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}):r},position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===ie.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),ie.nodeName(e[0],"html")||(n=e.offset()),n.top+=ie.css(e[0],"borderTopWidth",!0),n.left+=ie.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-ie.css(r,"marginTop",!0),left:t.left-n.left-ie.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||rn;e&&!ie.nodeName(e,"html")&&"static"===ie.css(e,"position");)e=e.offsetParent;return e||rn})}}),ie.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n=/Y/.test(t);ie.fn[e]=function(r){return De(this,function(e,r,i){var o=V(e);return void 0===i?o?t in o?o[t]:o.document.documentElement[r]:e[r]:void(o?o.scrollTo(n?ie(o).scrollLeft():i,n?i:ie(o).scrollTop()):e[r]=i)},e,r,arguments.length,null)}}),ie.each(["top","left"],function(e,t){ie.cssHooks[t]=k(ne.pixelPosition,function(e,n){return n?(n=tt(e,t),rt.test(n)?ie(e).position()[t]+"px":n):void 0})}),ie.each({Height:"height",Width:"width"},function(e,t){ie.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){ie.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),a=n||(r===!0||i===!0?"margin":"border"); return De(this,function(t,n,r){var i;return ie.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(i=t.documentElement,Math.max(t.body["scroll"+e],i["scroll"+e],t.body["offset"+e],i["offset"+e],i["client"+e])):void 0===r?ie.css(t,n,a):ie.style(t,n,r,a)},t,o?r:void 0,o,null)}})}),ie.fn.size=function(){return this.length},ie.fn.andSelf=ie.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return ie});var on=e.jQuery,an=e.$;return ie.noConflict=function(t){return e.$===ie&&(e.$=an),t&&e.jQuery===ie&&(e.jQuery=on),ie},typeof t===Ce&&(e.jQuery=e.$=ie),ie}); },{}],7:[function(require,module,exports){ "use strict";module.exports=function(e){var o=encodeURIComponent(e.getURL());return{popup:!0,shareText:{bg:"cподеляне",da:"del",de:"teilen",en:"share",es:"compartir",fi:"Jaa",fr:"partager",hr:"podijelite",hu:"megosztás",it:"condividi",ja:"共有",ko:"공유하기",nl:"delen",no:"del",pl:"udostępnij",pt:"compartilhar",ro:"partajează",ru:"поделиться",sk:"zdieľať",sl:"deli",sr:"podeli",sv:"dela",tr:"paylaş",zh:"分享"},name:"facebook",faName:"fa-facebook",title:{bg:"Сподели във Facebook",da:"Del på Facebook",de:"Bei Facebook teilen",en:"Share on Facebook",es:"Compartir en Facebook",fi:"Jaa Facebookissa",fr:"Partager sur Facebook",hr:"Podijelite na Facebooku",hu:"Megosztás Facebookon",it:"Condividi su Facebook",ja:"フェイスブック上で共有",ko:"페이스북에서 공유하기",nl:"Delen op Facebook",no:"Del på Facebook",pl:"Udostępnij na Facebooku",pt:"Compartilhar no Facebook",ro:"Partajează pe Facebook",ru:"Поделиться на Facebook",sk:"Zdieľať na Facebooku",sl:"Deli na Facebooku",sr:"Podeli na Facebook-u",sv:"Dela på Facebook",tr:"Facebook'ta paylaş",zh:"在Facebook上分享"},shareUrl:"https://www.facebook.com/sharer/sharer.php?u="+o+e.getReferrerTrack()}}; },{}],8:[function(require,module,exports){ "use strict";module.exports=function(o){var e=encodeURIComponent(o.getURL());return{popup:!0,shareText:"+1",name:"googleplus",faName:"fa-google-plus",title:{bg:"Сподели в Google+",da:"Del på Google+",de:"Bei Google+ teilen",en:"Share on Google+",es:"Compartir en Google+",fi:"Jaa Google+:ssa",fr:"Partager sur Goolge+",hr:"Podijelite na Google+",hu:"Megosztás Google+on",it:"Condividi su Google+",ja:"Google+上で共有",ko:"Google+에서 공유하기",nl:"Delen op Google+",no:"Del på Google+",pl:"Udostępnij na Google+",pt:"Compartilhar no Google+",ro:"Partajează pe Google+",ru:"Поделиться на Google+",sk:"Zdieľať na Google+",sl:"Deli na Google+",sr:"Podeli na Google+",sv:"Dela på Google+",tr:"Google+'da paylaş",zh:"在Google+上分享"},shareUrl:"https://plus.google.com/share?url="+e+o.getReferrerTrack()}}; },{}],9:[function(require,module,exports){ "use strict";module.exports=function(e){return{blank:!0,popup:!1,shareText:"Info",name:"info",faName:"fa-info",title:{de:"weitere Informationen",en:"more information",es:"más informaciones",fr:"plus d'informations",it:"maggiori informazioni",da:"flere oplysninger",nl:"verdere informatie"},shareUrl:e.getInfoUrl()}}; },{}],10:[function(require,module,exports){ "use strict";module.exports=function(e){var n=encodeURIComponent(e.getURL());return{popup:!0,shareText:{de:"mitteilen",en:"share",es:"compartir",fi:"Jaa",fr:"partager",hr:"podijelite",hu:"megosztás",it:"condividi",ja:"シェア",ko:"공유하기",nl:"delen",no:"del",pl:"udostępnij",pt:"compartilhar",ro:"distribuiți",ru:"поделиться",sk:"zdieľať",sl:"deli",sr:"podeli",sv:"dela",tr:"paylaş",zh:"分享"},name:"linkedin",faName:"fa-linkedin",title:{bg:"Сподели в LinkedIn",da:"Del på LinkedIn",de:"Bei LinkedIn teilen",en:"Share on LinkedIn",es:"Compartir en LinkedIn",fi:"Jaa LinkedInissä",fr:"Partager sur LinkedIn",hr:"Podijelite na LinkedIn",hu:"Megosztás LinkedInen",it:"Condividi su LinkedIn",ja:"LinkedIn上で共有",ko:"LinkedIn에서 공유하기",nl:"Delen op LinkedIn",no:"Del på LinkedIn",pl:"Udostępnij przez LinkedIn",pt:"Compartilhar no LinkedIn",ro:"Partajează pe LinkedIn",ru:"Поделиться на LinkedIn",sk:"Zdieľať na LinkedIn",sl:"Deli na LinkedIn",sr:"Podeli na LinkedIn-u",sv:"Dela på LinkedIn",tr:"LinkedIn'ta paylaş",zh:"在LinkedIn上分享"},shareUrl:"https://www.linkedin.com/cws/share?url="+n+e.getReferrerTrack()}}; },{}],11:[function(require,module,exports){ "use strict";module.exports=function(e){var i=e.getOption("mailUrl");return 0===i.indexOf("mailto:")&&(i+="?subject="+encodeURIComponent(e.getOption("mailSubject")),i+="&body="+encodeURIComponent(e.getOption("mailBody"))),{blank:0===i.indexOf("http"),popup:!1,shareText:"mail",name:"mail",faName:"fa-envelope",title:{bg:"Изпрати по имейл",da:"Sende via e-mail",de:"Per E-Mail versenden",en:"Send by email",es:"Enviar por email",fi:"Lähetä sähköpostitse",fr:"Envoyer par courriel",hr:"Pošaljite emailom",hu:"Elküldés e-mailben",it:"Inviare via email",ja:"電子メールで送信",ko:"이메일로 보내기",nl:"Sturen via e-mail",no:"Send via epost",pl:"Wyślij e-mailem",pt:"Enviar por e-mail",ro:"Trimite prin e-mail",ru:"Отправить по эл. почте",sk:"Poslať e-mailom",sl:"Pošlji po elektronski pošti",sr:"Pošalji putem email-a",sv:"Skicka via e-post",tr:"E-posta ile gönder",zh:"通过电子邮件传送"},shareUrl:i}}; },{}],12:[function(require,module,exports){ "use strict";var url=require("url");module.exports=function(e){var t=e.getMeta("DC.title")||e.getTitle(),r=e.getMeta("DC.creator");r.length>0&&(t+=" - "+r);var i=url.parse("https://www.pinterest.com/pin/create/link/",!0);return i.query.url=e.getURL(),i.query.media=e.getOption("mediaUrl"),i.query.description=t,delete i.search,{popup:!0,shareText:"pin it",name:"pinterest",faName:"fa-pinterest-p",title:{de:"Bei Pinterest pinnen",en:"Pin it on Pinterest",es:"Compartir en Pinterest",fr:"Partager sur Pinterest",it:"Condividi su Pinterest",da:"Del på Pinterest",nl:"Delen op Pinterest"},shareUrl:url.format(i)+e.getReferrerTrack()}}; },{"url":5}],13:[function(require,module,exports){ "use strict";var url=require("url"),$=require("jquery"),abbreviateText=function(t,e){var r=$("<div/>").html(t).text();if(r.length<=e)return t;var i=r.substring(0,e-1).lastIndexOf(" ");return r=r.substring(0,i)+"…"};module.exports=function(t){var e=url.parse("https://twitter.com/intent/tweet",!0),r=t.getMeta("DC.title"),i=t.getMeta("DC.creator");return r.length>0&&i.length>0?r+=" - "+i:r=t.getTitle(),e.query.text=abbreviateText(r,120),e.query.url=t.getURL(),null!==t.options.twitterVia&&(e.query.via=t.options.twitterVia),delete e.search,{popup:!0,shareText:"tweet",name:"twitter",faName:"fa-twitter",title:{bg:"Сподели в Twitter",da:"Del på Twitter",de:"Bei Twitter teilen",en:"Share on Twitter",es:"Compartir en Twitter",fi:"Jaa Twitterissä",fr:"Partager sur Twitter",hr:"Podijelite na Twitteru",hu:"Megosztás Twitteren",it:"Condividi su Twitter",ja:"ツイッター上で共有",ko:"트위터에서 공유하기",nl:"Delen op Twitter",no:"Del på Twitter",pl:"Udostępnij na Twitterze",pt:"Compartilhar no Twitter",ro:"Partajează pe Twitter",ru:"Поделиться на Twitter",sk:"Zdieľať na Twitteri",sl:"Deli na Twitterju",sr:"Podeli na Twitter-u",sv:"Dela på Twitter",tr:"Twitter'da paylaş",zh:"在Twitter上分享"},shareUrl:url.format(e)+t.getReferrerTrack()}}; },{"jquery":6,"url":5}],14:[function(require,module,exports){ "use strict";module.exports=function(a){var p=encodeURIComponent(a.getURL()),e=a.getMeta("DC.title"),t=a.getMeta("DC.creator");return e.length>0&&t.length>0?e+=" - "+t:e=a.getTitle(),{popup:!1,shareText:{bg:"cподеляне",da:"del",de:"teilen",en:"share",es:"compartir",fi:"Jaa",fr:"partager",hr:"podijelite",hu:"megosztás",it:"condividi",ja:"共有",ko:"공유하기",nl:"delen",no:"del",pl:"udostępnij",pt:"compartilhar",ro:"partajează",ru:"поделиться",sk:"zdieľať",sl:"deli",sr:"podeli",sv:"dela",tr:"paylaş",zh:"分享"},name:"whatsapp",faName:"fa-whatsapp",title:{bg:"Сподели в Whatsapp",da:"Del på Whatsapp",de:"Bei Whatsapp teilen",en:"Share on Whatsapp",es:"Compartir en Whatsapp",fi:"Jaa WhatsAppissä",fr:"Partager sur Whatsapp",hr:"Podijelite na Whatsapp",hu:"Megosztás WhatsAppen",it:"Condividi su Whatsapp",ja:"Whatsapp上で共有",ko:"Whatsapp에서 공유하기",nl:"Delen op Whatsapp",no:"Del på Whatsapp",pl:"Udostępnij przez WhatsApp",pt:"Compartilhar no Whatsapp",ro:"Partajează pe Whatsapp",ru:"Поделиться на Whatsapp",sk:"Zdieľať na Whatsapp",sl:"Deli na Whatsapp",sr:"Podeli na WhatsApp-u",sv:"Dela på Whatsapp",tr:"Whatsapp'ta paylaş",zh:"在Whatsapp上分享"},shareUrl:"whatsapp://send?text="+encodeURIComponent(e)+"%20"+p+a.getReferrerTrack()}}; },{}],15:[function(require,module,exports){ "use strict";module.exports=function(e){var r=encodeURIComponent(e.getURL());return{popup:!0,shareText:{de:"teilen",en:"share",es:"compartir",fr:"partager",it:"condividi",da:"del",nl:"delen"},name:"xing",faName:"fa-xing",title:{de:"Bei XING teilen",en:"Share on XING",es:"Compartir en XING",fr:"Partager sur XING",it:"Condividi su XING",da:"Del på XING",nl:"Delen op XING"},shareUrl:"https://www.xing.com/social_plugins/share?url="+r+e.getReferrerTrack()}}; },{}],16:[function(require,module,exports){ (function (global){ "use strict";var $=require("jquery"),url=require("url"),Shariff=function(t,e){var r=this;this.element=t,$(t).empty(),this.options=$.extend({},this.defaults,e,$(t).data());var i=[require("./services/facebook"),require("./services/googleplus"),require("./services/info"),require("./services/linkedin"),require("./services/mail"),require("./services/pinterest"),require("./services/twitter"),require("./services/whatsapp"),require("./services/xing")];this.services=$.map(this.options.services,function(t){var e;return i.forEach(function(i){return i=i(r),i.name===t?(e=i,null):void 0}),e}),this._addButtonList(),null!==this.options.backendUrl&&this.getShares().then($.proxy(this._updateCounts,this))};Shariff.prototype={defaults:{theme:"color",backendUrl:null,infoUrl:"http://ct.de/-2467514",lang:"de",langFallback:"en",mailUrl:function(){var t=url.parse(this.getURL(),!0);return t.query.view="mail",delete t.search,url.format(t)},mailSubject:function(){return this.getMeta("DC.title")||this.getTitle()},mailBody:function(){return"<"+this.getURL()+">"},mediaUrl:null,orientation:"horizontal",referrerTrack:null,services:["twitter","facebook","googleplus","info"],title:function(){return $("title").text()},twitterVia:null,url:function(){var t=global.document.location.href,e=$("link[rel=canonical]").attr("href")||this.getMeta("og:url")||"";return e.length>0&&(e.indexOf("http")<0&&(e=global.document.location.protocol+"//"+global.document.location.host+e),t=e),t}},$socialshareElement:function(){return $(this.element)},getLocalized:function(t,e){return"object"==typeof t[e]?"undefined"==typeof t[e][this.options.lang]?t[e][this.options.langFallback]:t[e][this.options.lang]:"string"==typeof t[e]?t[e]:void 0},getMeta:function(t){var e=$('meta[name="'+t+'"],[property="'+t+'"]').attr("content");return e||""},getInfoUrl:function(){return this.options.infoUrl},getURL:function(){return this.getOption("url")},getOption:function(t){var e=this.options[t];return"function"==typeof e?$.proxy(e,this)():e},getTitle:function(){return this.getOption("title")},getReferrerTrack:function(){return this.options.referrerTrack||""},getShares:function(){var t=url.parse(this.options.backendUrl,!0);return t.query.url=this.getURL(),delete t.search,$.getJSON(url.format(t))},_updateCounts:function(t){var e=this;$.each(t,function(t,r){r>=1e3&&(r=Math.round(r/1e3)+"k"),$(e.element).find("."+t+" a").append('<span class="share_count">'+r)})},_addButtonList:function(){var t=this,e=this.$socialshareElement(),r="theme-"+this.options.theme,i="orientation-"+this.options.orientation,n="col-"+this.options.services.length,a=$("<ul>").addClass(r).addClass(i).addClass(n);this.services.forEach(function(e){var r=$('<li class="shariff-button">').addClass(e.name),i='<span class="share_text">'+t.getLocalized(e,"shareText"),n=$("<a>").attr("href",e.shareUrl).append(i);"undefined"!=typeof e.faName&&n.prepend('<span class="fa '+e.faName+'">'),e.popup?n.attr("rel","popup"):e.blank&&n.attr("target","_blank"),n.attr("title",t.getLocalized(e,"title")),n.attr("role","button"),n.attr("aria-label",t.getLocalized(e,"title")),r.append(n),a.append(r)}),a.on("click",'[rel="popup"]',function(t){t.preventDefault();var e=$(this).attr("href"),r="_blank",i="600",n="460",a="width="+i+",height="+n;global.window.open(e,r,a)}),e.append(a)}},module.exports=Shariff,global.Shariff=Shariff,$(".shariff").each(function(){this.hasOwnProperty("shariff")||(this.shariff=new Shariff(this))}); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./services/facebook":7,"./services/googleplus":8,"./services/info":9,"./services/linkedin":10,"./services/mail":11,"./services/pinterest":12,"./services/twitter":13,"./services/whatsapp":14,"./services/xing":15,"jquery":6,"url":5}]},{},[16]);
src/svg-icons/av/playlist-add-check.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvPlaylistAddCheck = (props) => ( <SvgIcon {...props}> <path d="M14 10H2v2h12v-2zm0-4H2v2h12V6zM2 16h8v-2H2v2zm19.5-4.5L23 13l-6.99 7-4.51-4.5L13 14l3.01 3 5.49-5.5z"/> </SvgIcon> ); AvPlaylistAddCheck = pure(AvPlaylistAddCheck); AvPlaylistAddCheck.displayName = 'AvPlaylistAddCheck'; AvPlaylistAddCheck.muiName = 'SvgIcon'; export default AvPlaylistAddCheck;
__tests__/index.android.js
debiasej/react-native-learning
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
packages/material-ui-icons/src/AccessAlarmRounded.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M15.87 15.25l-3.37-2V8.72c0-.4-.32-.72-.72-.72h-.06c-.4 0-.72.32-.72.72v4.72c0 .35.18.68.49.86l3.65 2.19c.34.2.78.1.98-.24.21-.35.1-.8-.25-1zm5.31-10.24L18.1 2.45c-.42-.35-1.05-.3-1.41.13-.35.42-.29 1.05.13 1.41l3.07 2.56c.42.35 1.05.3 1.41-.13.36-.42.3-1.05-.12-1.41zM4.1 6.55l3.07-2.56c.43-.36.49-.99.13-1.41-.35-.43-.98-.48-1.4-.13L2.82 5.01c-.42.36-.48.99-.12 1.41.35.43.98.48 1.4.13zM12 4c-4.97 0-9 4.03-9 9s4.03 9 9 9 9-4.03 9-9-4.03-9-9-9zm0 16c-3.86 0-7-3.14-7-7s3.14-7 7-7 7 3.14 7 7-3.14 7-7 7z" /> , 'AccessAlarmRounded');
Libraries/Image/Image.ios.js
tadeuzagallo/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Image * @flow */ 'use strict'; const EdgeInsetsPropType = require('EdgeInsetsPropType'); const ImageResizeMode = require('ImageResizeMode'); const ImageSourcePropType = require('ImageSourcePropType'); const ImageStylePropTypes = require('ImageStylePropTypes'); const NativeMethodsMixin = require('NativeMethodsMixin'); const NativeModules = require('NativeModules'); const React = require('React'); const ReactNativeViewAttributes = require('ReactNativeViewAttributes'); const StyleSheet = require('StyleSheet'); const StyleSheetPropType = require('StyleSheetPropType'); const flattenStyle = require('flattenStyle'); const requireNativeComponent = require('requireNativeComponent'); const resolveAssetSource = require('resolveAssetSource'); const PropTypes = React.PropTypes; const ImageViewManager = NativeModules.ImageViewManager; /** * A React component for displaying different types of images, * including network images, static resources, temporary local images, and * images from local disk, such as the camera roll. * * This example shows both fetching and displaying an image from local * storage as well as one from network. * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, Image } from 'react-native'; * * class DisplayAnImage extends Component { * render() { * return ( * <View> * <Image * source={require('./img/favicon.png')} * /> * <Image * style={{width: 50, height: 50}} * source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} * /> * </View> * ); * } * } * * // App registration and rendering * AppRegistry.registerComponent('DisplayAnImage', () => DisplayAnImage); * ``` * * You can also add `style` to an image: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, Image, StyleSheet } from 'react-native'; * * const styles = StyleSheet.create({ * stretch: { * width: 50, * height: 200 * } * }); * * class DisplayAnImageWithStyle extends Component { * render() { * return ( * <View> * <Image * style={styles.stretch} * source={require('./img/favicon.png')} * /> * </View> * ); * } * } * * // App registration and rendering * AppRegistry.registerComponent( * 'DisplayAnImageWithStyle', * () => DisplayAnImageWithStyle * ); * ``` * * ### GIF and WebP support on Android * * By default, GIF and WebP are not supported on Android. * * You will need to add some optional modules in `android/app/build.gradle`, depending on the needs of your app. * * ``` * dependencies { * // If your app supports Android versions before Ice Cream Sandwich (API level 14) * compile 'com.facebook.fresco:animated-base-support:0.11.0' * * // For animated GIF support * compile 'com.facebook.fresco:animated-gif:0.11.0' * * // For WebP support, including animated WebP * compile 'com.facebook.fresco:animated-webp:0.11.0' * compile 'com.facebook.fresco:webpsupport:0.11.0' * * // For WebP support, without animations * compile 'com.facebook.fresco:webpsupport:0.11.0' * } * ``` * * Also, if you use GIF with ProGuard, you will need to add this rule in `proguard-rules.pro` : * ``` * -keep class com.facebook.imagepipeline.animated.factory.AnimatedFactoryImpl { * public AnimatedFactoryImpl(com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory, com.facebook.imagepipeline.core.ExecutorSupplier); * } * ``` * */ const Image = React.createClass({ propTypes: { /** * > `ImageResizeMode` is an `Enum` for different image resizing modes, set via the * > `resizeMode` style property on `Image` components. The values are `contain`, `cover`, * > `stretch`, `center`, `repeat`. */ style: StyleSheetPropType(ImageStylePropTypes), /** * The image source (either a remote URL or a local file resource). * * This prop can also contain several remote URLs, specified together with * their width and height and potentially with scale/other URI arguments. * The native side will then choose the best `uri` to display based on the * measured size of the image container. A `cache` property can be added to * control how networked request interacts with the local cache. */ source: ImageSourcePropType, /** * A static image to display while loading the image source. * * - `uri` - a string representing the resource identifier for the image, which * should be either a local file path or the name of a static image resource * (which should be wrapped in the `require('./path/to/image.png')` function). * - `width`, `height` - can be specified if known at build time, in which case * these will be used to set the default `<Image/>` component dimensions. * - `scale` - used to indicate the scale factor of the image. Defaults to 1.0 if * unspecified, meaning that one image pixel equates to one display point / DIP. * - `number` - Opaque type returned by something like `require('./image.jpg')`. * * @platform ios */ defaultSource: PropTypes.oneOfType([ // TODO: Tooling to support documenting these directly and having them display in the docs. PropTypes.shape({ uri: PropTypes.string, width: PropTypes.number, height: PropTypes.number, scale: PropTypes.number, }), PropTypes.number, ]), /** * When true, indicates the image is an accessibility element. * @platform ios */ accessible: PropTypes.bool, /** * The text that's read by the screen reader when the user interacts with * the image. * @platform ios */ accessibilityLabel: PropTypes.node, /** * blurRadius: the blur radius of the blur filter added to the image * @platform ios */ blurRadius: PropTypes.number, /** * When the image is resized, the corners of the size specified * by `capInsets` will stay a fixed size, but the center content and borders * of the image will be stretched. This is useful for creating resizable * rounded buttons, shadows, and other resizable assets. More info in the * [official Apple documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html#//apple_ref/occ/instm/UIImage/resizableImageWithCapInsets). * * @platform ios */ capInsets: EdgeInsetsPropType, /** * The mechanism that should be used to resize the image when the image's dimensions * differ from the image view's dimensions. Defaults to `auto`. * * - `auto`: Use heuristics to pick between `resize` and `scale`. * * - `resize`: A software operation which changes the encoded image in memory before it * gets decoded. This should be used instead of `scale` when the image is much larger * than the view. * * - `scale`: The image gets drawn downscaled or upscaled. Compared to `resize`, `scale` is * faster (usually hardware accelerated) and produces higher quality images. This * should be used if the image is smaller than the view. It should also be used if the * image is slightly bigger than the view. * * More details about `resize` and `scale` can be found at http://frescolib.org/docs/resizing-rotating.html. * * @platform android */ resizeMethod: PropTypes.oneOf(['auto', 'resize', 'scale']), /** * Determines how to resize the image when the frame doesn't match the raw * image dimensions. * * - `cover`: Scale the image uniformly (maintain the image's aspect ratio) * so that both dimensions (width and height) of the image will be equal * to or larger than the corresponding dimension of the view (minus padding). * * - `contain`: Scale the image uniformly (maintain the image's aspect ratio) * so that both dimensions (width and height) of the image will be equal to * or less than the corresponding dimension of the view (minus padding). * * - `stretch`: Scale width and height independently, This may change the * aspect ratio of the src. * * - `repeat`: Repeat the image to cover the frame of the view. The * image will keep it's size and aspect ratio. (iOS only) */ resizeMode: PropTypes.oneOf(['cover', 'contain', 'stretch', 'repeat', 'center']), /** * A unique identifier for this element to be used in UI Automation * testing scripts. */ testID: PropTypes.string, /** * Invoked on mount and layout changes with * `{nativeEvent: {layout: {x, y, width, height}}}`. */ onLayout: PropTypes.func, /** * Invoked on load start. * * e.g., `onLoadStart={(e) => this.setState({loading: true})}` */ onLoadStart: PropTypes.func, /** * Invoked on download progress with `{nativeEvent: {loaded, total}}`. * @platform ios */ onProgress: PropTypes.func, /** * Invoked on load error with `{nativeEvent: {error}}`. */ onError: PropTypes.func, /** * Invoked when a partial load of the image is complete. The definition of * what constitutes a "partial load" is loader specific though this is meant * for progressive JPEG loads. * @platform ios */ onPartialLoad: PropTypes.func, /** * Invoked when load completes successfully. */ onLoad: PropTypes.func, /** * Invoked when load either succeeds or fails. */ onLoadEnd: PropTypes.func, }, statics: { resizeMode: ImageResizeMode, /** * Retrieve the width and height (in pixels) of an image prior to displaying it. * This method can fail if the image cannot be found, or fails to download. * * In order to retrieve the image dimensions, the image may first need to be * loaded or downloaded, after which it will be cached. This means that in * principle you could use this method to preload images, however it is not * optimized for that purpose, and may in future be implemented in a way that * does not fully load/download the image data. A proper, supported way to * preload images will be provided as a separate API. * * @param uri The location of the image. * @param success The function that will be called if the image was successfully found and width * and height retrieved. * @param failure The function that will be called if there was an error, such as failing to * to retrieve the image. * * @returns void * * @platform ios */ getSize: function( uri: string, success: (width: number, height: number) => void, failure: (error: any) => void, ) { ImageViewManager.getSize(uri, success, failure || function() { console.warn('Failed to get size for image: ' + uri); }); }, /** * Prefetches a remote image for later use by downloading it to the disk * cache * * @param url The remote location of the image. * * @return The prefetched image. */ prefetch(url: string) { return ImageViewManager.prefetchImage(url); }, /** * Resolves an asset reference into an object which has the properties `uri`, `width`, * and `height`. The input may either be a number (opaque type returned by * require('./foo.png')) or an `ImageSource` like { uri: '<http location || file path>' } */ resolveAssetSource: resolveAssetSource, }, mixins: [NativeMethodsMixin], /** * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We * make `this` look like an actual native component class. */ viewConfig: { uiViewClassName: 'UIView', validAttributes: ReactNativeViewAttributes.UIView }, render: function() { const source = resolveAssetSource(this.props.source) || { uri: undefined, width: undefined, height: undefined }; let sources; let style; if (Array.isArray(source)) { style = flattenStyle([styles.base, this.props.style]) || {}; sources = source; } else { const {width, height, uri} = source; style = flattenStyle([{width, height}, styles.base, this.props.style]) || {}; sources = [source]; if (uri === '') { console.warn('source.uri should not be an empty string'); } } const resizeMode = this.props.resizeMode || (style || {}).resizeMode || 'cover'; // Workaround for flow bug t7737108 const tintColor = (style || {}).tintColor; // Workaround for flow bug t7737108 if (this.props.src) { console.warn('The <Image> component requires a `source` property rather than `src`.'); } return ( <RCTImageView {...this.props} style={style} resizeMode={resizeMode} tintColor={tintColor} source={sources} /> ); }, }); const styles = StyleSheet.create({ base: { overflow: 'hidden', }, }); const RCTImageView = requireNativeComponent('RCTImageView', Image); module.exports = Image;
assets/vendor/masterslider/jquery-1.10.2.min.js
ceto/cementlap
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery-1.10.2.min.map */ (function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||at.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav></:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t }({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},x.Event=function(e,n){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,x(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.inArray(e,t)>=0!==n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Ct=/^(?:checkbox|radio)$/i,Nt=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:x.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!x.support.htmlSerialize&&mt.test(e)||!x.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle); u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=un(e,t),Pt.detach()),Gt[e]=n),n}function un(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,n){x.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(x.css(e,"display"))?x.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x.support.opacity||(x.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=x.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===x.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,n){return n?x.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,n){x.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?x(e).position()[n]+"px":r):t}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!x.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||x.css(e,"display"))},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(x.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Ct.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),x.param=function(e,n){var r,i=[],o=function(e,t){t=x.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(x.isArray(t))x.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==x.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}x.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var mn,yn,vn=x.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Cn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Nn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=x.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=o.href}catch(Ln){yn=a.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(T)||[];if(x.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(l){var u;return o[l]=!0,x.each(e[l]||[],function(e,l){var c=l(n,r,i);return"string"!=typeof c||a||o[c]?a?!(u=c):t:(n.dataTypes.unshift(c),s(c),!1)}),u}return s(n.dataTypes[0])||!o["*"]&&s("*")}function _n(e,n){var r,i,o=x.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,l=e.indexOf(" ");return l>=0&&(i=e.slice(l,e.length),e=e.slice(0,l)),x.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&x.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?x("<div>").append(x.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Cn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?_n(_n(e,x.ajaxSettings),t):_n(x.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,l,u,c,p=x.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),g=x.Callbacks("once memory"),m=p.statusCode||{},y={},v={},b=0,w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||w;return u&&u.abort(t),k(0,t),this}};if(h.promise(C).complete=g.add,C.success=C.done,C.error=C.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=x.trim(p.dataType||"*").toLowerCase().match(T)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(mn[3]||("http:"===mn[1]?"80":"443")))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=x.param(p.data,p.traditional)),qn(An,p,n,C),2===b)return C;l=p.global,l&&0===x.active++&&x.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Nn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(x.lastModified[o]&&C.setRequestHeader("If-Modified-Since",x.lastModified[o]),x.etag[o]&&C.setRequestHeader("If-None-Match",x.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",p.contentType),C.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)C.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,C,p)===!1||2===b))return C.abort();w="abort";for(i in{success:1,error:1,complete:1})C[i](p[i]);if(u=qn(jn,p,n,C)){C.readyState=1,l&&d.trigger("ajaxSend",[C,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){C.abort("timeout")},p.timeout));try{b=1,u.send(y,k)}catch(N){if(!(2>b))throw N;k(-1,N)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,N=n;2!==b&&(b=2,s&&clearTimeout(s),u=t,a=i||"",C.readyState=e>0?4:0,c=e>=200&&300>e||304===e,r&&(w=Mn(p,C,r)),w=On(p,w,C,c),c?(p.ifModified&&(T=C.getResponseHeader("Last-Modified"),T&&(x.lastModified[o]=T),T=C.getResponseHeader("etag"),T&&(x.etag[o]=T)),204===e||"HEAD"===p.type?N="nocontent":304===e?N="notmodified":(N=w.state,y=w.data,v=w.error,c=!v)):(v=N,(e||!N)&&(N="error",0>e&&(e=0))),C.status=e,C.statusText=(n||N)+"",c?h.resolveWith(f,[y,N,C]):h.rejectWith(f,[C,N,v]),C.statusCode(m),m=t,l&&d.trigger(c?"ajaxSuccess":"ajaxError",[C,p,c?y:v]),g.fireWith(f,[C,N]),l&&(d.trigger("ajaxComplete",[C,p]),--x.active||x.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,n){return x.get(e,t,n,"script")}}),x.each(["get","post"],function(e,n){x[n]=function(e,r,i,o){return x.isFunction(r)&&(o=o||i,i=r,r=t),x.ajax({url:e,type:n,dataType:o,data:r,success:i})}});function Mn(e,n,r){var i,o,a,s,l=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in l)if(l[s]&&l[s].test(o)){u.unshift(s);break}if(u[0]in r)a=u[0];else{for(s in r){if(!u[0]||e.converters[s+" "+u[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==u[0]&&u.unshift(a),r[a]):t}function On(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(p){return{state:"parsererror",error:a?p:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),x.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=a.head||x("head")[0]||a.documentElement;return{send:function(t,i){n=a.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var Fn=[],Bn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Fn.pop()||x.expando+"_"+vn++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,l=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return l||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=x.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,l?n[l]=n[l].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||x.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,Fn.push(o)),s&&x.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}x.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=x.ajaxSettings.xhr(),x.support.cors=!!Rn&&"withCredentials"in Rn,Rn=x.support.ajax=!!Rn,Rn&&x.ajaxTransport(function(n){if(!n.crossDomain||x.support.cors){var r;return{send:function(i,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)l.setRequestHeader(s,i[s])}catch(u){}l.send(n.hasContent&&n.data||null),r=function(e,i){var s,u,c,p;try{if(r&&(i||4===l.readyState))if(r=t,a&&(l.onreadystatechange=x.noop,$n&&delete Pn[a]),i)4!==l.readyState&&l.abort();else{p={},s=l.status,u=l.getAllResponseHeaders(),"string"==typeof l.responseText&&(p.text=l.responseText);try{c=l.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,u)},n.async?4===l.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},x(e).unload($n)),Pn[a]=r),l.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+w+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Yn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),a=(x.cssNumber[e]||"px"!==o&&+r)&&Yn.exec(x.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,x.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=x.now()}function Zn(e,t,n){var r,i=(Qn[t]||[]).concat(Qn["*"]),o=0,a=i.length;for(;a>o;o++)if(r=i[o].call(n,t,e))return r}function er(e,t,n){var r,i,o=0,a=Gn.length,s=x.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;for(;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(tr(c,u.opts.specialEasing);a>o;o++)if(r=Gn[o].call(u,e,c,u.opts))return r;return x.map(c,Zn,u),x.isFunction(u.opts.start)&&u.opts.start.call(e,u),x.fx.timer(x.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function tr(e,t){var n,r,i,o,a;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=x.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(er,{tweener:function(e,t){x.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,l,u=this,c={},p=e.style,f=e.nodeType&&nn(e),d=x._data(e,"fxshow");n.queue||(s=x._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,u.always(function(){u.always(function(){s.unqueued--,x.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(x.support.inlineBlockNeedsLayout&&"inline"!==ln(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",x.support.shrinkWrapBlocks||u.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show"))continue;c[r]=d&&d[r]||x.style(e,r)}if(!x.isEmptyObject(c)){d?"hidden"in d&&(f=d.hidden):d=x._data(e,"fxshow",{}),o&&(d.hidden=!f),f?x(e).show():u.done(function(){x(e).hide()}),u.done(function(){var t;x._removeData(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)a=Zn(f?d[r]:0,r,u),r in d||(d[r]=a.start,f&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}x.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(x.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?x.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),x.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=x.isEmptyObject(e),o=x.speed(t,n,r),a=function(){var t=er(this,x.extend({},e),o);(i||x._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=x.timers,a=x._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=x._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,a=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}x.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=rr.prototype.init,x.fx.tick=function(){var e,n=x.timers,r=0;for(Xn=x.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||x.fx.stop(),Xn=t},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){Un||(Un=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(Un),Un=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){x.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,x.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},x.offset={setOffset:function(e,t,n){var r=x.css(e,"position");"static"===r&&(e.style.position="relative");var i=x(e),o=i.offset(),a=x.css(e,"top"),s=x.css(e,"left"),l=("absolute"===r||"fixed"===r)&&x.inArray("auto",[a,s])>-1,u={},c={},p,f;l?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),x.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(u.top=t.top-o.top+p),null!=t.left&&(u.left=t.left-o.left+f),"using"in t?t.using.call(e,u):i.css(u)}},x.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===x.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(n=e.offset()),n.top+=x.css(e[0],"borderTopWidth",!0),n.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-x.css(r,"marginTop",!0),left:t.left-n.left-x.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);x.fn[e]=function(i){return x.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?x(a).scrollLeft():o,r?o:x(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return x.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}x.each({Height:"height",Width:"width"},function(e,n){x.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){x.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return x.access(this,function(n,r,i){var o;return x.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?x.css(n,r,s):x.style(n,r,i,s)},n,a?i:t,a,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:(e.jQuery=e.$=x,"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}))})(window);
ajax/libs/yasqe/2.3.5/yasqe.bundled.min.js
pc035860/cdnjs
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.YASQE=e()}}(function(){var e;return function t(e,i,r){function n(s,a){if(!i[s]){if(!e[s]){var l="function"==typeof require&&require;if(!a&&l)return l(s,!0);if(o)return o(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var p=i[s]={exports:{}};e[s][0].call(p.exports,function(t){var i=e[s][1][t];return n(i?i:t)},p,p.exports,t,e,i,r)}return i[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)n(r[s]);return n}({1:[function(e,t){t.exports=e("./main.js")},{"./main.js":30}],2:[function(e){"use strict";var t=e("jquery");t.deparam=function(e,i){var r={},n={"true":!0,"false":!1,"null":null};t.each(e.replace(/\+/g," ").split("&"),function(e,o){var s,a=o.split("="),l=decodeURIComponent(a[0]),u=r,p=0,c=l.split("]["),d=c.length-1;if(/\[/.test(c[0])&&/\]$/.test(c[d])){c[d]=c[d].replace(/\]$/,"");c=c.shift().split("[").concat(c);d=c.length-1}else d=0;if(2===a.length){s=decodeURIComponent(a[1]);i&&(s=s&&!isNaN(s)?+s:"undefined"===s?void 0:void 0!==n[s]?n[s]:s);if(d)for(;d>=p;p++){l=""===c[p]?u.length:c[p];u=u[l]=d>p?u[l]||(c[p+1]&&isNaN(c[p+1])?{}:[]):s}else t.isArray(r[l])?r[l].push(s):r[l]=void 0!==r[l]?[r[l],s]:s}else l&&(r[l]=i?void 0:"")});return r}},{jquery:15}],3:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("codemirror")):"function"==typeof e&&e.amd?e(["codemirror"],n):n(CodeMirror)})(function(e){"use strict";e.defineMode("sparql11",function(e){function t(){var e,t,i="<[^<>\"'|{}^\\\x00- ]*>",r="[A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]",n=r+"|_",o="("+n+"|-|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])",s="("+n+"|[0-9])("+n+"|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])*",a="\\?"+s,l="\\$"+s,p="("+r+")((("+o+")|\\.)*("+o+"))?",c="[0-9A-Fa-f]",d="(%"+c+c+")",f="(\\\\[_~\\.\\-!\\$&'\\(\\)\\*\\+,;=/\\?#@%])",h="("+d+"|"+f+")";if("sparql11"==u){e="("+n+"|:|[0-9]|"+h+")(("+o+"|\\.|:|"+h+")*("+o+"|:|"+h+"))?";t="_:("+n+"|[0-9])(("+o+"|\\.)*"+o+")?"}else{e="("+n+"|[0-9])((("+o+")|\\.)*("+o+"))?";t="_:"+e}var E="("+p+")?:",m=E+e,g="@[a-zA-Z]+(-[a-zA-Z0-9]+)*",v="[eE][\\+-]?[0-9]+",x="[0-9]+",N="(([0-9]+\\.[0-9]*)|(\\.[0-9]+))",T="(([0-9]+\\.[0-9]*"+v+")|(\\.[0-9]+"+v+")|([0-9]+"+v+"))",L="\\+"+x,I="\\+"+N,y="\\+"+T,A="-"+x,S="-"+N,C="-"+T,R="\\\\[tbnrfuU\\\\\"']",b="'(([^\\x27\\x5C\\x0A\\x0D])|"+R+")*'",O='"(([^\\x22\\x5C\\x0A\\x0D])|'+R+')*"',P="'''(('|'')?([^'\\\\]|"+R+"))*'''",D='"""(("|"")?([^"\\\\]|'+R+'))*"""',w="[\\x20\\x09\\x0D\\x0A]",_="#([^\\n\\r]*[\\n\\r]|[^\\n\\r]*$)",M="("+w+"|("+_+"))*",k="\\("+M+"\\)",G="\\["+M+"\\]",B={terminal:[{name:"WS",regex:new RegExp("^"+w+"+"),style:"ws"},{name:"COMMENT",regex:new RegExp("^"+_),style:"comment"},{name:"IRI_REF",regex:new RegExp("^"+i),style:"variable-3"},{name:"VAR1",regex:new RegExp("^"+a),style:"atom"},{name:"VAR2",regex:new RegExp("^"+l),style:"atom"},{name:"LANGTAG",regex:new RegExp("^"+g),style:"meta"},{name:"DOUBLE",regex:new RegExp("^"+T),style:"number"},{name:"DECIMAL",regex:new RegExp("^"+N),style:"number"},{name:"INTEGER",regex:new RegExp("^"+x),style:"number"},{name:"DOUBLE_POSITIVE",regex:new RegExp("^"+y),style:"number"},{name:"DECIMAL_POSITIVE",regex:new RegExp("^"+I),style:"number"},{name:"INTEGER_POSITIVE",regex:new RegExp("^"+L),style:"number"},{name:"DOUBLE_NEGATIVE",regex:new RegExp("^"+C),style:"number"},{name:"DECIMAL_NEGATIVE",regex:new RegExp("^"+S),style:"number"},{name:"INTEGER_NEGATIVE",regex:new RegExp("^"+A),style:"number"},{name:"STRING_LITERAL_LONG1",regex:new RegExp("^"+P),style:"string"},{name:"STRING_LITERAL_LONG2",regex:new RegExp("^"+D),style:"string"},{name:"STRING_LITERAL1",regex:new RegExp("^"+b),style:"string"},{name:"STRING_LITERAL2",regex:new RegExp("^"+O),style:"string"},{name:"NIL",regex:new RegExp("^"+k),style:"punc"},{name:"ANON",regex:new RegExp("^"+G),style:"punc"},{name:"PNAME_LN",regex:new RegExp("^"+m),style:"string-2"},{name:"PNAME_NS",regex:new RegExp("^"+E),style:"string-2"},{name:"BLANK_NODE_LABEL",regex:new RegExp("^"+t),style:"string-2"}]};return B}function i(e){var t=[],i=o[e];if(void 0!=i)for(var r in i)t.push(r.toString());else t.push(e);return t}function r(e,t){function r(){for(var t=null,i=0;i<f.length;++i){t=e.match(f[i].regex,!0,!1);if(t)return{cat:f[i].name,style:f[i].style,text:t[0]}}t=e.match(s,!0,!1);if(t)return{cat:e.current().toUpperCase(),style:"keyword",text:t[0]};t=e.match(a,!0,!1);if(t)return{cat:e.current(),style:"punc",text:t[0]};t=e.match(/^.[A-Za-z0-9]*/,!0,!1);return{cat:"<invalid_token>",style:"error",text:t[0]}}function n(){var i=e.column();t.errorStartPos=i;t.errorEndPos=i+c.text.length}function l(e){null==t.queryType&&("SELECT"==e||"CONSTRUCT"==e||"ASK"==e||"DESCRIBE"==e||"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e)&&(t.queryType=e)}function u(e){"disallowVars"==e?t.allowVars=!1:"allowVars"==e?t.allowVars=!0:"disallowBnodes"==e?t.allowBnodes=!1:"allowBnodes"==e?t.allowBnodes=!0:"storeProperty"==e&&(t.storeProperty=!0)}function p(e){return(t.allowVars||"var"!=e)&&(t.allowBnodes||"blankNode"!=e&&"blankNodePropertyList"!=e&&"blankNodePropertyListPath"!=e)}0==e.pos&&(t.possibleCurrent=t.possibleNext);var c=r();if("<invalid_token>"==c.cat){if(1==t.OK){t.OK=!1;n()}t.complete=!1;return c.style}if("WS"==c.cat||"COMMENT"==c.cat){t.possibleCurrent=t.possibleNext;return c.style}for(var d,h=!1,E=c.cat;t.stack.length>0&&E&&t.OK&&!h;){d=t.stack.pop();if(o[d]){var m=o[d][E];if(void 0!=m&&p(d)){for(var g=m.length-1;g>=0;--g)t.stack.push(m[g]);u(d)}else{t.OK=!1;t.complete=!1;n();t.stack.push(d)}}else if(d==E){h=!0;l(d);for(var v=!0,x=t.stack.length;x>0;--x){var N=o[t.stack[x-1]];N&&N.$||(v=!1)}t.complete=v;if(t.storeProperty&&"punc"!=E.cat){t.lastProperty=c.text;t.storeProperty=!1}}else{t.OK=!1;t.complete=!1;n()}}if(!h&&t.OK){t.OK=!1;t.complete=!1;n()}t.possibleCurrent=t.possibleNext;t.possibleNext=i(t.stack[t.stack.length-1]);return c.style}function n(t,i){var r=0,n=t.stack.length-1;if(/^[\}\]\)]/.test(i)){for(var o=i.substr(0,1);n>=0;--n)if(t.stack[n]==o){--n;break}}else{var s=h[t.stack[n]];if(s){r+=s;--n}}for(;n>=0;--n){var s=E[t.stack[n]];s&&(r+=s)}return r*e.indentUnit}var o=(e.indentUnit,{"*[&&,valueLogical]":{"&&":["[&&,valueLogical]","*[&&,valueLogical]"],AS:[],")":[],",":[],"||":[],";":[]},"*[,,expression]":{",":["[,,expression]","*[,,expression]"],")":[]},"*[,,objectPath]":{",":["[,,objectPath]","*[,,objectPath]"],".":[],";":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[,,object]":{",":["[,,object]","*[,,object]"],".":[],";":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[/,pathEltOrInverse]":{"/":["[/,pathEltOrInverse]","*[/,pathEltOrInverse]"],"|":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[;,?[or([verbPath,verbSimple]),objectList]]":{";":["[;,?[or([verbPath,verbSimple]),objectList]]","*[;,?[or([verbPath,verbSimple]),objectList]]"],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[;,?[verb,objectList]]":{";":["[;,?[verb,objectList]]","*[;,?[verb,objectList]]"],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[UNION,groupGraphPattern]":{UNION:["[UNION,groupGraphPattern]","*[UNION,groupGraphPattern]"],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[graphPatternNotTriples,?.,?triplesBlock]":{"{":["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":[]},"*[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["[quadsNotTriples,?.,?triplesTemplate]","*[quadsNotTriples,?.,?triplesTemplate]"],"}":[]},"*[|,pathOneInPropertySet]":{"|":["[|,pathOneInPropertySet]","*[|,pathOneInPropertySet]"],")":[]},"*[|,pathSequence]":{"|":["[|,pathSequence]","*[|,pathSequence]"],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[||,conditionalAndExpression]":{"||":["[||,conditionalAndExpression]","*[||,conditionalAndExpression]"],AS:[],")":[],",":[],";":[]},"*dataBlockValue":{UNDEF:["dataBlockValue","*dataBlockValue"],IRI_REF:["dataBlockValue","*dataBlockValue"],TRUE:["dataBlockValue","*dataBlockValue"],FALSE:["dataBlockValue","*dataBlockValue"],PNAME_LN:["dataBlockValue","*dataBlockValue"],PNAME_NS:["dataBlockValue","*dataBlockValue"],STRING_LITERAL1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL2:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG2:["dataBlockValue","*dataBlockValue"],INTEGER:["dataBlockValue","*dataBlockValue"],DECIMAL:["dataBlockValue","*dataBlockValue"],DOUBLE:["dataBlockValue","*dataBlockValue"],INTEGER_POSITIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_POSITIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_POSITIVE:["dataBlockValue","*dataBlockValue"],INTEGER_NEGATIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_NEGATIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_NEGATIVE:["dataBlockValue","*dataBlockValue"],"}":[],")":[]},"*datasetClause":{FROM:["datasetClause","*datasetClause"],WHERE:[],"{":[]},"*describeDatasetClause":{FROM:["describeDatasetClause","*describeDatasetClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],VALUES:[],$:[]},"*graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"],")":[]},"*graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"],")":[]},"*groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"*havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"*or([[ (,*dataBlockValue,)],NIL])":{"(":["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],NIL:["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],"}":[]},"*or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],";":[]},"*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"*or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],WHERE:[],"{":[],FROM:[]},"*orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"*prefixDecl":{PREFIX:["prefixDecl","*prefixDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[]},"*usingClause":{USING:["usingClause","*usingClause"],WHERE:[]},"*var":{VAR1:["var","*var"],VAR2:["var","*var"],")":[]},"*varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],FROM:[],VALUES:[],$:[]},"+graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"]},"+graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"]},"+groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"]},"+havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"]},"+or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"]},"+orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"]},"+varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"]},"?.":{".":["."],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?DISTINCT":{DISTINCT:["DISTINCT"],"!":[],"+":[],"-":[],VAR1:[],VAR2:[],"(":[],STR:[],LANG:[],LANGMATCHES:[],DATATYPE:[],BOUND:[],IRI:[],URI:[],BNODE:[],RAND:[],ABS:[],CEIL:[],FLOOR:[],ROUND:[],CONCAT:[],STRLEN:[],UCASE:[],LCASE:[],ENCODE_FOR_URI:[],CONTAINS:[],STRSTARTS:[],STRENDS:[],STRBEFORE:[],STRAFTER:[],YEAR:[],MONTH:[],DAY:[],HOURS:[],MINUTES:[],SECONDS:[],TIMEZONE:[],TZ:[],NOW:[],UUID:[],STRUUID:[],MD5:[],SHA1:[],SHA256:[],SHA384:[],SHA512:[],COALESCE:[],IF:[],STRLANG:[],STRDT:[],SAMETERM:[],ISIRI:[],ISURI:[],ISBLANK:[],ISLITERAL:[],ISNUMERIC:[],TRUE:[],FALSE:[],COUNT:[],SUM:[],MIN:[],MAX:[],AVG:[],SAMPLE:[],GROUP_CONCAT:[],SUBSTR:[],REPLACE:[],REGEX:[],EXISTS:[],NOT:[],IRI_REF:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],PNAME_LN:[],PNAME_NS:[],"*":[]},"?GRAPH":{GRAPH:["GRAPH"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT":{SILENT:["SILENT"],VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_1":{SILENT:["SILENT"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_2":{SILENT:["SILENT"],GRAPH:[],DEFAULT:[],NAMED:[],ALL:[]},"?SILENT_3":{SILENT:["SILENT"],GRAPH:[]},"?SILENT_4":{SILENT:["SILENT"],DEFAULT:[],GRAPH:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?WHERE":{WHERE:["WHERE"],"{":[]},"?[,,expression]":{",":["[,,expression]"],")":[]},"?[.,?constructTriples]":{".":["[.,?constructTriples]"],"}":[]},"?[.,?triplesBlock]":{".":["[.,?triplesBlock]"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[.,?triplesTemplate]":{".":["[.,?triplesTemplate]"],"}":[],GRAPH:[]},"?[;,SEPARATOR,=,string]":{";":["[;,SEPARATOR,=,string]"],")":[]},"?[;,update]":{";":["[;,update]"],$:[]},"?[AS,var]":{AS:["[AS,var]"],")":[]},"?[INTO,graphRef]":{INTO:["[INTO,graphRef]"],";":[],$:[]},"?[or([verbPath,verbSimple]),objectList]":{VAR1:["[or([verbPath,verbSimple]),objectList]"],VAR2:["[or([verbPath,verbSimple]),objectList]"],"^":["[or([verbPath,verbSimple]),objectList]"],a:["[or([verbPath,verbSimple]),objectList]"],"!":["[or([verbPath,verbSimple]),objectList]"],"(":["[or([verbPath,verbSimple]),objectList]"],IRI_REF:["[or([verbPath,verbSimple]),objectList]"],PNAME_LN:["[or([verbPath,verbSimple]),objectList]"],PNAME_NS:["[or([verbPath,verbSimple]),objectList]"],";":[],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],"^":["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],IRI_REF:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_LN:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_NS:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],")":[]},"?[update1,?[;,update]]":{INSERT:["[update1,?[;,update]]"],DELETE:["[update1,?[;,update]]"],LOAD:["[update1,?[;,update]]"],CLEAR:["[update1,?[;,update]]"],DROP:["[update1,?[;,update]]"],ADD:["[update1,?[;,update]]"],MOVE:["[update1,?[;,update]]"],COPY:["[update1,?[;,update]]"],CREATE:["[update1,?[;,update]]"],WITH:["[update1,?[;,update]]"],$:[]},"?[verb,objectList]":{a:["[verb,objectList]"],VAR1:["[verb,objectList]"],VAR2:["[verb,objectList]"],IRI_REF:["[verb,objectList]"],PNAME_LN:["[verb,objectList]"],PNAME_NS:["[verb,objectList]"],";":[],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?argList":{NIL:["argList"],"(":["argList"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],"*":[],"/":[],";":[]},"?baseDecl":{BASE:["baseDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[],PREFIX:[]},"?constructTriples":{VAR1:["constructTriples"],VAR2:["constructTriples"],NIL:["constructTriples"],"(":["constructTriples"],"[":["constructTriples"],IRI_REF:["constructTriples"],TRUE:["constructTriples"],FALSE:["constructTriples"],BLANK_NODE_LABEL:["constructTriples"],ANON:["constructTriples"],PNAME_LN:["constructTriples"],PNAME_NS:["constructTriples"],STRING_LITERAL1:["constructTriples"],STRING_LITERAL2:["constructTriples"],STRING_LITERAL_LONG1:["constructTriples"],STRING_LITERAL_LONG2:["constructTriples"],INTEGER:["constructTriples"],DECIMAL:["constructTriples"],DOUBLE:["constructTriples"],INTEGER_POSITIVE:["constructTriples"],DECIMAL_POSITIVE:["constructTriples"],DOUBLE_POSITIVE:["constructTriples"],INTEGER_NEGATIVE:["constructTriples"],DECIMAL_NEGATIVE:["constructTriples"],DOUBLE_NEGATIVE:["constructTriples"],"}":[]},"?groupClause":{GROUP:["groupClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"?havingClause":{HAVING:["havingClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"?insertClause":{INSERT:["insertClause"],WHERE:[],USING:[]},"?limitClause":{LIMIT:["limitClause"],VALUES:[],$:[],"}":[]},"?limitOffsetClauses":{LIMIT:["limitOffsetClauses"],OFFSET:["limitOffsetClauses"],VALUES:[],$:[],"}":[]},"?offsetClause":{OFFSET:["offsetClause"],VALUES:[],$:[],"}":[]},"?or([DISTINCT,REDUCED])":{DISTINCT:["or([DISTINCT,REDUCED])"],REDUCED:["or([DISTINCT,REDUCED])"],"*":[],"(":[],VAR1:[],VAR2:[]},"?or([LANGTAG,[^^,iriRef]])":{LANGTAG:["or([LANGTAG,[^^,iriRef]])"],"^^":["or([LANGTAG,[^^,iriRef]])"],UNDEF:[],IRI_REF:[],TRUE:[],FALSE:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],a:[],VAR1:[],VAR2:[],"^":[],"!":[],"(":[],".":[],";":[],",":[],AS:[],")":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],"*":[],"/":[],"}":[],"[":[],NIL:[],BLANK_NODE_LABEL:[],ANON:[],"]":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])"],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"!=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IN:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AS:[],")":[],",":[],"||":[],"&&":[],";":[]},"?orderClause":{ORDER:["orderClause"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"?pathMod":{"*":["pathMod"],"?":["pathMod"],"+":["pathMod"],"{":["pathMod"],"|":[],"/":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"?triplesBlock":{VAR1:["triplesBlock"],VAR2:["triplesBlock"],NIL:["triplesBlock"],"(":["triplesBlock"],"[":["triplesBlock"],IRI_REF:["triplesBlock"],TRUE:["triplesBlock"],FALSE:["triplesBlock"],BLANK_NODE_LABEL:["triplesBlock"],ANON:["triplesBlock"],PNAME_LN:["triplesBlock"],PNAME_NS:["triplesBlock"],STRING_LITERAL1:["triplesBlock"],STRING_LITERAL2:["triplesBlock"],STRING_LITERAL_LONG1:["triplesBlock"],STRING_LITERAL_LONG2:["triplesBlock"],INTEGER:["triplesBlock"],DECIMAL:["triplesBlock"],DOUBLE:["triplesBlock"],INTEGER_POSITIVE:["triplesBlock"],DECIMAL_POSITIVE:["triplesBlock"],DOUBLE_POSITIVE:["triplesBlock"],INTEGER_NEGATIVE:["triplesBlock"],DECIMAL_NEGATIVE:["triplesBlock"],DOUBLE_NEGATIVE:["triplesBlock"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?triplesTemplate":{VAR1:["triplesTemplate"],VAR2:["triplesTemplate"],NIL:["triplesTemplate"],"(":["triplesTemplate"],"[":["triplesTemplate"],IRI_REF:["triplesTemplate"],TRUE:["triplesTemplate"],FALSE:["triplesTemplate"],BLANK_NODE_LABEL:["triplesTemplate"],ANON:["triplesTemplate"],PNAME_LN:["triplesTemplate"],PNAME_NS:["triplesTemplate"],STRING_LITERAL1:["triplesTemplate"],STRING_LITERAL2:["triplesTemplate"],STRING_LITERAL_LONG1:["triplesTemplate"],STRING_LITERAL_LONG2:["triplesTemplate"],INTEGER:["triplesTemplate"],DECIMAL:["triplesTemplate"],DOUBLE:["triplesTemplate"],INTEGER_POSITIVE:["triplesTemplate"],DECIMAL_POSITIVE:["triplesTemplate"],DOUBLE_POSITIVE:["triplesTemplate"],INTEGER_NEGATIVE:["triplesTemplate"],DECIMAL_NEGATIVE:["triplesTemplate"],DOUBLE_NEGATIVE:["triplesTemplate"],"}":[],GRAPH:[]},"?whereClause":{WHERE:["whereClause"],"{":["whereClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],VALUES:[],$:[]},"[ (,*dataBlockValue,)]":{"(":["(","*dataBlockValue",")"]},"[ (,*var,)]":{"(":["(","*var",")"]},"[ (,expression,)]":{"(":["(","expression",")"]},"[ (,expression,AS,var,)]":{"(":["(","expression","AS","var",")"]},"[!=,numericExpression]":{"!=":["!=","numericExpression"]},"[&&,valueLogical]":{"&&":["&&","valueLogical"]},"[*,unaryExpression]":{"*":["*","unaryExpression"]},"[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]":{WHERE:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"],FROM:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"]},"[+,multiplicativeExpression]":{"+":["+","multiplicativeExpression"]},"[,,expression]":{",":[",","expression"]},"[,,integer,}]":{",":[",","integer","}"]},"[,,objectPath]":{",":[",","objectPath"]},"[,,object]":{",":[",","object"]},"[,,or([},[integer,}]])]":{",":[",","or([},[integer,}]])"]},"[-,multiplicativeExpression]":{"-":["-","multiplicativeExpression"]},"[.,?constructTriples]":{".":[".","?constructTriples"]},"[.,?triplesBlock]":{".":[".","?triplesBlock"]},"[.,?triplesTemplate]":{".":[".","?triplesTemplate"]},"[/,pathEltOrInverse]":{"/":["/","pathEltOrInverse"]},"[/,unaryExpression]":{"/":["/","unaryExpression"]},"[;,?[or([verbPath,verbSimple]),objectList]]":{";":[";","?[or([verbPath,verbSimple]),objectList]"]},"[;,?[verb,objectList]]":{";":[";","?[verb,objectList]"]},"[;,SEPARATOR,=,string]":{";":[";","SEPARATOR","=","string"]},"[;,update]":{";":[";","update"]},"[<,numericExpression]":{"<":["<","numericExpression"]},"[<=,numericExpression]":{"<=":["<=","numericExpression"]},"[=,numericExpression]":{"=":["=","numericExpression"]},"[>,numericExpression]":{">":[">","numericExpression"]},"[>=,numericExpression]":{">=":[">=","numericExpression"]},"[AS,var]":{AS:["AS","var"]},"[IN,expressionList]":{IN:["IN","expressionList"]},"[INTO,graphRef]":{INTO:["INTO","graphRef"]},"[NAMED,iriRef]":{NAMED:["NAMED","iriRef"]},"[NOT,IN,expressionList]":{NOT:["NOT","IN","expressionList"]},"[UNION,groupGraphPattern]":{UNION:["UNION","groupGraphPattern"]},"[^^,iriRef]":{"^^":["^^","iriRef"]},"[constructTemplate,*datasetClause,whereClause,solutionModifier]":{"{":["constructTemplate","*datasetClause","whereClause","solutionModifier"]},"[deleteClause,?insertClause]":{DELETE:["deleteClause","?insertClause"]},"[graphPatternNotTriples,?.,?triplesBlock]":{"{":["graphPatternNotTriples","?.","?triplesBlock"],OPTIONAL:["graphPatternNotTriples","?.","?triplesBlock"],MINUS:["graphPatternNotTriples","?.","?triplesBlock"],GRAPH:["graphPatternNotTriples","?.","?triplesBlock"],SERVICE:["graphPatternNotTriples","?.","?triplesBlock"],FILTER:["graphPatternNotTriples","?.","?triplesBlock"],BIND:["graphPatternNotTriples","?.","?triplesBlock"],VALUES:["graphPatternNotTriples","?.","?triplesBlock"]},"[integer,or([[,,or([},[integer,}]])],}])]":{INTEGER:["integer","or([[,,or([},[integer,}]])],}])"]},"[integer,}]":{INTEGER:["integer","}"]},"[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]":{INTEGER_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"]},"[or([verbPath,verbSimple]),objectList]":{VAR1:["or([verbPath,verbSimple])","objectList"],VAR2:["or([verbPath,verbSimple])","objectList"],"^":["or([verbPath,verbSimple])","objectList"],a:["or([verbPath,verbSimple])","objectList"],"!":["or([verbPath,verbSimple])","objectList"],"(":["or([verbPath,verbSimple])","objectList"],IRI_REF:["or([verbPath,verbSimple])","objectList"],PNAME_LN:["or([verbPath,verbSimple])","objectList"],PNAME_NS:["or([verbPath,verbSimple])","objectList"]},"[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],"^":["pathOneInPropertySet","*[|,pathOneInPropertySet]"],IRI_REF:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_LN:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_NS:["pathOneInPropertySet","*[|,pathOneInPropertySet]"]},"[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["quadsNotTriples","?.","?triplesTemplate"]},"[update1,?[;,update]]":{INSERT:["update1","?[;,update]"],DELETE:["update1","?[;,update]"],LOAD:["update1","?[;,update]"],CLEAR:["update1","?[;,update]"],DROP:["update1","?[;,update]"],ADD:["update1","?[;,update]"],MOVE:["update1","?[;,update]"],COPY:["update1","?[;,update]"],CREATE:["update1","?[;,update]"],WITH:["update1","?[;,update]"]},"[verb,objectList]":{a:["verb","objectList"],VAR1:["verb","objectList"],VAR2:["verb","objectList"],IRI_REF:["verb","objectList"],PNAME_LN:["verb","objectList"],PNAME_NS:["verb","objectList"]},"[|,pathOneInPropertySet]":{"|":["|","pathOneInPropertySet"]},"[|,pathSequence]":{"|":["|","pathSequence"]},"[||,conditionalAndExpression]":{"||":["||","conditionalAndExpression"]},add:{ADD:["ADD","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},additiveExpression:{"!":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"+":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"(":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANGMATCHES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DATATYPE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BOUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BNODE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],RAND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ABS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CEIL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FLOOR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ROUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLEN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ENCODE_FOR_URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONTAINS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRSTARTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRENDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRBEFORE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRAFTER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],YEAR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MONTH:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DAY:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],HOURS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MINUTES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SECONDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TIMEZONE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TZ:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOW:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRUUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MD5:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA256:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA384:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA512:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COALESCE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRDT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMETERM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISIRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISURI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISBLANK:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISLITERAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISNUMERIC:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TRUE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FALSE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COUNT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MIN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MAX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AVG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMPLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],GROUP_CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUBSTR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REPLACE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REGEX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],EXISTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI_REF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_LN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_NS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"]},aggregate:{COUNT:["COUNT","(","?DISTINCT","or([*,expression])",")"],SUM:["SUM","(","?DISTINCT","expression",")"],MIN:["MIN","(","?DISTINCT","expression",")"],MAX:["MAX","(","?DISTINCT","expression",")"],AVG:["AVG","(","?DISTINCT","expression",")"],SAMPLE:["SAMPLE","(","?DISTINCT","expression",")"],GROUP_CONCAT:["GROUP_CONCAT","(","?DISTINCT","expression","?[;,SEPARATOR,=,string]",")"]},allowBnodes:{"}":[]},allowVars:{"}":[]},argList:{NIL:["NIL"],"(":["(","?DISTINCT","expression","*[,,expression]",")"]},askQuery:{ASK:["ASK","*datasetClause","whereClause","solutionModifier"]},baseDecl:{BASE:["BASE","IRI_REF"]},bind:{BIND:["BIND","(","expression","AS","var",")"]},blankNode:{BLANK_NODE_LABEL:["BLANK_NODE_LABEL"],ANON:["ANON"]},blankNodePropertyList:{"[":["[","propertyListNotEmpty","]"]},blankNodePropertyListPath:{"[":["[","propertyListPathNotEmpty","]"]},booleanLiteral:{TRUE:["TRUE"],FALSE:["FALSE"]},brackettedExpression:{"(":["(","expression",")"]},builtInCall:{STR:["STR","(","expression",")"],LANG:["LANG","(","expression",")"],LANGMATCHES:["LANGMATCHES","(","expression",",","expression",")"],DATATYPE:["DATATYPE","(","expression",")"],BOUND:["BOUND","(","var",")"],IRI:["IRI","(","expression",")"],URI:["URI","(","expression",")"],BNODE:["BNODE","or([[ (,expression,)],NIL])"],RAND:["RAND","NIL"],ABS:["ABS","(","expression",")"],CEIL:["CEIL","(","expression",")"],FLOOR:["FLOOR","(","expression",")"],ROUND:["ROUND","(","expression",")"],CONCAT:["CONCAT","expressionList"],SUBSTR:["substringExpression"],STRLEN:["STRLEN","(","expression",")"],REPLACE:["strReplaceExpression"],UCASE:["UCASE","(","expression",")"],LCASE:["LCASE","(","expression",")"],ENCODE_FOR_URI:["ENCODE_FOR_URI","(","expression",")"],CONTAINS:["CONTAINS","(","expression",",","expression",")"],STRSTARTS:["STRSTARTS","(","expression",",","expression",")"],STRENDS:["STRENDS","(","expression",",","expression",")"],STRBEFORE:["STRBEFORE","(","expression",",","expression",")"],STRAFTER:["STRAFTER","(","expression",",","expression",")"],YEAR:["YEAR","(","expression",")"],MONTH:["MONTH","(","expression",")"],DAY:["DAY","(","expression",")"],HOURS:["HOURS","(","expression",")"],MINUTES:["MINUTES","(","expression",")"],SECONDS:["SECONDS","(","expression",")"],TIMEZONE:["TIMEZONE","(","expression",")"],TZ:["TZ","(","expression",")"],NOW:["NOW","NIL"],UUID:["UUID","NIL"],STRUUID:["STRUUID","NIL"],MD5:["MD5","(","expression",")"],SHA1:["SHA1","(","expression",")"],SHA256:["SHA256","(","expression",")"],SHA384:["SHA384","(","expression",")"],SHA512:["SHA512","(","expression",")"],COALESCE:["COALESCE","expressionList"],IF:["IF","(","expression",",","expression",",","expression",")"],STRLANG:["STRLANG","(","expression",",","expression",")"],STRDT:["STRDT","(","expression",",","expression",")"],SAMETERM:["SAMETERM","(","expression",",","expression",")"],ISIRI:["ISIRI","(","expression",")"],ISURI:["ISURI","(","expression",")"],ISBLANK:["ISBLANK","(","expression",")"],ISLITERAL:["ISLITERAL","(","expression",")"],ISNUMERIC:["ISNUMERIC","(","expression",")"],REGEX:["regexExpression"],EXISTS:["existsFunc"],NOT:["notExistsFunc"]},clear:{CLEAR:["CLEAR","?SILENT_2","graphRefAll"]},collection:{"(":["(","+graphNode",")"]},collectionPath:{"(":["(","+graphNodePath",")"]},conditionalAndExpression:{"!":["valueLogical","*[&&,valueLogical]"],"+":["valueLogical","*[&&,valueLogical]"],"-":["valueLogical","*[&&,valueLogical]"],VAR1:["valueLogical","*[&&,valueLogical]"],VAR2:["valueLogical","*[&&,valueLogical]"],"(":["valueLogical","*[&&,valueLogical]"],STR:["valueLogical","*[&&,valueLogical]"],LANG:["valueLogical","*[&&,valueLogical]"],LANGMATCHES:["valueLogical","*[&&,valueLogical]"],DATATYPE:["valueLogical","*[&&,valueLogical]"],BOUND:["valueLogical","*[&&,valueLogical]"],IRI:["valueLogical","*[&&,valueLogical]"],URI:["valueLogical","*[&&,valueLogical]"],BNODE:["valueLogical","*[&&,valueLogical]"],RAND:["valueLogical","*[&&,valueLogical]"],ABS:["valueLogical","*[&&,valueLogical]"],CEIL:["valueLogical","*[&&,valueLogical]"],FLOOR:["valueLogical","*[&&,valueLogical]"],ROUND:["valueLogical","*[&&,valueLogical]"],CONCAT:["valueLogical","*[&&,valueLogical]"],STRLEN:["valueLogical","*[&&,valueLogical]"],UCASE:["valueLogical","*[&&,valueLogical]"],LCASE:["valueLogical","*[&&,valueLogical]"],ENCODE_FOR_URI:["valueLogical","*[&&,valueLogical]"],CONTAINS:["valueLogical","*[&&,valueLogical]"],STRSTARTS:["valueLogical","*[&&,valueLogical]"],STRENDS:["valueLogical","*[&&,valueLogical]"],STRBEFORE:["valueLogical","*[&&,valueLogical]"],STRAFTER:["valueLogical","*[&&,valueLogical]"],YEAR:["valueLogical","*[&&,valueLogical]"],MONTH:["valueLogical","*[&&,valueLogical]"],DAY:["valueLogical","*[&&,valueLogical]"],HOURS:["valueLogical","*[&&,valueLogical]"],MINUTES:["valueLogical","*[&&,valueLogical]"],SECONDS:["valueLogical","*[&&,valueLogical]"],TIMEZONE:["valueLogical","*[&&,valueLogical]"],TZ:["valueLogical","*[&&,valueLogical]"],NOW:["valueLogical","*[&&,valueLogical]"],UUID:["valueLogical","*[&&,valueLogical]"],STRUUID:["valueLogical","*[&&,valueLogical]"],MD5:["valueLogical","*[&&,valueLogical]"],SHA1:["valueLogical","*[&&,valueLogical]"],SHA256:["valueLogical","*[&&,valueLogical]"],SHA384:["valueLogical","*[&&,valueLogical]"],SHA512:["valueLogical","*[&&,valueLogical]"],COALESCE:["valueLogical","*[&&,valueLogical]"],IF:["valueLogical","*[&&,valueLogical]"],STRLANG:["valueLogical","*[&&,valueLogical]"],STRDT:["valueLogical","*[&&,valueLogical]"],SAMETERM:["valueLogical","*[&&,valueLogical]"],ISIRI:["valueLogical","*[&&,valueLogical]"],ISURI:["valueLogical","*[&&,valueLogical]"],ISBLANK:["valueLogical","*[&&,valueLogical]"],ISLITERAL:["valueLogical","*[&&,valueLogical]"],ISNUMERIC:["valueLogical","*[&&,valueLogical]"],TRUE:["valueLogical","*[&&,valueLogical]"],FALSE:["valueLogical","*[&&,valueLogical]"],COUNT:["valueLogical","*[&&,valueLogical]"],SUM:["valueLogical","*[&&,valueLogical]"],MIN:["valueLogical","*[&&,valueLogical]"],MAX:["valueLogical","*[&&,valueLogical]"],AVG:["valueLogical","*[&&,valueLogical]"],SAMPLE:["valueLogical","*[&&,valueLogical]"],GROUP_CONCAT:["valueLogical","*[&&,valueLogical]"],SUBSTR:["valueLogical","*[&&,valueLogical]"],REPLACE:["valueLogical","*[&&,valueLogical]"],REGEX:["valueLogical","*[&&,valueLogical]"],EXISTS:["valueLogical","*[&&,valueLogical]"],NOT:["valueLogical","*[&&,valueLogical]"],IRI_REF:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL2:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG2:["valueLogical","*[&&,valueLogical]"],INTEGER:["valueLogical","*[&&,valueLogical]"],DECIMAL:["valueLogical","*[&&,valueLogical]"],DOUBLE:["valueLogical","*[&&,valueLogical]"],INTEGER_POSITIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_POSITIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_POSITIVE:["valueLogical","*[&&,valueLogical]"],INTEGER_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_NEGATIVE:["valueLogical","*[&&,valueLogical]"],PNAME_LN:["valueLogical","*[&&,valueLogical]"],PNAME_NS:["valueLogical","*[&&,valueLogical]"]},conditionalOrExpression:{"!":["conditionalAndExpression","*[||,conditionalAndExpression]"],"+":["conditionalAndExpression","*[||,conditionalAndExpression]"],"-":["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR1:["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR2:["conditionalAndExpression","*[||,conditionalAndExpression]"],"(":["conditionalAndExpression","*[||,conditionalAndExpression]"],STR:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANGMATCHES:["conditionalAndExpression","*[||,conditionalAndExpression]"],DATATYPE:["conditionalAndExpression","*[||,conditionalAndExpression]"],BOUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],BNODE:["conditionalAndExpression","*[||,conditionalAndExpression]"],RAND:["conditionalAndExpression","*[||,conditionalAndExpression]"],ABS:["conditionalAndExpression","*[||,conditionalAndExpression]"],CEIL:["conditionalAndExpression","*[||,conditionalAndExpression]"],FLOOR:["conditionalAndExpression","*[||,conditionalAndExpression]"],ROUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLEN:["conditionalAndExpression","*[||,conditionalAndExpression]"],UCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],LCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],ENCODE_FOR_URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONTAINS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRSTARTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRENDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRBEFORE:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRAFTER:["conditionalAndExpression","*[||,conditionalAndExpression]"],YEAR:["conditionalAndExpression","*[||,conditionalAndExpression]"],MONTH:["conditionalAndExpression","*[||,conditionalAndExpression]"],DAY:["conditionalAndExpression","*[||,conditionalAndExpression]"],HOURS:["conditionalAndExpression","*[||,conditionalAndExpression]"],MINUTES:["conditionalAndExpression","*[||,conditionalAndExpression]"],SECONDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],TIMEZONE:["conditionalAndExpression","*[||,conditionalAndExpression]"],TZ:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOW:["conditionalAndExpression","*[||,conditionalAndExpression]"],UUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRUUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],MD5:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA1:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA256:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA384:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA512:["conditionalAndExpression","*[||,conditionalAndExpression]"],COALESCE:["conditionalAndExpression","*[||,conditionalAndExpression]"],IF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRDT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMETERM:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISIRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISURI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISBLANK:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISLITERAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISNUMERIC:["conditionalAndExpression","*[||,conditionalAndExpression]"],TRUE:["conditionalAndExpression","*[||,conditionalAndExpression]"],FALSE:["conditionalAndExpression","*[||,conditionalAndExpression]"],COUNT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUM:["conditionalAndExpression","*[||,conditionalAndExpression]"],MIN:["conditionalAndExpression","*[||,conditionalAndExpression]"],MAX:["conditionalAndExpression","*[||,conditionalAndExpression]"],AVG:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMPLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],GROUP_CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUBSTR:["conditionalAndExpression","*[||,conditionalAndExpression]"],REPLACE:["conditionalAndExpression","*[||,conditionalAndExpression]"],REGEX:["conditionalAndExpression","*[||,conditionalAndExpression]"],EXISTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOT:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI_REF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL2:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG2:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_LN:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_NS:["conditionalAndExpression","*[||,conditionalAndExpression]"]},constraint:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"]},constructQuery:{CONSTRUCT:["CONSTRUCT","or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])"]},constructTemplate:{"{":["{","?constructTriples","}"]},constructTriples:{VAR1:["triplesSameSubject","?[.,?constructTriples]"],VAR2:["triplesSameSubject","?[.,?constructTriples]"],NIL:["triplesSameSubject","?[.,?constructTriples]"],"(":["triplesSameSubject","?[.,?constructTriples]"],"[":["triplesSameSubject","?[.,?constructTriples]"],IRI_REF:["triplesSameSubject","?[.,?constructTriples]"],TRUE:["triplesSameSubject","?[.,?constructTriples]"],FALSE:["triplesSameSubject","?[.,?constructTriples]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?constructTriples]"],ANON:["triplesSameSubject","?[.,?constructTriples]"],PNAME_LN:["triplesSameSubject","?[.,?constructTriples]"],PNAME_NS:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL2:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?constructTriples]"],INTEGER:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"]},copy:{COPY:["COPY","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},create:{CREATE:["CREATE","?SILENT_3","graphRef"]},dataBlock:{NIL:["or([inlineDataOneVar,inlineDataFull])"],"(":["or([inlineDataOneVar,inlineDataFull])"],VAR1:["or([inlineDataOneVar,inlineDataFull])"],VAR2:["or([inlineDataOneVar,inlineDataFull])"]},dataBlockValue:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],UNDEF:["UNDEF"]},datasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},defaultGraphClause:{IRI_REF:["sourceSelector"],PNAME_LN:["sourceSelector"],PNAME_NS:["sourceSelector"]},delete1:{DATA:["DATA","quadDataNoBnodes"],WHERE:["WHERE","quadPatternNoBnodes"],"{":["quadPatternNoBnodes","?insertClause","*usingClause","WHERE","groupGraphPattern"]},deleteClause:{DELETE:["DELETE","quadPattern"]},describeDatasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},describeQuery:{DESCRIBE:["DESCRIBE","or([+varOrIRIref,*])","*describeDatasetClause","?whereClause","solutionModifier"]},disallowBnodes:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},disallowVars:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},drop:{DROP:["DROP","?SILENT_2","graphRefAll"]},existsFunc:{EXISTS:["EXISTS","groupGraphPattern"]},expression:{"!":["conditionalOrExpression"],"+":["conditionalOrExpression"],"-":["conditionalOrExpression"],VAR1:["conditionalOrExpression"],VAR2:["conditionalOrExpression"],"(":["conditionalOrExpression"],STR:["conditionalOrExpression"],LANG:["conditionalOrExpression"],LANGMATCHES:["conditionalOrExpression"],DATATYPE:["conditionalOrExpression"],BOUND:["conditionalOrExpression"],IRI:["conditionalOrExpression"],URI:["conditionalOrExpression"],BNODE:["conditionalOrExpression"],RAND:["conditionalOrExpression"],ABS:["conditionalOrExpression"],CEIL:["conditionalOrExpression"],FLOOR:["conditionalOrExpression"],ROUND:["conditionalOrExpression"],CONCAT:["conditionalOrExpression"],STRLEN:["conditionalOrExpression"],UCASE:["conditionalOrExpression"],LCASE:["conditionalOrExpression"],ENCODE_FOR_URI:["conditionalOrExpression"],CONTAINS:["conditionalOrExpression"],STRSTARTS:["conditionalOrExpression"],STRENDS:["conditionalOrExpression"],STRBEFORE:["conditionalOrExpression"],STRAFTER:["conditionalOrExpression"],YEAR:["conditionalOrExpression"],MONTH:["conditionalOrExpression"],DAY:["conditionalOrExpression"],HOURS:["conditionalOrExpression"],MINUTES:["conditionalOrExpression"],SECONDS:["conditionalOrExpression"],TIMEZONE:["conditionalOrExpression"],TZ:["conditionalOrExpression"],NOW:["conditionalOrExpression"],UUID:["conditionalOrExpression"],STRUUID:["conditionalOrExpression"],MD5:["conditionalOrExpression"],SHA1:["conditionalOrExpression"],SHA256:["conditionalOrExpression"],SHA384:["conditionalOrExpression"],SHA512:["conditionalOrExpression"],COALESCE:["conditionalOrExpression"],IF:["conditionalOrExpression"],STRLANG:["conditionalOrExpression"],STRDT:["conditionalOrExpression"],SAMETERM:["conditionalOrExpression"],ISIRI:["conditionalOrExpression"],ISURI:["conditionalOrExpression"],ISBLANK:["conditionalOrExpression"],ISLITERAL:["conditionalOrExpression"],ISNUMERIC:["conditionalOrExpression"],TRUE:["conditionalOrExpression"],FALSE:["conditionalOrExpression"],COUNT:["conditionalOrExpression"],SUM:["conditionalOrExpression"],MIN:["conditionalOrExpression"],MAX:["conditionalOrExpression"],AVG:["conditionalOrExpression"],SAMPLE:["conditionalOrExpression"],GROUP_CONCAT:["conditionalOrExpression"],SUBSTR:["conditionalOrExpression"],REPLACE:["conditionalOrExpression"],REGEX:["conditionalOrExpression"],EXISTS:["conditionalOrExpression"],NOT:["conditionalOrExpression"],IRI_REF:["conditionalOrExpression"],STRING_LITERAL1:["conditionalOrExpression"],STRING_LITERAL2:["conditionalOrExpression"],STRING_LITERAL_LONG1:["conditionalOrExpression"],STRING_LITERAL_LONG2:["conditionalOrExpression"],INTEGER:["conditionalOrExpression"],DECIMAL:["conditionalOrExpression"],DOUBLE:["conditionalOrExpression"],INTEGER_POSITIVE:["conditionalOrExpression"],DECIMAL_POSITIVE:["conditionalOrExpression"],DOUBLE_POSITIVE:["conditionalOrExpression"],INTEGER_NEGATIVE:["conditionalOrExpression"],DECIMAL_NEGATIVE:["conditionalOrExpression"],DOUBLE_NEGATIVE:["conditionalOrExpression"],PNAME_LN:["conditionalOrExpression"],PNAME_NS:["conditionalOrExpression"]},expressionList:{NIL:["NIL"],"(":["(","expression","*[,,expression]",")"]},filter:{FILTER:["FILTER","constraint"]},functionCall:{IRI_REF:["iriRef","argList"],PNAME_LN:["iriRef","argList"],PNAME_NS:["iriRef","argList"]},graphGraphPattern:{GRAPH:["GRAPH","varOrIRIref","groupGraphPattern"]},graphNode:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNode"],"[":["triplesNode"]},graphNodePath:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNodePath"],"[":["triplesNodePath"]},graphOrDefault:{DEFAULT:["DEFAULT"],IRI_REF:["?GRAPH","iriRef"],PNAME_LN:["?GRAPH","iriRef"],PNAME_NS:["?GRAPH","iriRef"],GRAPH:["?GRAPH","iriRef"]},graphPatternNotTriples:{"{":["groupOrUnionGraphPattern"],OPTIONAL:["optionalGraphPattern"],MINUS:["minusGraphPattern"],GRAPH:["graphGraphPattern"],SERVICE:["serviceGraphPattern"],FILTER:["filter"],BIND:["bind"],VALUES:["inlineData"]},graphRef:{GRAPH:["GRAPH","iriRef"]},graphRefAll:{GRAPH:["graphRef"],DEFAULT:["DEFAULT"],NAMED:["NAMED"],ALL:["ALL"]},graphTerm:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],BLANK_NODE_LABEL:["blankNode"],ANON:["blankNode"],NIL:["NIL"]},groupClause:{GROUP:["GROUP","BY","+groupCondition"]},groupCondition:{STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"],"(":["(","expression","?[AS,var]",")"],VAR1:["var"],VAR2:["var"]},groupGraphPattern:{"{":["{","or([subSelect,groupGraphPatternSub])","}"]},groupGraphPatternSub:{"{":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],NIL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"(":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"[":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],IRI_REF:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],TRUE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FALSE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BLANK_NODE_LABEL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],ANON:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_LN:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_NS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"]},groupOrUnionGraphPattern:{"{":["groupGraphPattern","*[UNION,groupGraphPattern]"]},havingClause:{HAVING:["HAVING","+havingCondition"]},havingCondition:{"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"]},inlineData:{VALUES:["VALUES","dataBlock"]},inlineDataFull:{NIL:["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"],"(":["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"]},inlineDataOneVar:{VAR1:["var","{","*dataBlockValue","}"],VAR2:["var","{","*dataBlockValue","}"]},insert1:{DATA:["DATA","quadData"],"{":["quadPattern","*usingClause","WHERE","groupGraphPattern"]},insertClause:{INSERT:["INSERT","quadPattern"]},integer:{INTEGER:["INTEGER"]},iriRef:{IRI_REF:["IRI_REF"],PNAME_LN:["prefixedName"],PNAME_NS:["prefixedName"]},iriRefOrFunction:{IRI_REF:["iriRef","?argList"],PNAME_LN:["iriRef","?argList"],PNAME_NS:["iriRef","?argList"]},limitClause:{LIMIT:["LIMIT","INTEGER"]},limitOffsetClauses:{LIMIT:["limitClause","?offsetClause"],OFFSET:["offsetClause","?limitClause"]},load:{LOAD:["LOAD","?SILENT_1","iriRef","?[INTO,graphRef]"]},minusGraphPattern:{MINUS:["MINUS","groupGraphPattern"]},modify:{WITH:["WITH","iriRef","or([[deleteClause,?insertClause],insertClause])","*usingClause","WHERE","groupGraphPattern"]},move:{MOVE:["MOVE","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},multiplicativeExpression:{"!":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"+":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"-":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"(":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANGMATCHES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DATATYPE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BOUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BNODE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],RAND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ABS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CEIL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FLOOR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ROUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLEN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ENCODE_FOR_URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONTAINS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRSTARTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRENDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRBEFORE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRAFTER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],YEAR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MONTH:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DAY:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],HOURS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MINUTES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SECONDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TIMEZONE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TZ:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOW:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRUUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MD5:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA256:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA384:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA512:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COALESCE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRDT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMETERM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISIRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISURI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISBLANK:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISLITERAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISNUMERIC:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TRUE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FALSE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COUNT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MIN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MAX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],AVG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMPLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],GROUP_CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUBSTR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REPLACE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REGEX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],EXISTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI_REF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_LN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_NS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"]},namedGraphClause:{NAMED:["NAMED","sourceSelector"]},notExistsFunc:{NOT:["NOT","EXISTS","groupGraphPattern"]},numericExpression:{"!":["additiveExpression"],"+":["additiveExpression"],"-":["additiveExpression"],VAR1:["additiveExpression"],VAR2:["additiveExpression"],"(":["additiveExpression"],STR:["additiveExpression"],LANG:["additiveExpression"],LANGMATCHES:["additiveExpression"],DATATYPE:["additiveExpression"],BOUND:["additiveExpression"],IRI:["additiveExpression"],URI:["additiveExpression"],BNODE:["additiveExpression"],RAND:["additiveExpression"],ABS:["additiveExpression"],CEIL:["additiveExpression"],FLOOR:["additiveExpression"],ROUND:["additiveExpression"],CONCAT:["additiveExpression"],STRLEN:["additiveExpression"],UCASE:["additiveExpression"],LCASE:["additiveExpression"],ENCODE_FOR_URI:["additiveExpression"],CONTAINS:["additiveExpression"],STRSTARTS:["additiveExpression"],STRENDS:["additiveExpression"],STRBEFORE:["additiveExpression"],STRAFTER:["additiveExpression"],YEAR:["additiveExpression"],MONTH:["additiveExpression"],DAY:["additiveExpression"],HOURS:["additiveExpression"],MINUTES:["additiveExpression"],SECONDS:["additiveExpression"],TIMEZONE:["additiveExpression"],TZ:["additiveExpression"],NOW:["additiveExpression"],UUID:["additiveExpression"],STRUUID:["additiveExpression"],MD5:["additiveExpression"],SHA1:["additiveExpression"],SHA256:["additiveExpression"],SHA384:["additiveExpression"],SHA512:["additiveExpression"],COALESCE:["additiveExpression"],IF:["additiveExpression"],STRLANG:["additiveExpression"],STRDT:["additiveExpression"],SAMETERM:["additiveExpression"],ISIRI:["additiveExpression"],ISURI:["additiveExpression"],ISBLANK:["additiveExpression"],ISLITERAL:["additiveExpression"],ISNUMERIC:["additiveExpression"],TRUE:["additiveExpression"],FALSE:["additiveExpression"],COUNT:["additiveExpression"],SUM:["additiveExpression"],MIN:["additiveExpression"],MAX:["additiveExpression"],AVG:["additiveExpression"],SAMPLE:["additiveExpression"],GROUP_CONCAT:["additiveExpression"],SUBSTR:["additiveExpression"],REPLACE:["additiveExpression"],REGEX:["additiveExpression"],EXISTS:["additiveExpression"],NOT:["additiveExpression"],IRI_REF:["additiveExpression"],STRING_LITERAL1:["additiveExpression"],STRING_LITERAL2:["additiveExpression"],STRING_LITERAL_LONG1:["additiveExpression"],STRING_LITERAL_LONG2:["additiveExpression"],INTEGER:["additiveExpression"],DECIMAL:["additiveExpression"],DOUBLE:["additiveExpression"],INTEGER_POSITIVE:["additiveExpression"],DECIMAL_POSITIVE:["additiveExpression"],DOUBLE_POSITIVE:["additiveExpression"],INTEGER_NEGATIVE:["additiveExpression"],DECIMAL_NEGATIVE:["additiveExpression"],DOUBLE_NEGATIVE:["additiveExpression"],PNAME_LN:["additiveExpression"],PNAME_NS:["additiveExpression"]},numericLiteral:{INTEGER:["numericLiteralUnsigned"],DECIMAL:["numericLiteralUnsigned"],DOUBLE:["numericLiteralUnsigned"],INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},numericLiteralNegative:{INTEGER_NEGATIVE:["INTEGER_NEGATIVE"],DECIMAL_NEGATIVE:["DECIMAL_NEGATIVE"],DOUBLE_NEGATIVE:["DOUBLE_NEGATIVE"]},numericLiteralPositive:{INTEGER_POSITIVE:["INTEGER_POSITIVE"],DECIMAL_POSITIVE:["DECIMAL_POSITIVE"],DOUBLE_POSITIVE:["DOUBLE_POSITIVE"]},numericLiteralUnsigned:{INTEGER:["INTEGER"],DECIMAL:["DECIMAL"],DOUBLE:["DOUBLE"]},object:{"(":["graphNode"],"[":["graphNode"],VAR1:["graphNode"],VAR2:["graphNode"],NIL:["graphNode"],IRI_REF:["graphNode"],TRUE:["graphNode"],FALSE:["graphNode"],BLANK_NODE_LABEL:["graphNode"],ANON:["graphNode"],PNAME_LN:["graphNode"],PNAME_NS:["graphNode"],STRING_LITERAL1:["graphNode"],STRING_LITERAL2:["graphNode"],STRING_LITERAL_LONG1:["graphNode"],STRING_LITERAL_LONG2:["graphNode"],INTEGER:["graphNode"],DECIMAL:["graphNode"],DOUBLE:["graphNode"],INTEGER_POSITIVE:["graphNode"],DECIMAL_POSITIVE:["graphNode"],DOUBLE_POSITIVE:["graphNode"],INTEGER_NEGATIVE:["graphNode"],DECIMAL_NEGATIVE:["graphNode"],DOUBLE_NEGATIVE:["graphNode"]},objectList:{"(":["object","*[,,object]"],"[":["object","*[,,object]"],VAR1:["object","*[,,object]"],VAR2:["object","*[,,object]"],NIL:["object","*[,,object]"],IRI_REF:["object","*[,,object]"],TRUE:["object","*[,,object]"],FALSE:["object","*[,,object]"],BLANK_NODE_LABEL:["object","*[,,object]"],ANON:["object","*[,,object]"],PNAME_LN:["object","*[,,object]"],PNAME_NS:["object","*[,,object]"],STRING_LITERAL1:["object","*[,,object]"],STRING_LITERAL2:["object","*[,,object]"],STRING_LITERAL_LONG1:["object","*[,,object]"],STRING_LITERAL_LONG2:["object","*[,,object]"],INTEGER:["object","*[,,object]"],DECIMAL:["object","*[,,object]"],DOUBLE:["object","*[,,object]"],INTEGER_POSITIVE:["object","*[,,object]"],DECIMAL_POSITIVE:["object","*[,,object]"],DOUBLE_POSITIVE:["object","*[,,object]"],INTEGER_NEGATIVE:["object","*[,,object]"],DECIMAL_NEGATIVE:["object","*[,,object]"],DOUBLE_NEGATIVE:["object","*[,,object]"]},objectListPath:{"(":["objectPath","*[,,objectPath]"],"[":["objectPath","*[,,objectPath]"],VAR1:["objectPath","*[,,objectPath]"],VAR2:["objectPath","*[,,objectPath]"],NIL:["objectPath","*[,,objectPath]"],IRI_REF:["objectPath","*[,,objectPath]"],TRUE:["objectPath","*[,,objectPath]"],FALSE:["objectPath","*[,,objectPath]"],BLANK_NODE_LABEL:["objectPath","*[,,objectPath]"],ANON:["objectPath","*[,,objectPath]"],PNAME_LN:["objectPath","*[,,objectPath]"],PNAME_NS:["objectPath","*[,,objectPath]"],STRING_LITERAL1:["objectPath","*[,,objectPath]"],STRING_LITERAL2:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG1:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG2:["objectPath","*[,,objectPath]"],INTEGER:["objectPath","*[,,objectPath]"],DECIMAL:["objectPath","*[,,objectPath]"],DOUBLE:["objectPath","*[,,objectPath]"],INTEGER_POSITIVE:["objectPath","*[,,objectPath]"],DECIMAL_POSITIVE:["objectPath","*[,,objectPath]"],DOUBLE_POSITIVE:["objectPath","*[,,objectPath]"],INTEGER_NEGATIVE:["objectPath","*[,,objectPath]"],DECIMAL_NEGATIVE:["objectPath","*[,,objectPath]"],DOUBLE_NEGATIVE:["objectPath","*[,,objectPath]"]},objectPath:{"(":["graphNodePath"],"[":["graphNodePath"],VAR1:["graphNodePath"],VAR2:["graphNodePath"],NIL:["graphNodePath"],IRI_REF:["graphNodePath"],TRUE:["graphNodePath"],FALSE:["graphNodePath"],BLANK_NODE_LABEL:["graphNodePath"],ANON:["graphNodePath"],PNAME_LN:["graphNodePath"],PNAME_NS:["graphNodePath"],STRING_LITERAL1:["graphNodePath"],STRING_LITERAL2:["graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath"],INTEGER:["graphNodePath"],DECIMAL:["graphNodePath"],DOUBLE:["graphNodePath"],INTEGER_POSITIVE:["graphNodePath"],DECIMAL_POSITIVE:["graphNodePath"],DOUBLE_POSITIVE:["graphNodePath"],INTEGER_NEGATIVE:["graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath"]},offsetClause:{OFFSET:["OFFSET","INTEGER"]},optionalGraphPattern:{OPTIONAL:["OPTIONAL","groupGraphPattern"]},"or([*,expression])":{"*":["*"],"!":["expression"],"+":["expression"],"-":["expression"],VAR1:["expression"],VAR2:["expression"],"(":["expression"],STR:["expression"],LANG:["expression"],LANGMATCHES:["expression"],DATATYPE:["expression"],BOUND:["expression"],IRI:["expression"],URI:["expression"],BNODE:["expression"],RAND:["expression"],ABS:["expression"],CEIL:["expression"],FLOOR:["expression"],ROUND:["expression"],CONCAT:["expression"],STRLEN:["expression"],UCASE:["expression"],LCASE:["expression"],ENCODE_FOR_URI:["expression"],CONTAINS:["expression"],STRSTARTS:["expression"],STRENDS:["expression"],STRBEFORE:["expression"],STRAFTER:["expression"],YEAR:["expression"],MONTH:["expression"],DAY:["expression"],HOURS:["expression"],MINUTES:["expression"],SECONDS:["expression"],TIMEZONE:["expression"],TZ:["expression"],NOW:["expression"],UUID:["expression"],STRUUID:["expression"],MD5:["expression"],SHA1:["expression"],SHA256:["expression"],SHA384:["expression"],SHA512:["expression"],COALESCE:["expression"],IF:["expression"],STRLANG:["expression"],STRDT:["expression"],SAMETERM:["expression"],ISIRI:["expression"],ISURI:["expression"],ISBLANK:["expression"],ISLITERAL:["expression"],ISNUMERIC:["expression"],TRUE:["expression"],FALSE:["expression"],COUNT:["expression"],SUM:["expression"],MIN:["expression"],MAX:["expression"],AVG:["expression"],SAMPLE:["expression"],GROUP_CONCAT:["expression"],SUBSTR:["expression"],REPLACE:["expression"],REGEX:["expression"],EXISTS:["expression"],NOT:["expression"],IRI_REF:["expression"],STRING_LITERAL1:["expression"],STRING_LITERAL2:["expression"],STRING_LITERAL_LONG1:["expression"],STRING_LITERAL_LONG2:["expression"],INTEGER:["expression"],DECIMAL:["expression"],DOUBLE:["expression"],INTEGER_POSITIVE:["expression"],DECIMAL_POSITIVE:["expression"],DOUBLE_POSITIVE:["expression"],INTEGER_NEGATIVE:["expression"],DECIMAL_NEGATIVE:["expression"],DOUBLE_NEGATIVE:["expression"],PNAME_LN:["expression"],PNAME_NS:["expression"]},"or([+or([var,[ (,expression,AS,var,)]]),*])":{"(":["+or([var,[ (,expression,AS,var,)]])"],VAR1:["+or([var,[ (,expression,AS,var,)]])"],VAR2:["+or([var,[ (,expression,AS,var,)]])"],"*":["*"]},"or([+varOrIRIref,*])":{VAR1:["+varOrIRIref"],VAR2:["+varOrIRIref"],IRI_REF:["+varOrIRIref"],PNAME_LN:["+varOrIRIref"],PNAME_NS:["+varOrIRIref"],"*":["*"]},"or([ASC,DESC])":{ASC:["ASC"],DESC:["DESC"]},"or([DISTINCT,REDUCED])":{DISTINCT:["DISTINCT"],REDUCED:["REDUCED"]},"or([LANGTAG,[^^,iriRef]])":{LANGTAG:["LANGTAG"],"^^":["[^^,iriRef]"]},"or([NIL,[ (,*var,)]])":{NIL:["NIL"],"(":["[ (,*var,)]"]},"or([[ (,*dataBlockValue,)],NIL])":{"(":["[ (,*dataBlockValue,)]"],NIL:["NIL"]},"or([[ (,expression,)],NIL])":{"(":["[ (,expression,)]"],NIL:["NIL"]},"or([[*,unaryExpression],[/,unaryExpression]])":{"*":["[*,unaryExpression]"],"/":["[/,unaryExpression]"]},"or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["[+,multiplicativeExpression]"],"-":["[-,multiplicativeExpression]"],INTEGER_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],INTEGER_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"]},"or([[,,or([},[integer,}]])],}])":{",":["[,,or([},[integer,}]])]"],"}":["}"]},"or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["[=,numericExpression]"],"!=":["[!=,numericExpression]"],"<":["[<,numericExpression]"],">":["[>,numericExpression]"],"<=":["[<=,numericExpression]"],">=":["[>=,numericExpression]"],IN:["[IN,expressionList]"],NOT:["[NOT,IN,expressionList]"]},"or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])":{"{":["[constructTemplate,*datasetClause,whereClause,solutionModifier]"],WHERE:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"],FROM:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"]},"or([[deleteClause,?insertClause],insertClause])":{DELETE:["[deleteClause,?insertClause]"],INSERT:["insertClause"]},"or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])":{INTEGER:["[integer,or([[,,or([},[integer,}]])],}])]"],",":["[,,integer,}]"]},"or([defaultGraphClause,namedGraphClause])":{IRI_REF:["defaultGraphClause"],PNAME_LN:["defaultGraphClause"],PNAME_NS:["defaultGraphClause"],NAMED:["namedGraphClause"]},"or([inlineDataOneVar,inlineDataFull])":{VAR1:["inlineDataOneVar"],VAR2:["inlineDataOneVar"],NIL:["inlineDataFull"],"(":["inlineDataFull"]},"or([iriRef,[NAMED,iriRef]])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],NAMED:["[NAMED,iriRef]"]},"or([iriRef,a])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"]},"or([numericLiteralPositive,numericLiteralNegative])":{INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},"or([queryAll,updateAll])":{CONSTRUCT:["queryAll"],DESCRIBE:["queryAll"],ASK:["queryAll"],SELECT:["queryAll"],INSERT:["updateAll"],DELETE:["updateAll"],LOAD:["updateAll"],CLEAR:["updateAll"],DROP:["updateAll"],ADD:["updateAll"],MOVE:["updateAll"],COPY:["updateAll"],CREATE:["updateAll"],WITH:["updateAll"],$:["updateAll"]},"or([selectQuery,constructQuery,describeQuery,askQuery])":{SELECT:["selectQuery"],CONSTRUCT:["constructQuery"],DESCRIBE:["describeQuery"],ASK:["askQuery"]},"or([subSelect,groupGraphPatternSub])":{SELECT:["subSelect"],"{":["groupGraphPatternSub"],OPTIONAL:["groupGraphPatternSub"],MINUS:["groupGraphPatternSub"],GRAPH:["groupGraphPatternSub"],SERVICE:["groupGraphPatternSub"],FILTER:["groupGraphPatternSub"],BIND:["groupGraphPatternSub"],VALUES:["groupGraphPatternSub"],VAR1:["groupGraphPatternSub"],VAR2:["groupGraphPatternSub"],NIL:["groupGraphPatternSub"],"(":["groupGraphPatternSub"],"[":["groupGraphPatternSub"],IRI_REF:["groupGraphPatternSub"],TRUE:["groupGraphPatternSub"],FALSE:["groupGraphPatternSub"],BLANK_NODE_LABEL:["groupGraphPatternSub"],ANON:["groupGraphPatternSub"],PNAME_LN:["groupGraphPatternSub"],PNAME_NS:["groupGraphPatternSub"],STRING_LITERAL1:["groupGraphPatternSub"],STRING_LITERAL2:["groupGraphPatternSub"],STRING_LITERAL_LONG1:["groupGraphPatternSub"],STRING_LITERAL_LONG2:["groupGraphPatternSub"],INTEGER:["groupGraphPatternSub"],DECIMAL:["groupGraphPatternSub"],DOUBLE:["groupGraphPatternSub"],INTEGER_POSITIVE:["groupGraphPatternSub"],DECIMAL_POSITIVE:["groupGraphPatternSub"],DOUBLE_POSITIVE:["groupGraphPatternSub"],INTEGER_NEGATIVE:["groupGraphPatternSub"],DECIMAL_NEGATIVE:["groupGraphPatternSub"],DOUBLE_NEGATIVE:["groupGraphPatternSub"],"}":["groupGraphPatternSub"]},"or([var,[ (,expression,AS,var,)]])":{VAR1:["var"],VAR2:["var"],"(":["[ (,expression,AS,var,)]"]},"or([verbPath,verbSimple])":{"^":["verbPath"],a:["verbPath"],"!":["verbPath"],"(":["verbPath"],IRI_REF:["verbPath"],PNAME_LN:["verbPath"],PNAME_NS:["verbPath"],VAR1:["verbSimple"],VAR2:["verbSimple"]},"or([},[integer,}]])":{"}":["}"],INTEGER:["[integer,}]"]},orderClause:{ORDER:["ORDER","BY","+orderCondition"]},orderCondition:{ASC:["or([ASC,DESC])","brackettedExpression"],DESC:["or([ASC,DESC])","brackettedExpression"],"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"],VAR1:["var"],VAR2:["var"]},path:{"^":["pathAlternative"],a:["pathAlternative"],"!":["pathAlternative"],"(":["pathAlternative"],IRI_REF:["pathAlternative"],PNAME_LN:["pathAlternative"],PNAME_NS:["pathAlternative"]},pathAlternative:{"^":["pathSequence","*[|,pathSequence]"],a:["pathSequence","*[|,pathSequence]"],"!":["pathSequence","*[|,pathSequence]"],"(":["pathSequence","*[|,pathSequence]"],IRI_REF:["pathSequence","*[|,pathSequence]"],PNAME_LN:["pathSequence","*[|,pathSequence]"],PNAME_NS:["pathSequence","*[|,pathSequence]"]},pathElt:{a:["pathPrimary","?pathMod"],"!":["pathPrimary","?pathMod"],"(":["pathPrimary","?pathMod"],IRI_REF:["pathPrimary","?pathMod"],PNAME_LN:["pathPrimary","?pathMod"],PNAME_NS:["pathPrimary","?pathMod"]},pathEltOrInverse:{a:["pathElt"],"!":["pathElt"],"(":["pathElt"],IRI_REF:["pathElt"],PNAME_LN:["pathElt"],PNAME_NS:["pathElt"],"^":["^","pathElt"]},pathMod:{"*":["*"],"?":["?"],"+":["+"],"{":["{","or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])"]},pathNegatedPropertySet:{a:["pathOneInPropertySet"],"^":["pathOneInPropertySet"],IRI_REF:["pathOneInPropertySet"],PNAME_LN:["pathOneInPropertySet"],PNAME_NS:["pathOneInPropertySet"],"(":["(","?[pathOneInPropertySet,*[|,pathOneInPropertySet]]",")"]},pathOneInPropertySet:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"],"^":["^","or([iriRef,a])"]},pathPrimary:{IRI_REF:["storeProperty","iriRef"],PNAME_LN:["storeProperty","iriRef"],PNAME_NS:["storeProperty","iriRef"],a:["storeProperty","a"],"!":["!","pathNegatedPropertySet"],"(":["(","path",")"]},pathSequence:{"^":["pathEltOrInverse","*[/,pathEltOrInverse]"],a:["pathEltOrInverse","*[/,pathEltOrInverse]"],"!":["pathEltOrInverse","*[/,pathEltOrInverse]"],"(":["pathEltOrInverse","*[/,pathEltOrInverse]"],IRI_REF:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_LN:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_NS:["pathEltOrInverse","*[/,pathEltOrInverse]"]},prefixDecl:{PREFIX:["PREFIX","PNAME_NS","IRI_REF"]},prefixedName:{PNAME_LN:["PNAME_LN"],PNAME_NS:["PNAME_NS"]},primaryExpression:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["iriRefOrFunction"],PNAME_LN:["iriRefOrFunction"],PNAME_NS:["iriRefOrFunction"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],VAR1:["var"],VAR2:["var"],COUNT:["aggregate"],SUM:["aggregate"],MIN:["aggregate"],MAX:["aggregate"],AVG:["aggregate"],SAMPLE:["aggregate"],GROUP_CONCAT:["aggregate"]},prologue:{PREFIX:["?baseDecl","*prefixDecl"],BASE:["?baseDecl","*prefixDecl"],$:["?baseDecl","*prefixDecl"],CONSTRUCT:["?baseDecl","*prefixDecl"],DESCRIBE:["?baseDecl","*prefixDecl"],ASK:["?baseDecl","*prefixDecl"],INSERT:["?baseDecl","*prefixDecl"],DELETE:["?baseDecl","*prefixDecl"],SELECT:["?baseDecl","*prefixDecl"],LOAD:["?baseDecl","*prefixDecl"],CLEAR:["?baseDecl","*prefixDecl"],DROP:["?baseDecl","*prefixDecl"],ADD:["?baseDecl","*prefixDecl"],MOVE:["?baseDecl","*prefixDecl"],COPY:["?baseDecl","*prefixDecl"],CREATE:["?baseDecl","*prefixDecl"],WITH:["?baseDecl","*prefixDecl"]},propertyList:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"}":[],GRAPH:[]},propertyListNotEmpty:{a:["verb","objectList","*[;,?[verb,objectList]]"],VAR1:["verb","objectList","*[;,?[verb,objectList]]"],VAR2:["verb","objectList","*[;,?[verb,objectList]]"],IRI_REF:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_LN:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_NS:["verb","objectList","*[;,?[verb,objectList]]"]},propertyListPath:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},propertyListPathNotEmpty:{VAR1:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],VAR2:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"^":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],a:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"!":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"(":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],IRI_REF:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_LN:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_NS:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"]},quadData:{"{":["{","disallowVars","quads","allowVars","}"]},quadDataNoBnodes:{"{":["{","disallowBnodes","disallowVars","quads","allowVars","allowBnodes","}"]},quadPattern:{"{":["{","quads","}"]},quadPatternNoBnodes:{"{":["{","disallowBnodes","quads","allowBnodes","}"]},quads:{GRAPH:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],NIL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"(":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"[":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],IRI_REF:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],TRUE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],FALSE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],BLANK_NODE_LABEL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],ANON:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_LN:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_NS:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"}":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"]},quadsNotTriples:{GRAPH:["GRAPH","varOrIRIref","{","?triplesTemplate","}"]},queryAll:{CONSTRUCT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],DESCRIBE:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],ASK:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],SELECT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"]},rdfLiteral:{STRING_LITERAL1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL2:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG2:["string","?or([LANGTAG,[^^,iriRef]])"]},regexExpression:{REGEX:["REGEX","(","expression",",","expression","?[,,expression]",")"]},relationalExpression:{"!":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"+":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"-":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"(":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANGMATCHES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DATATYPE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BOUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BNODE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],RAND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ABS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CEIL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FLOOR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ROUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLEN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ENCODE_FOR_URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONTAINS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRSTARTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRENDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRBEFORE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRAFTER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],YEAR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MONTH:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DAY:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],HOURS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MINUTES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SECONDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TIMEZONE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TZ:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOW:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRUUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MD5:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA256:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA384:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA512:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COALESCE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRDT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMETERM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISIRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISURI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISBLANK:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISLITERAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISNUMERIC:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TRUE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FALSE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COUNT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MIN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MAX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AVG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMPLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],GROUP_CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUBSTR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REPLACE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REGEX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],EXISTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI_REF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_LN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_NS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"]},selectClause:{SELECT:["SELECT","?or([DISTINCT,REDUCED])","or([+or([var,[ (,expression,AS,var,)]]),*])"]},selectQuery:{SELECT:["selectClause","*datasetClause","whereClause","solutionModifier"]},serviceGraphPattern:{SERVICE:["SERVICE","?SILENT","varOrIRIref","groupGraphPattern"]},solutionModifier:{LIMIT:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],OFFSET:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],ORDER:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],HAVING:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],GROUP:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],VALUES:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],$:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],"}":["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"]},sourceSelector:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},sparql11:{$:["prologue","or([queryAll,updateAll])","$"],CONSTRUCT:["prologue","or([queryAll,updateAll])","$"],DESCRIBE:["prologue","or([queryAll,updateAll])","$"],ASK:["prologue","or([queryAll,updateAll])","$"],INSERT:["prologue","or([queryAll,updateAll])","$"],DELETE:["prologue","or([queryAll,updateAll])","$"],SELECT:["prologue","or([queryAll,updateAll])","$"],LOAD:["prologue","or([queryAll,updateAll])","$"],CLEAR:["prologue","or([queryAll,updateAll])","$"],DROP:["prologue","or([queryAll,updateAll])","$"],ADD:["prologue","or([queryAll,updateAll])","$"],MOVE:["prologue","or([queryAll,updateAll])","$"],COPY:["prologue","or([queryAll,updateAll])","$"],CREATE:["prologue","or([queryAll,updateAll])","$"],WITH:["prologue","or([queryAll,updateAll])","$"],PREFIX:["prologue","or([queryAll,updateAll])","$"],BASE:["prologue","or([queryAll,updateAll])","$"]},storeProperty:{VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[],a:[]},strReplaceExpression:{REPLACE:["REPLACE","(","expression",",","expression",",","expression","?[,,expression]",")"]},string:{STRING_LITERAL1:["STRING_LITERAL1"],STRING_LITERAL2:["STRING_LITERAL2"],STRING_LITERAL_LONG1:["STRING_LITERAL_LONG1"],STRING_LITERAL_LONG2:["STRING_LITERAL_LONG2"]},subSelect:{SELECT:["selectClause","whereClause","solutionModifier","valuesClause"]},substringExpression:{SUBSTR:["SUBSTR","(","expression",",","expression","?[,,expression]",")"]},triplesBlock:{VAR1:["triplesSameSubjectPath","?[.,?triplesBlock]"],VAR2:["triplesSameSubjectPath","?[.,?triplesBlock]"],NIL:["triplesSameSubjectPath","?[.,?triplesBlock]"],"(":["triplesSameSubjectPath","?[.,?triplesBlock]"],"[":["triplesSameSubjectPath","?[.,?triplesBlock]"],IRI_REF:["triplesSameSubjectPath","?[.,?triplesBlock]"],TRUE:["triplesSameSubjectPath","?[.,?triplesBlock]"],FALSE:["triplesSameSubjectPath","?[.,?triplesBlock]"],BLANK_NODE_LABEL:["triplesSameSubjectPath","?[.,?triplesBlock]"],ANON:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_LN:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_NS:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL2:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG2:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"]},triplesNode:{"(":["collection"],"[":["blankNodePropertyList"]},triplesNodePath:{"(":["collectionPath"],"[":["blankNodePropertyListPath"]},triplesSameSubject:{VAR1:["varOrTerm","propertyListNotEmpty"],VAR2:["varOrTerm","propertyListNotEmpty"],NIL:["varOrTerm","propertyListNotEmpty"],IRI_REF:["varOrTerm","propertyListNotEmpty"],TRUE:["varOrTerm","propertyListNotEmpty"],FALSE:["varOrTerm","propertyListNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListNotEmpty"],ANON:["varOrTerm","propertyListNotEmpty"],PNAME_LN:["varOrTerm","propertyListNotEmpty"],PNAME_NS:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListNotEmpty"],INTEGER:["varOrTerm","propertyListNotEmpty"],DECIMAL:["varOrTerm","propertyListNotEmpty"],DOUBLE:["varOrTerm","propertyListNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListNotEmpty"],"(":["triplesNode","propertyList"],"[":["triplesNode","propertyList"]},triplesSameSubjectPath:{VAR1:["varOrTerm","propertyListPathNotEmpty"],VAR2:["varOrTerm","propertyListPathNotEmpty"],NIL:["varOrTerm","propertyListPathNotEmpty"],IRI_REF:["varOrTerm","propertyListPathNotEmpty"],TRUE:["varOrTerm","propertyListPathNotEmpty"],FALSE:["varOrTerm","propertyListPathNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListPathNotEmpty"],ANON:["varOrTerm","propertyListPathNotEmpty"],PNAME_LN:["varOrTerm","propertyListPathNotEmpty"],PNAME_NS:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListPathNotEmpty"],INTEGER:["varOrTerm","propertyListPathNotEmpty"],DECIMAL:["varOrTerm","propertyListPathNotEmpty"],DOUBLE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],"(":["triplesNodePath","propertyListPath"],"[":["triplesNodePath","propertyListPath"]},triplesTemplate:{VAR1:["triplesSameSubject","?[.,?triplesTemplate]"],VAR2:["triplesSameSubject","?[.,?triplesTemplate]"],NIL:["triplesSameSubject","?[.,?triplesTemplate]"],"(":["triplesSameSubject","?[.,?triplesTemplate]"],"[":["triplesSameSubject","?[.,?triplesTemplate]"],IRI_REF:["triplesSameSubject","?[.,?triplesTemplate]"],TRUE:["triplesSameSubject","?[.,?triplesTemplate]"],FALSE:["triplesSameSubject","?[.,?triplesTemplate]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?triplesTemplate]"],ANON:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_LN:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_NS:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL2:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"]},unaryExpression:{"!":["!","primaryExpression"],"+":["+","primaryExpression"],"-":["-","primaryExpression"],VAR1:["primaryExpression"],VAR2:["primaryExpression"],"(":["primaryExpression"],STR:["primaryExpression"],LANG:["primaryExpression"],LANGMATCHES:["primaryExpression"],DATATYPE:["primaryExpression"],BOUND:["primaryExpression"],IRI:["primaryExpression"],URI:["primaryExpression"],BNODE:["primaryExpression"],RAND:["primaryExpression"],ABS:["primaryExpression"],CEIL:["primaryExpression"],FLOOR:["primaryExpression"],ROUND:["primaryExpression"],CONCAT:["primaryExpression"],STRLEN:["primaryExpression"],UCASE:["primaryExpression"],LCASE:["primaryExpression"],ENCODE_FOR_URI:["primaryExpression"],CONTAINS:["primaryExpression"],STRSTARTS:["primaryExpression"],STRENDS:["primaryExpression"],STRBEFORE:["primaryExpression"],STRAFTER:["primaryExpression"],YEAR:["primaryExpression"],MONTH:["primaryExpression"],DAY:["primaryExpression"],HOURS:["primaryExpression"],MINUTES:["primaryExpression"],SECONDS:["primaryExpression"],TIMEZONE:["primaryExpression"],TZ:["primaryExpression"],NOW:["primaryExpression"],UUID:["primaryExpression"],STRUUID:["primaryExpression"],MD5:["primaryExpression"],SHA1:["primaryExpression"],SHA256:["primaryExpression"],SHA384:["primaryExpression"],SHA512:["primaryExpression"],COALESCE:["primaryExpression"],IF:["primaryExpression"],STRLANG:["primaryExpression"],STRDT:["primaryExpression"],SAMETERM:["primaryExpression"],ISIRI:["primaryExpression"],ISURI:["primaryExpression"],ISBLANK:["primaryExpression"],ISLITERAL:["primaryExpression"],ISNUMERIC:["primaryExpression"],TRUE:["primaryExpression"],FALSE:["primaryExpression"],COUNT:["primaryExpression"],SUM:["primaryExpression"],MIN:["primaryExpression"],MAX:["primaryExpression"],AVG:["primaryExpression"],SAMPLE:["primaryExpression"],GROUP_CONCAT:["primaryExpression"],SUBSTR:["primaryExpression"],REPLACE:["primaryExpression"],REGEX:["primaryExpression"],EXISTS:["primaryExpression"],NOT:["primaryExpression"],IRI_REF:["primaryExpression"],STRING_LITERAL1:["primaryExpression"],STRING_LITERAL2:["primaryExpression"],STRING_LITERAL_LONG1:["primaryExpression"],STRING_LITERAL_LONG2:["primaryExpression"],INTEGER:["primaryExpression"],DECIMAL:["primaryExpression"],DOUBLE:["primaryExpression"],INTEGER_POSITIVE:["primaryExpression"],DECIMAL_POSITIVE:["primaryExpression"],DOUBLE_POSITIVE:["primaryExpression"],INTEGER_NEGATIVE:["primaryExpression"],DECIMAL_NEGATIVE:["primaryExpression"],DOUBLE_NEGATIVE:["primaryExpression"],PNAME_LN:["primaryExpression"],PNAME_NS:["primaryExpression"]},update:{INSERT:["prologue","?[update1,?[;,update]]"],DELETE:["prologue","?[update1,?[;,update]]"],LOAD:["prologue","?[update1,?[;,update]]"],CLEAR:["prologue","?[update1,?[;,update]]"],DROP:["prologue","?[update1,?[;,update]]"],ADD:["prologue","?[update1,?[;,update]]"],MOVE:["prologue","?[update1,?[;,update]]"],COPY:["prologue","?[update1,?[;,update]]"],CREATE:["prologue","?[update1,?[;,update]]"],WITH:["prologue","?[update1,?[;,update]]"],PREFIX:["prologue","?[update1,?[;,update]]"],BASE:["prologue","?[update1,?[;,update]]"],$:["prologue","?[update1,?[;,update]]"]},update1:{LOAD:["load"],CLEAR:["clear"],DROP:["drop"],ADD:["add"],MOVE:["move"],COPY:["copy"],CREATE:["create"],INSERT:["INSERT","insert1"],DELETE:["DELETE","delete1"],WITH:["modify"]},updateAll:{INSERT:["?[update1,?[;,update]]"],DELETE:["?[update1,?[;,update]]"],LOAD:["?[update1,?[;,update]]"],CLEAR:["?[update1,?[;,update]]"],DROP:["?[update1,?[;,update]]"],ADD:["?[update1,?[;,update]]"],MOVE:["?[update1,?[;,update]]"],COPY:["?[update1,?[;,update]]"],CREATE:["?[update1,?[;,update]]"],WITH:["?[update1,?[;,update]]"],$:["?[update1,?[;,update]]"]},usingClause:{USING:["USING","or([iriRef,[NAMED,iriRef]])"]},valueLogical:{"!":["relationalExpression"],"+":["relationalExpression"],"-":["relationalExpression"],VAR1:["relationalExpression"],VAR2:["relationalExpression"],"(":["relationalExpression"],STR:["relationalExpression"],LANG:["relationalExpression"],LANGMATCHES:["relationalExpression"],DATATYPE:["relationalExpression"],BOUND:["relationalExpression"],IRI:["relationalExpression"],URI:["relationalExpression"],BNODE:["relationalExpression"],RAND:["relationalExpression"],ABS:["relationalExpression"],CEIL:["relationalExpression"],FLOOR:["relationalExpression"],ROUND:["relationalExpression"],CONCAT:["relationalExpression"],STRLEN:["relationalExpression"],UCASE:["relationalExpression"],LCASE:["relationalExpression"],ENCODE_FOR_URI:["relationalExpression"],CONTAINS:["relationalExpression"],STRSTARTS:["relationalExpression"],STRENDS:["relationalExpression"],STRBEFORE:["relationalExpression"],STRAFTER:["relationalExpression"],YEAR:["relationalExpression"],MONTH:["relationalExpression"],DAY:["relationalExpression"],HOURS:["relationalExpression"],MINUTES:["relationalExpression"],SECONDS:["relationalExpression"],TIMEZONE:["relationalExpression"],TZ:["relationalExpression"],NOW:["relationalExpression"],UUID:["relationalExpression"],STRUUID:["relationalExpression"],MD5:["relationalExpression"],SHA1:["relationalExpression"],SHA256:["relationalExpression"],SHA384:["relationalExpression"],SHA512:["relationalExpression"],COALESCE:["relationalExpression"],IF:["relationalExpression"],STRLANG:["relationalExpression"],STRDT:["relationalExpression"],SAMETERM:["relationalExpression"],ISIRI:["relationalExpression"],ISURI:["relationalExpression"],ISBLANK:["relationalExpression"],ISLITERAL:["relationalExpression"],ISNUMERIC:["relationalExpression"],TRUE:["relationalExpression"],FALSE:["relationalExpression"],COUNT:["relationalExpression"],SUM:["relationalExpression"],MIN:["relationalExpression"],MAX:["relationalExpression"],AVG:["relationalExpression"],SAMPLE:["relationalExpression"],GROUP_CONCAT:["relationalExpression"],SUBSTR:["relationalExpression"],REPLACE:["relationalExpression"],REGEX:["relationalExpression"],EXISTS:["relationalExpression"],NOT:["relationalExpression"],IRI_REF:["relationalExpression"],STRING_LITERAL1:["relationalExpression"],STRING_LITERAL2:["relationalExpression"],STRING_LITERAL_LONG1:["relationalExpression"],STRING_LITERAL_LONG2:["relationalExpression"],INTEGER:["relationalExpression"],DECIMAL:["relationalExpression"],DOUBLE:["relationalExpression"],INTEGER_POSITIVE:["relationalExpression"],DECIMAL_POSITIVE:["relationalExpression"],DOUBLE_POSITIVE:["relationalExpression"],INTEGER_NEGATIVE:["relationalExpression"],DECIMAL_NEGATIVE:["relationalExpression"],DOUBLE_NEGATIVE:["relationalExpression"],PNAME_LN:["relationalExpression"],PNAME_NS:["relationalExpression"]},valuesClause:{VALUES:["VALUES","dataBlock"],$:[],"}":[]},"var":{VAR1:["VAR1"],VAR2:["VAR2"]},varOrIRIref:{VAR1:["var"],VAR2:["var"],IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},varOrTerm:{VAR1:["var"],VAR2:["var"],NIL:["graphTerm"],IRI_REF:["graphTerm"],TRUE:["graphTerm"],FALSE:["graphTerm"],BLANK_NODE_LABEL:["graphTerm"],ANON:["graphTerm"],PNAME_LN:["graphTerm"],PNAME_NS:["graphTerm"],STRING_LITERAL1:["graphTerm"],STRING_LITERAL2:["graphTerm"],STRING_LITERAL_LONG1:["graphTerm"],STRING_LITERAL_LONG2:["graphTerm"],INTEGER:["graphTerm"],DECIMAL:["graphTerm"],DOUBLE:["graphTerm"],INTEGER_POSITIVE:["graphTerm"],DECIMAL_POSITIVE:["graphTerm"],DOUBLE_POSITIVE:["graphTerm"],INTEGER_NEGATIVE:["graphTerm"],DECIMAL_NEGATIVE:["graphTerm"],DOUBLE_NEGATIVE:["graphTerm"]},verb:{VAR1:["storeProperty","varOrIRIref"],VAR2:["storeProperty","varOrIRIref"],IRI_REF:["storeProperty","varOrIRIref"],PNAME_LN:["storeProperty","varOrIRIref"],PNAME_NS:["storeProperty","varOrIRIref"],a:["storeProperty","a"]},verbPath:{"^":["path"],a:["path"],"!":["path"],"(":["path"],IRI_REF:["path"],PNAME_LN:["path"],PNAME_NS:["path"]},verbSimple:{VAR1:["var"],VAR2:["var"]},whereClause:{"{":["?WHERE","groupGraphPattern"],WHERE:["?WHERE","groupGraphPattern"]}}),s=/^(GROUP_CONCAT|DATATYPE|BASE|PREFIX|SELECT|CONSTRUCT|DESCRIBE|ASK|FROM|NAMED|ORDER|BY|LIMIT|ASC|DESC|OFFSET|DISTINCT|REDUCED|WHERE|GRAPH|OPTIONAL|UNION|FILTER|GROUP|HAVING|AS|VALUES|LOAD|CLEAR|DROP|CREATE|MOVE|COPY|SILENT|INSERT|DELETE|DATA|WITH|TO|USING|NAMED|MINUS|BIND|LANGMATCHES|LANG|BOUND|SAMETERM|ISIRI|ISURI|ISBLANK|ISLITERAL|REGEX|TRUE|FALSE|UNDEF|ADD|DEFAULT|ALL|SERVICE|INTO|IN|NOT|IRI|URI|BNODE|RAND|ABS|CEIL|FLOOR|ROUND|CONCAT|STRLEN|UCASE|LCASE|ENCODE_FOR_URI|CONTAINS|STRSTARTS|STRENDS|STRBEFORE|STRAFTER|YEAR|MONTH|DAY|HOURS|MINUTES|SECONDS|TIMEZONE|TZ|NOW|UUID|STRUUID|MD5|SHA1|SHA256|SHA384|SHA512|COALESCE|IF|STRLANG|STRDT|ISNUMERIC|SUBSTR|REPLACE|EXISTS|COUNT|SUM|MIN|MAX|AVG|SAMPLE|SEPARATOR|STR)/i,a=/^(\*|a|\.|\{|\}|,|\(|\)|;|\[|\]|\|\||&&|=|!=|!|<=|>=|<|>|\+|-|\/|\^\^|\?|\||\^)/,l=null,u="sparql11",p="sparql11",c=!0,d=t(),f=d.terminal,h={"*[,, object]":3,"*[(,),object]":3,"*[(,),objectPath]":3,"*[/,pathEltOrInverse]":2,object:2,objectPath:2,objectList:2,objectListPath:2,storeProperty:2,pathMod:2,"?pathMod":2,propertyListNotEmpty:1,propertyList:1,propertyListPath:1,propertyListPathNotEmpty:1,"?[verb,objectList]":1,"?[or([verbPath, verbSimple]),objectList]":1},E={"}":1,"]":0,")":1,"{":-1,"(":-1,"*[;,?[or([verbPath,verbSimple]),objectList]]":1}; return{token:r,startState:function(){return{tokenize:r,OK:!0,complete:c,errorStartPos:null,errorEndPos:null,queryType:l,possibleCurrent:i(p),possibleNext:i(p),allowVars:!0,allowBnodes:!0,storeProperty:!1,lastProperty:"",stack:[p]}},indent:n,electricChars:"}])"}});e.defineMIME("application/x-sparql-query","sparql11")})},{codemirror:14}],4:[function(e,t){var i=t.exports=function(){this.words=0;this.prefixes=0;this.children=[]};i.prototype={insert:function(e,t){if(0!=e.length){var r,n,o=this;void 0===t&&(t=0);if(t!==e.length){o.prefixes++;r=e[t];void 0===o.children[r]&&(o.children[r]=new i);n=o.children[r];n.insert(e,t+1)}else o.words++}},remove:function(e,t){if(0!=e.length){var i,r,n=this;void 0===t&&(t=0);if(void 0!==n)if(t!==e.length){n.prefixes--;i=e[t];r=n.children[i];r.remove(e,t+1)}else n.words--}},update:function(e,t){if(0!=e.length&&0!=t.length){this.remove(e);this.insert(t)}},countWord:function(e,t){if(0==e.length)return 0;var i,r,n=this,o=0;void 0===t&&(t=0);if(t===e.length)return n.words;i=e[t];r=n.children[i];void 0!==r&&(o=r.countWord(e,t+1));return o},countPrefix:function(e,t){if(0==e.length)return 0;var i,r,n=this,o=0;void 0===t&&(t=0);if(t===e.length)return n.prefixes;var i=e[t];r=n.children[i];void 0!==r&&(o=r.countPrefix(e,t+1));return o},find:function(e){return 0==e.length?!1:this.countWord(e)>0?!0:!1},getAllWords:function(e){var t,i,r=this,n=[];void 0===e&&(e="");if(void 0===r)return[];r.words>0&&n.push(e);for(t in r.children){i=r.children[t];n=n.concat(i.getAllWords(e+t))}return n},autoComplete:function(e,t){var i,r,n=this;if(0==e.length)return void 0===t?n.getAllWords(e):[];void 0===t&&(t=0);i=e[t];r=n.children[i];return void 0===r?[]:t===e.length-1?r.getAllWords(e):r.autoComplete(e,t+1)}}},{}],5:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e){var t=e.getWrapperElement();e.state.fullScreenRestore={scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,width:t.style.width,height:t.style.height};t.style.width="";t.style.height="auto";t.className+=" CodeMirror-fullscreen";document.documentElement.style.overflow="hidden";e.refresh()}function i(e){var t=e.getWrapperElement();t.className=t.className.replace(/\s*CodeMirror-fullscreen\b/,"");document.documentElement.style.overflow="";var i=e.state.fullScreenRestore;t.style.width=i.width;t.style.height=i.height;window.scrollTo(i.scrollLeft,i.scrollTop);e.refresh()}e.defineOption("fullScreen",!1,function(r,n,o){o==e.Init&&(o=!1);!o!=!n&&(n?t(r):i(r))})})},{"../../lib/codemirror":14}],6:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){function t(e,t,r,n){var o=e.getLineHandle(t.line),l=t.ch-1,u=l>=0&&a[o.text.charAt(l)]||a[o.text.charAt(++l)];if(!u)return null;var p=">"==u.charAt(1)?1:-1;if(r&&p>0!=(l==t.ch))return null;var c=e.getTokenTypeAt(s(t.line,l+1)),d=i(e,s(t.line,l+(p>0?1:0)),p,c||null,n);return null==d?null:{from:s(t.line,l),to:d&&d.pos,match:d&&d.ch==u.charAt(0),forward:p>0}}function i(e,t,i,r,n){for(var o=n&&n.maxScanLineLength||1e4,l=n&&n.maxScanLines||1e3,u=[],p=n&&n.bracketRegex?n.bracketRegex:/[(){}[\]]/,c=i>0?Math.min(t.line+l,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-l),d=t.line;d!=c;d+=i){var f=e.getLine(d);if(f){var h=i>0?0:f.length-1,E=i>0?f.length:-1;if(!(f.length>o)){d==t.line&&(h=t.ch-(0>i?1:0));for(;h!=E;h+=i){var m=f.charAt(h);if(p.test(m)&&(void 0===r||e.getTokenTypeAt(s(d,h+1))==r)){var g=a[m];if(">"==g.charAt(1)==i>0)u.push(m);else{if(!u.length)return{pos:s(d,h),ch:m};u.pop()}}}}}}return d-i==(i>0?e.lastLine():e.firstLine())?!1:null}function r(e,i,r){for(var n=e.state.matchBrackets.maxHighlightLineLength||1e3,a=[],l=e.listSelections(),u=0;u<l.length;u++){var p=l[u].empty()&&t(e,l[u].head,!1,r);if(p&&e.getLine(p.from.line).length<=n){var c=p.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";a.push(e.markText(p.from,s(p.from.line,p.from.ch+1),{className:c}));p.to&&e.getLine(p.to.line).length<=n&&a.push(e.markText(p.to,s(p.to.line,p.to.ch+1),{className:c}))}}if(a.length){o&&e.state.focused&&e.display.input.focus();var d=function(){e.operation(function(){for(var e=0;e<a.length;e++)a[e].clear()})};if(!i)return d;setTimeout(d,800)}}function n(e){e.operation(function(){if(l){l();l=null}l=r(e,!1,e.state.matchBrackets)})}var o=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),s=e.Pos,a={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},l=null;e.defineOption("matchBrackets",!1,function(t,i,r){r&&r!=e.Init&&t.off("cursorActivity",n);if(i){t.state.matchBrackets="object"==typeof i?i:{};t.on("cursorActivity",n)}});e.defineExtension("matchBrackets",function(){r(this,!0)});e.defineExtension("findMatchingBracket",function(e,i,r){return t(this,e,i,r)});e.defineExtension("scanForBracket",function(e,t,r,n){return i(this,e,t,r,n)})})},{"../../lib/codemirror":14}],7:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";e.registerHelper("fold","brace",function(t,i){function r(r){for(var n=i.ch,l=0;;){var u=0>=n?-1:a.lastIndexOf(r,n-1);if(-1!=u){if(1==l&&u<i.ch)break;o=t.getTokenTypeAt(e.Pos(s,u+1));if(!/^(comment|string)/.test(o))return u+1;n=u-1}else{if(1==l)break;l=1;n=a.length}}}var n,o,s=i.line,a=t.getLine(s),l="{",u="}",n=r("{");if(null==n){l="[",u="]";n=r("[")}if(null!=n){var p,c,d=1,f=t.lastLine();e:for(var h=s;f>=h;++h)for(var E=t.getLine(h),m=h==s?n:0;;){var g=E.indexOf(l,m),v=E.indexOf(u,m);0>g&&(g=E.length);0>v&&(v=E.length);m=Math.min(g,v);if(m==E.length)break;if(t.getTokenTypeAt(e.Pos(h,m+1))==o)if(m==g)++d;else if(!--d){p=h;c=m;break e}++m}if(null!=p&&(s!=p||c!=n))return{from:e.Pos(s,n),to:e.Pos(p,c)}}});e.registerHelper("fold","import",function(t,i){function r(i){if(i<t.firstLine()||i>t.lastLine())return null;var r=t.getTokenAt(e.Pos(i,1));/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(i,r.end+1)));if("keyword"!=r.type||"import"!=r.string)return null;for(var n=i,o=Math.min(t.lastLine(),i+10);o>=n;++n){var s=t.getLine(n),a=s.indexOf(";");if(-1!=a)return{startCh:r.end,end:e.Pos(n,a)}}}var n,i=i.line,o=r(i);if(!o||r(i-1)||(n=r(i-2))&&n.end.line==i-1)return null;for(var s=o.end;;){var a=r(s.line+1);if(null==a)break;s=a.end}return{from:t.clipPos(e.Pos(i,o.startCh+1)),to:s}});e.registerHelper("fold","include",function(t,i){function r(i){if(i<t.firstLine()||i>t.lastLine())return null;var r=t.getTokenAt(e.Pos(i,1));/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(i,r.end+1)));return"meta"==r.type&&"#include"==r.string.slice(0,8)?r.start+8:void 0}var i=i.line,n=r(i);if(null==n||null!=r(i-1))return null;for(var o=i;;){var s=r(o+1);if(null==s)break;++o}return{from:e.Pos(i,n+1),to:t.clipPos(e.Pos(o))}})})},{"../../lib/codemirror":14}],8:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(t,n,o,s){function a(e){var i=l(t,n);if(!i||i.to.line-i.from.line<u)return null;for(var r=t.findMarksAt(i.from),o=0;o<r.length;++o)if(r[o].__isFold&&"fold"!==s){if(!e)return null;i.cleared=!0;r[o].clear()}return i}if(o&&o.call){var l=o;o=null}else var l=r(t,o,"rangeFinder");"number"==typeof n&&(n=e.Pos(n,0));var u=r(t,o,"minFoldSize"),p=a(!0);if(r(t,o,"scanUp"))for(;!p&&n.line>t.firstLine();){n=e.Pos(n.line-1,0);p=a(!1)}if(p&&!p.cleared&&"unfold"!==s){var c=i(t,o);e.on(c,"mousedown",function(t){d.clear();e.e_preventDefault(t)});var d=t.markText(p.from,p.to,{replacedWith:c,clearOnEnter:!0,__isFold:!0});d.on("clear",function(i,r){e.signal(t,"unfold",t,i,r)});e.signal(t,"fold",t,p.from,p.to)}}function i(e,t){var i=r(e,t,"widget");if("string"==typeof i){var n=document.createTextNode(i);i=document.createElement("span");i.appendChild(n);i.className="CodeMirror-foldmarker"}return i}function r(e,t,i){if(t&&void 0!==t[i])return t[i];var r=e.options.foldOptions;return r&&void 0!==r[i]?r[i]:n[i]}e.newFoldFunction=function(e,i){return function(r,n){t(r,n,{rangeFinder:e,widget:i})}};e.defineExtension("foldCode",function(e,i,r){t(this,e,i,r)});e.defineExtension("isFolded",function(e){for(var t=this.findMarksAt(e),i=0;i<t.length;++i)if(t[i].__isFold)return!0});e.commands.toggleFold=function(e){e.foldCode(e.getCursor())};e.commands.fold=function(e){e.foldCode(e.getCursor(),null,"fold")};e.commands.unfold=function(e){e.foldCode(e.getCursor(),null,"unfold")};e.commands.foldAll=function(t){t.operation(function(){for(var i=t.firstLine(),r=t.lastLine();r>=i;i++)t.foldCode(e.Pos(i,0),null,"fold")})};e.commands.unfoldAll=function(t){t.operation(function(){for(var i=t.firstLine(),r=t.lastLine();r>=i;i++)t.foldCode(e.Pos(i,0),null,"unfold")})};e.registerHelper("fold","combine",function(){var e=Array.prototype.slice.call(arguments,0);return function(t,i){for(var r=0;r<e.length;++r){var n=e[r](t,i);if(n)return n}}});e.registerHelper("fold","auto",function(e,t){for(var i=e.getHelpers(t,"fold"),r=0;r<i.length;r++){var n=i[r](e,t);if(n)return n}});var n={rangeFinder:e.fold.auto,widget:"↔",minFoldSize:0,scanUp:!1};e.defineOption("foldOptions",null);e.defineExtension("foldOption",function(e,t){return r(this,e,t)})})},{"../../lib/codemirror":14}],9:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror"),t("./foldcode")):"function"==typeof e&&e.amd?e(["../../lib/codemirror","./foldcode"],n):n(CodeMirror)})(function(e){"use strict";function t(e){this.options=e;this.from=this.to=0}function i(e){e===!0&&(e={});null==e.gutter&&(e.gutter="CodeMirror-foldgutter");null==e.indicatorOpen&&(e.indicatorOpen="CodeMirror-foldgutter-open");null==e.indicatorFolded&&(e.indicatorFolded="CodeMirror-foldgutter-folded");return e}function r(e,t){for(var i=e.findMarksAt(c(t)),r=0;r<i.length;++r)if(i[r].__isFold&&i[r].find().from.line==t)return!0}function n(e){if("string"==typeof e){var t=document.createElement("div");t.className=e+" CodeMirror-guttermarker-subtle";return t}return e.cloneNode(!0)}function o(e,t,i){var o=e.state.foldGutter.options,s=t,a=e.foldOption(o,"minFoldSize"),l=e.foldOption(o,"rangeFinder");e.eachLine(t,i,function(t){var i=null;if(r(e,s))i=n(o.indicatorFolded);else{var u=c(s,0),p=l&&l(e,u);p&&p.to.line-p.from.line>=a&&(i=n(o.indicatorOpen))}e.setGutterMarker(t,o.gutter,i);++s})}function s(e){var t=e.getViewport(),i=e.state.foldGutter;if(i){e.operation(function(){o(e,t.from,t.to)});i.from=t.from;i.to=t.to}}function a(e,t,i){var r=e.state.foldGutter.options;i==r.gutter&&e.foldCode(c(t,0),r.rangeFinder)}function l(e){var t=e.state.foldGutter,i=e.state.foldGutter.options;t.from=t.to=0;clearTimeout(t.changeUpdate);t.changeUpdate=setTimeout(function(){s(e)},i.foldOnChangeTimeSpan||600)}function u(e){var t=e.state.foldGutter,i=e.state.foldGutter.options;clearTimeout(t.changeUpdate);t.changeUpdate=setTimeout(function(){var i=e.getViewport();t.from==t.to||i.from-t.to>20||t.from-i.to>20?s(e):e.operation(function(){if(i.from<t.from){o(e,i.from,t.from);t.from=i.from}if(i.to>t.to){o(e,t.to,i.to);t.to=i.to}})},i.updateViewportTimeSpan||400)}function p(e,t){var i=e.state.foldGutter,r=t.line;r>=i.from&&r<i.to&&o(e,r,r+1)}e.defineOption("foldGutter",!1,function(r,n,o){if(o&&o!=e.Init){r.clearGutter(r.state.foldGutter.options.gutter);r.state.foldGutter=null;r.off("gutterClick",a);r.off("change",l);r.off("viewportChange",u);r.off("fold",p);r.off("unfold",p);r.off("swapDoc",s)}if(n){r.state.foldGutter=new t(i(n));s(r);r.on("gutterClick",a);r.on("change",l);r.on("viewportChange",u);r.on("fold",p);r.on("unfold",p);r.on("swapDoc",s)}});var c=e.Pos})},{"../../lib/codemirror":14,"./foldcode":8}],10:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e,t){return e.line-t.line||e.ch-t.ch}function i(e,t,i,r){this.line=t;this.ch=i;this.cm=e;this.text=e.getLine(t);this.min=r?r.from:e.firstLine();this.max=r?r.to-1:e.lastLine()}function r(e,t){var i=e.cm.getTokenTypeAt(d(e.line,t));return i&&/\btag\b/.test(i)}function n(e){if(!(e.line>=e.max)){e.ch=0;e.text=e.cm.getLine(++e.line);return!0}}function o(e){if(!(e.line<=e.min)){e.text=e.cm.getLine(--e.line);e.ch=e.text.length;return!0}}function s(e){for(;;){var t=e.text.indexOf(">",e.ch);if(-1==t){if(n(e))continue;return}if(r(e,t+1)){var i=e.text.lastIndexOf("/",t),o=i>-1&&!/\S/.test(e.text.slice(i+1,t));e.ch=t+1;return o?"selfClose":"regular"}e.ch=t+1}}function a(e){for(;;){var t=e.ch?e.text.lastIndexOf("<",e.ch-1):-1;if(-1==t){if(o(e))continue;return}if(r(e,t+1)){E.lastIndex=t;e.ch=t;var i=E.exec(e.text);if(i&&i.index==t)return i}else e.ch=t}}function l(e){for(;;){E.lastIndex=e.ch;var t=E.exec(e.text);if(!t){if(n(e))continue;return}if(r(e,t.index+1)){e.ch=t.index+t[0].length;return t}e.ch=t.index+1}}function u(e){for(;;){var t=e.ch?e.text.lastIndexOf(">",e.ch-1):-1;if(-1==t){if(o(e))continue;return}if(r(e,t+1)){var i=e.text.lastIndexOf("/",t),n=i>-1&&!/\S/.test(e.text.slice(i+1,t));e.ch=t+1;return n?"selfClose":"regular"}e.ch=t}}function p(e,t){for(var i=[];;){var r,n=l(e),o=e.line,a=e.ch-(n?n[0].length:0);if(!n||!(r=s(e)))return;if("selfClose"!=r)if(n[1]){for(var u=i.length-1;u>=0;--u)if(i[u]==n[2]){i.length=u;break}if(0>u&&(!t||t==n[2]))return{tag:n[2],from:d(o,a),to:d(e.line,e.ch)}}else i.push(n[2])}}function c(e,t){for(var i=[];;){var r=u(e);if(!r)return;if("selfClose"!=r){var n=e.line,o=e.ch,s=a(e);if(!s)return;if(s[1])i.push(s[2]);else{for(var l=i.length-1;l>=0;--l)if(i[l]==s[2]){i.length=l;break}if(0>l&&(!t||t==s[2]))return{tag:s[2],from:d(e.line,e.ch),to:d(n,o)}}}else a(e)}}var d=e.Pos,f="A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",h=f+"-:.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",E=new RegExp("<(/?)(["+f+"]["+h+"]*)","g");e.registerHelper("fold","xml",function(e,t){for(var r=new i(e,t.line,0);;){var n,o=l(r);if(!o||r.line!=t.line||!(n=s(r)))return;if(!o[1]&&"selfClose"!=n){var t=d(r.line,r.ch),a=p(r,o[2]);return a&&{from:t,to:a.from}}}});e.findMatchingTag=function(e,r,n){var o=new i(e,r.line,r.ch,n);if(-1!=o.text.indexOf(">")||-1!=o.text.indexOf("<")){var l=s(o),u=l&&d(o.line,o.ch),f=l&&a(o);if(l&&f&&!(t(o,r)>0)){var h={from:d(o.line,o.ch),to:u,tag:f[2]};if("selfClose"==l)return{open:h,close:null,at:"open"};if(f[1])return{open:c(o,f[2]),close:h,at:"close"};o=new i(e,u.line,u.ch,n);return{open:h,close:p(o,f[2]),at:"open"}}}};e.findEnclosingTag=function(e,t,r){for(var n=new i(e,t.line,t.ch,r);;){var o=c(n);if(!o)break;var s=new i(e,t.line,t.ch,r),a=p(s,o.tag);if(a)return{open:o,close:a}}};e.scanForClosingTag=function(e,t,r,n){var o=new i(e,t.line,t.ch,n?{from:0,to:n}:null);return p(o,r)}})},{"../../lib/codemirror":14}],11:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e,t){this.cm=e;this.options=this.buildOptions(t);this.widget=this.onClose=null}function i(e){return"string"==typeof e?e:e.text}function r(e,t){function i(e,i){var n;n="string"!=typeof i?function(e){return i(e,t)}:r.hasOwnProperty(i)?r[i]:i;o[e]=n}var r={Up:function(){t.moveFocus(-1)},Down:function(){t.moveFocus(1)},PageUp:function(){t.moveFocus(-t.menuSize()+1,!0)},PageDown:function(){t.moveFocus(t.menuSize()-1,!0)},Home:function(){t.setFocus(0)},End:function(){t.setFocus(t.length-1)},Enter:t.pick,Tab:t.pick,Esc:t.close},n=e.options.customKeys,o=n?{}:r;if(n)for(var s in n)n.hasOwnProperty(s)&&i(s,n[s]);var a=e.options.extraKeys;if(a)for(var s in a)a.hasOwnProperty(s)&&i(s,a[s]);return o}function n(e,t){for(;t&&t!=e;){if("LI"===t.nodeName.toUpperCase()&&t.parentNode==e)return t;t=t.parentNode}}function o(t,o){this.completion=t;this.data=o;var l=this,u=t.cm,p=this.hints=document.createElement("ul");p.className="CodeMirror-hints";this.selectedHint=o.selectedHint||0;for(var c=o.list,d=0;d<c.length;++d){var f=p.appendChild(document.createElement("li")),h=c[d],E=s+(d!=this.selectedHint?"":" "+a);null!=h.className&&(E=h.className+" "+E);f.className=E;h.render?h.render(f,o,h):f.appendChild(document.createTextNode(h.displayText||i(h)));f.hintId=d}var m=u.cursorCoords(t.options.alignWithWord?o.from:null),g=m.left,v=m.bottom,x=!0;p.style.left=g+"px";p.style.top=v+"px";var N=window.innerWidth||Math.max(document.body.offsetWidth,document.documentElement.offsetWidth),T=window.innerHeight||Math.max(document.body.offsetHeight,document.documentElement.offsetHeight);(t.options.container||document.body).appendChild(p);var L=p.getBoundingClientRect(),I=L.bottom-T;if(I>0){var y=L.bottom-L.top,A=m.top-(m.bottom-L.top);if(A-y>0){p.style.top=(v=m.top-y)+"px";x=!1}else if(y>T){p.style.height=T-5+"px";p.style.top=(v=m.bottom-L.top)+"px";var S=u.getCursor();if(o.from.ch!=S.ch){m=u.cursorCoords(S);p.style.left=(g=m.left)+"px";L=p.getBoundingClientRect()}}}var C=L.right-N;if(C>0){if(L.right-L.left>N){p.style.width=N-5+"px";C-=L.right-L.left-N}p.style.left=(g=m.left-C)+"px"}u.addKeyMap(this.keyMap=r(t,{moveFocus:function(e,t){l.changeActive(l.selectedHint+e,t)},setFocus:function(e){l.changeActive(e)},menuSize:function(){return l.screenAmount()},length:c.length,close:function(){t.close()},pick:function(){l.pick()},data:o}));if(t.options.closeOnUnfocus){var R;u.on("blur",this.onBlur=function(){R=setTimeout(function(){t.close()},100)});u.on("focus",this.onFocus=function(){clearTimeout(R)})}var b=u.getScrollInfo();u.on("scroll",this.onScroll=function(){var e=u.getScrollInfo(),i=u.getWrapperElement().getBoundingClientRect(),r=v+b.top-e.top,n=r-(window.pageYOffset||(document.documentElement||document.body).scrollTop);x||(n+=p.offsetHeight);if(n<=i.top||n>=i.bottom)return t.close();p.style.top=r+"px";p.style.left=g+b.left-e.left+"px"});e.on(p,"dblclick",function(e){var t=n(p,e.target||e.srcElement);if(t&&null!=t.hintId){l.changeActive(t.hintId);l.pick()}});e.on(p,"click",function(e){var i=n(p,e.target||e.srcElement);if(i&&null!=i.hintId){l.changeActive(i.hintId);t.options.completeOnSingleClick&&l.pick()}});e.on(p,"mousedown",function(){setTimeout(function(){u.focus()},20)});e.signal(o,"select",c[0],p.firstChild);return!0}var s="CodeMirror-hint",a="CodeMirror-hint-active";e.showHint=function(e,t,i){if(!t)return e.showHint(i);i&&i.async&&(t.async=!0);var r={hint:t};if(i)for(var n in i)r[n]=i[n];return e.showHint(r)};e.defineExtension("showHint",function(i){if(!(this.listSelections().length>1||this.somethingSelected())){this.state.completionActive&&this.state.completionActive.close();var r=this.state.completionActive=new t(this,i),n=r.options.hint;if(n){e.signal(this,"startCompletion",this);if(!n.async)return r.showHints(n(this,r.options));n(this,function(e){r.showHints(e)},r.options);return void 0}}});t.prototype={close:function(){if(this.active()){this.cm.state.completionActive=null;this.widget&&this.widget.close();this.onClose&&this.onClose();e.signal(this.cm,"endCompletion",this.cm)}},active:function(){return this.cm.state.completionActive==this},pick:function(t,r){var n=t.list[r];n.hint?n.hint(this.cm,t,n):this.cm.replaceRange(i(n),n.from||t.from,n.to||t.to,"complete");e.signal(t,"pick",n);this.close()},showHints:function(e){if(!e||!e.list.length||!this.active())return this.close();this.options.completeSingle&&1==e.list.length?this.pick(e,0):this.showWidget(e);return void 0},showWidget:function(t){function i(){if(!l){l=!0;p.close();p.cm.off("cursorActivity",a);t&&e.signal(t,"close")}}function r(){if(!l){e.signal(t,"update");var i=p.options.hint;i.async?i(p.cm,n,p.options):n(i(p.cm,p.options))}}function n(e){t=e;if(!l){if(!t||!t.list.length)return i();p.widget&&p.widget.close();p.widget=new o(p,t)}}function s(){if(u){E(u);u=0}}function a(){s();var e=p.cm.getCursor(),t=p.cm.getLine(e.line);if(e.line!=d.line||t.length-e.ch!=f-d.ch||e.ch<d.ch||p.cm.somethingSelected()||e.ch&&c.test(t.charAt(e.ch-1)))p.close();else{u=h(r);p.widget&&p.widget.close()}}this.widget=new o(this,t);e.signal(t,"shown");var l,u=0,p=this,c=this.options.closeCharacters,d=this.cm.getCursor(),f=this.cm.getLine(d.line).length,h=window.requestAnimationFrame||function(e){return setTimeout(e,1e3/60)},E=window.cancelAnimationFrame||clearTimeout;this.cm.on("cursorActivity",a);this.onClose=i},buildOptions:function(e){var t=this.cm.options.hintOptions,i={};for(var r in l)i[r]=l[r];if(t)for(var r in t)void 0!==t[r]&&(i[r]=t[r]);if(e)for(var r in e)void 0!==e[r]&&(i[r]=e[r]);return i}};o.prototype={close:function(){if(this.completion.widget==this){this.completion.widget=null;this.hints.parentNode.removeChild(this.hints);this.completion.cm.removeKeyMap(this.keyMap);var e=this.completion.cm;if(this.completion.options.closeOnUnfocus){e.off("blur",this.onBlur);e.off("focus",this.onFocus)}e.off("scroll",this.onScroll)}},pick:function(){this.completion.pick(this.data,this.selectedHint)},changeActive:function(t,i){t>=this.data.list.length?t=i?this.data.list.length-1:0:0>t&&(t=i?0:this.data.list.length-1);if(this.selectedHint!=t){var r=this.hints.childNodes[this.selectedHint];r.className=r.className.replace(" "+a,"");r=this.hints.childNodes[this.selectedHint=t];r.className+=" "+a;r.offsetTop<this.hints.scrollTop?this.hints.scrollTop=r.offsetTop-3:r.offsetTop+r.offsetHeight>this.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=r.offsetTop+r.offsetHeight-this.hints.clientHeight+3);e.signal(this.data,"select",this.data.list[this.selectedHint],r)}},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}};e.registerHelper("hint","auto",function(t,i){var r,n=t.getHelpers(t.getCursor(),"hint");if(n.length)for(var o=0;o<n.length;o++){var s=n[o](t,i);if(s&&s.list.length)return s}else if(r=t.getHelper(t.getCursor(),"hintWords")){if(r)return e.hint.fromList(t,{words:r})}else if(e.hint.anyword)return e.hint.anyword(t,i)});e.registerHelper("hint","fromList",function(t,i){for(var r=t.getCursor(),n=t.getTokenAt(r),o=[],s=0;s<i.words.length;s++){var a=i.words[s];a.slice(0,n.string.length)==n.string&&o.push(a)}return o.length?{list:o,from:e.Pos(r.line,n.start),to:e.Pos(r.line,n.end)}:void 0});e.commands.autocomplete=e.showHint;var l={hint:e.hint.auto,completeSingle:!0,alignWithWord:!0,closeCharacters:/[\s()\[\]{};:>,]/,closeOnUnfocus:!0,completeOnSingleClick:!1,container:null,customKeys:null,extraKeys:null};e.defineOption("hintOptions",null)})},{"../../lib/codemirror":14}],12:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";e.runMode=function(t,i,r,n){var o=e.getMode(e.defaults,i),s=/MSIE \d/.test(navigator.userAgent),a=s&&(null==document.documentMode||document.documentMode<9);if(1==r.nodeType){var l=n&&n.tabSize||e.defaults.tabSize,u=r,p=0;u.innerHTML="";r=function(e,t){if("\n"!=e){for(var i="",r=0;;){var n=e.indexOf(" ",r);if(-1==n){i+=e.slice(r);p+=e.length-r;break}p+=n-r;i+=e.slice(r,n);var o=l-p%l;p+=o;for(var s=0;o>s;++s)i+=" ";r=n+1}if(t){var c=u.appendChild(document.createElement("span"));c.className="cm-"+t.replace(/ +/g," cm-");c.appendChild(document.createTextNode(i))}else u.appendChild(document.createTextNode(i))}else{u.appendChild(document.createTextNode(a?"\r":e));p=0}}}for(var c=e.splitLines(t),d=n&&n.state||e.startState(o),f=0,h=c.length;h>f;++f){f&&r("\n");var E=new e.StringStream(c[f]);!E.string&&o.blankLine&&o.blankLine(d);for(;!E.eol();){var m=o.token(E,d);r(E.current(),m,f,E.start,d);E.start=E.pos}}}})},{"../../lib/codemirror":14}],13:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e,t,n,o){this.atOccurrence=!1;this.doc=e;null==o&&"string"==typeof t&&(o=!1);n=n?e.clipPos(n):r(0,0);this.pos={from:n,to:n};if("string"!=typeof t){t.global||(t=new RegExp(t.source,t.ignoreCase?"ig":"g"));this.matches=function(i,n){if(i){t.lastIndex=0;for(var o,s,a=e.getLine(n.line).slice(0,n.ch),l=0;;){t.lastIndex=l;var u=t.exec(a);if(!u)break;o=u;s=o.index;l=o.index+(o[0].length||1);if(l==a.length)break}var p=o&&o[0].length||0;p||(0==s&&0==a.length?o=void 0:s!=e.getLine(n.line).length&&p++)}else{t.lastIndex=n.ch;var a=e.getLine(n.line),o=t.exec(a),p=o&&o[0].length||0,s=o&&o.index;s+p==a.length||p||(p=1)}return o&&p?{from:r(n.line,s),to:r(n.line,s+p),match:o}:void 0}}else{var s=t;o&&(t=t.toLowerCase());var a=o?function(e){return e.toLowerCase()}:function(e){return e},l=t.split("\n");if(1==l.length)this.matches=t.length?function(n,o){if(n){var l=e.getLine(o.line).slice(0,o.ch),u=a(l),p=u.lastIndexOf(t);if(p>-1){p=i(l,u,p);return{from:r(o.line,p),to:r(o.line,p+s.length)}}}else{var l=e.getLine(o.line).slice(o.ch),u=a(l),p=u.indexOf(t);if(p>-1){p=i(l,u,p)+o.ch;return{from:r(o.line,p),to:r(o.line,p+s.length)}}}}:function(){};else{var u=s.split("\n");this.matches=function(t,i){var n=l.length-1;if(t){if(i.line-(l.length-1)<e.firstLine())return;if(a(e.getLine(i.line).slice(0,u[n].length))!=l[l.length-1])return;for(var o=r(i.line,u[n].length),s=i.line-1,p=n-1;p>=1;--p,--s)if(l[p]!=a(e.getLine(s)))return;var c=e.getLine(s),d=c.length-u[0].length;if(a(c.slice(d))!=l[0])return;return{from:r(s,d),to:o}}if(!(i.line+(l.length-1)>e.lastLine())){var c=e.getLine(i.line),d=c.length-u[0].length;if(a(c.slice(d))==l[0]){for(var f=r(i.line,d),s=i.line+1,p=1;n>p;++p,++s)if(l[p]!=a(e.getLine(s)))return;if(a(e.getLine(s).slice(0,u[n].length))==l[n])return{from:f,to:r(s,u[n].length)}}}}}}}function i(e,t,i){if(e.length==t.length)return i;for(var r=Math.min(i,e.length);;){var n=e.slice(0,r).toLowerCase().length;if(i>n)++r;else{if(!(n>i))return r;--r}}}var r=e.Pos;t.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(e){function t(e){var t=r(e,0);i.pos={from:t,to:t};i.atOccurrence=!1;return!1}for(var i=this,n=this.doc.clipPos(e?this.pos.from:this.pos.to);;){if(this.pos=this.matches(e,n)){this.atOccurrence=!0;return this.pos.match||!0}if(e){if(!n.line)return t(0);n=r(n.line-1,this.doc.getLine(n.line-1).length)}else{var o=this.doc.lineCount();if(n.line==o-1)return t(o);n=r(n.line+1,0)}}},from:function(){return this.atOccurrence?this.pos.from:void 0},to:function(){return this.atOccurrence?this.pos.to:void 0},replace:function(t){if(this.atOccurrence){var i=e.splitLines(t);this.doc.replaceRange(i,this.pos.from,this.pos.to);this.pos.to=r(this.pos.from.line+i.length-1,i[i.length-1].length+(1==i.length?this.pos.from.ch:0))}}};e.defineExtension("getSearchCursor",function(e,i,r){return new t(this.doc,e,i,r)});e.defineDocExtension("getSearchCursor",function(e,i,r){return new t(this,e,i,r)});e.defineExtension("selectMatches",function(t,i){for(var r,n=[],o=this.getSearchCursor(t,this.getCursor("from"),i);(r=o.findNext())&&!(e.cmpPos(o.to(),this.getCursor("to"))>0);)n.push({anchor:o.from(),head:o.to()});n.length&&this.setSelections(n,0)})})},{"../../lib/codemirror":14}],14:[function(t,i,r){(function(t){if("object"==typeof r&&"object"==typeof i)i.exports=t();else{if("function"==typeof e&&e.amd)return e([],t);this.CodeMirror=t()}})(function(){"use strict";function e(i,r){if(!(this instanceof e))return new e(i,r);this.options=r=r?yo(r):{};yo(Us,r,!1);f(r);var n=r.value;"string"==typeof n&&(n=new ua(n,r.mode));this.doc=n;var o=this.display=new t(i,n);o.wrapper.CodeMirror=this;u(this);a(this);r.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap");r.autofocus&&!Es&&Oi(this);g(this);this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,draggingText:!1,highlight:new go,keySeq:null};ns&&11>os&&setTimeout(Ao(bi,this,!0),20);wi(this);Go();ni(this);this.curOp.forceUpdate=!0;Gn(this,n);r.autofocus&&!Es||wo()==o.input?setTimeout(Ao(rr,this),20):nr(this);for(var s in Vs)Vs.hasOwnProperty(s)&&Vs[s](this,r[s],Fs);L(this);for(var l=0;l<qs.length;++l)qs[l](this);si(this);ss&&r.lineWrapping&&"optimizelegibility"==getComputedStyle(o.lineDiv).textRendering&&(o.lineDiv.style.textRendering="auto")}function t(e,t){var i=this,r=i.input=bo("textarea",null,null,"position: absolute; padding: 0; width: 1px; height: 1em; outline: none");ss?r.style.width="1000px":r.setAttribute("wrap","off");hs&&(r.style.border="1px solid black");r.setAttribute("autocorrect","off");r.setAttribute("autocapitalize","off");r.setAttribute("spellcheck","false");i.inputDiv=bo("div",[r],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");i.scrollbarFiller=bo("div",null,"CodeMirror-scrollbar-filler");i.scrollbarFiller.setAttribute("not-content","true");i.gutterFiller=bo("div",null,"CodeMirror-gutter-filler");i.gutterFiller.setAttribute("not-content","true");i.lineDiv=bo("div",null,"CodeMirror-code");i.selectionDiv=bo("div",null,null,"position: relative; z-index: 1");i.cursorDiv=bo("div",null,"CodeMirror-cursors");i.measure=bo("div",null,"CodeMirror-measure");i.lineMeasure=bo("div",null,"CodeMirror-measure");i.lineSpace=bo("div",[i.measure,i.lineMeasure,i.selectionDiv,i.cursorDiv,i.lineDiv],null,"position: relative; outline: none");i.mover=bo("div",[bo("div",[i.lineSpace],"CodeMirror-lines")],null,"position: relative");i.sizer=bo("div",[i.mover],"CodeMirror-sizer");i.sizerWidth=null;i.heightForcer=bo("div",null,null,"position: absolute; height: "+xa+"px; width: 1px;");i.gutters=bo("div",null,"CodeMirror-gutters");i.lineGutter=null;i.scroller=bo("div",[i.sizer,i.heightForcer,i.gutters],"CodeMirror-scroll");i.scroller.setAttribute("tabIndex","-1");i.wrapper=bo("div",[i.inputDiv,i.scrollbarFiller,i.gutterFiller,i.scroller],"CodeMirror");if(ns&&8>os){i.gutters.style.zIndex=-1;i.scroller.style.paddingRight=0}hs&&(r.style.width="0px");ss||(i.scroller.draggable=!0);if(cs){i.inputDiv.style.height="1px";i.inputDiv.style.position="absolute"}e&&(e.appendChild?e.appendChild(i.wrapper):e(i.wrapper));i.viewFrom=i.viewTo=t.first;i.reportedViewFrom=i.reportedViewTo=t.first;i.view=[];i.renderedView=null;i.externalMeasured=null;i.viewOffset=0;i.lastWrapHeight=i.lastWrapWidth=0;i.updateLineNumbers=null;i.nativeBarWidth=i.barHeight=i.barWidth=0;i.scrollbarsClipped=!1;i.lineNumWidth=i.lineNumInnerWidth=i.lineNumChars=null;i.prevInput="";i.alignWidgets=!1;i.pollingFast=!1;i.poll=new go;i.cachedCharWidth=i.cachedTextHeight=i.cachedPaddingH=null;i.inaccurateSelection=!1;i.maxLine=null;i.maxLineLength=0;i.maxLineChanged=!1;i.wheelDX=i.wheelDY=i.wheelStartX=i.wheelStartY=null;i.shift=!1;i.selForContextMenu=null}function i(t){t.doc.mode=e.getMode(t.options,t.doc.modeOption);r(t)}function r(e){e.doc.iter(function(e){e.stateAfter&&(e.stateAfter=null);e.styles&&(e.styles=null)});e.doc.frontier=e.doc.first;yt(e,100);e.state.modeGen++;e.curOp&&xi(e)}function n(e){if(e.options.lineWrapping){_a(e.display.wrapper,"CodeMirror-wrap");e.display.sizer.style.minWidth="";e.display.sizerWidth=null}else{wa(e.display.wrapper,"CodeMirror-wrap");d(e)}s(e);xi(e);qt(e);setTimeout(function(){v(e)},100)}function o(e){var t=ii(e.display),i=e.options.lineWrapping,r=i&&Math.max(5,e.display.scroller.clientWidth/ri(e.display)-3);return function(n){if(un(e.doc,n))return 0;var o=0;if(n.widgets)for(var s=0;s<n.widgets.length;s++)n.widgets[s].height&&(o+=n.widgets[s].height);return i?o+(Math.ceil(n.text.length/r)||1)*t:o+t}}function s(e){var t=e.doc,i=o(e);t.iter(function(e){var t=i(e);t!=e.height&&Fn(e,t)})}function a(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-");qt(e)}function l(e){u(e);xi(e);setTimeout(function(){T(e) },20)}function u(e){var t=e.display.gutters,i=e.options.gutters;Oo(t);for(var r=0;r<i.length;++r){var n=i[r],o=t.appendChild(bo("div",null,"CodeMirror-gutter "+n));if("CodeMirror-linenumbers"==n){e.display.lineGutter=o;o.style.width=(e.display.lineNumWidth||1)+"px"}}t.style.display=r?"":"none";p(e)}function p(e){var t=e.display.gutters.offsetWidth;e.display.sizer.style.marginLeft=t+"px"}function c(e){if(0==e.height)return 0;for(var t,i=e.text.length,r=e;t=tn(r);){var n=t.find(0,!0);r=n.from.line;i+=n.from.ch-n.to.ch}r=e;for(;t=rn(r);){var n=t.find(0,!0);i-=r.text.length-n.from.ch;r=n.to.line;i+=r.text.length-n.to.ch}return i}function d(e){var t=e.display,i=e.doc;t.maxLine=Bn(i,i.first);t.maxLineLength=c(t.maxLine);t.maxLineChanged=!0;i.iter(function(e){var i=c(e);if(i>t.maxLineLength){t.maxLineLength=i;t.maxLine=e}})}function f(e){var t=To(e.gutters,"CodeMirror-linenumbers");if(-1==t&&e.lineNumbers)e.gutters=e.gutters.concat(["CodeMirror-linenumbers"]);else if(t>-1&&!e.lineNumbers){e.gutters=e.gutters.slice(0);e.gutters.splice(t,1)}}function h(e){var t=e.display,i=t.gutters.offsetWidth,r=Math.round(e.doc.height+bt(e.display));return{clientHeight:t.scroller.clientHeight,viewHeight:t.wrapper.clientHeight,scrollWidth:t.scroller.scrollWidth,clientWidth:t.scroller.clientWidth,viewWidth:t.wrapper.clientWidth,barLeft:e.options.fixedGutter?i:0,docHeight:r,scrollHeight:r+Pt(e)+t.barHeight,nativeBarWidth:t.nativeBarWidth,gutterWidth:i}}function E(e,t,i){this.cm=i;var r=this.vert=bo("div",[bo("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),n=this.horiz=bo("div",[bo("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");e(r);e(n);Ea(r,"scroll",function(){r.clientHeight&&t(r.scrollTop,"vertical")});Ea(n,"scroll",function(){n.clientWidth&&t(n.scrollLeft,"horizontal")});this.checkedOverlay=!1;ns&&8>os&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")}function m(){}function g(t){if(t.display.scrollbars){t.display.scrollbars.clear();t.display.scrollbars.addClass&&wa(t.display.wrapper,t.display.scrollbars.addClass)}t.display.scrollbars=new e.scrollbarModel[t.options.scrollbarStyle](function(e){t.display.wrapper.insertBefore(e,t.display.scrollbarFiller);Ea(e,"mousedown",function(){t.state.focused&&setTimeout(Ao(Oi,t),0)});e.setAttribute("not-content","true")},function(e,i){"horizontal"==i?zi(t,e):qi(t,e)},t);t.display.scrollbars.addClass&&_a(t.display.wrapper,t.display.scrollbars.addClass)}function v(e,t){t||(t=h(e));var i=e.display.barWidth,r=e.display.barHeight;x(e,t);for(var n=0;4>n&&i!=e.display.barWidth||r!=e.display.barHeight;n++){i!=e.display.barWidth&&e.options.lineWrapping&&P(e);x(e,h(e));i=e.display.barWidth;r=e.display.barHeight}}function x(e,t){var i=e.display,r=i.scrollbars.update(t);i.sizer.style.paddingRight=(i.barWidth=r.right)+"px";i.sizer.style.paddingBottom=(i.barHeight=r.bottom)+"px";if(r.right&&r.bottom){i.scrollbarFiller.style.display="block";i.scrollbarFiller.style.height=r.bottom+"px";i.scrollbarFiller.style.width=r.right+"px"}else i.scrollbarFiller.style.display="";if(r.bottom&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter){i.gutterFiller.style.display="block";i.gutterFiller.style.height=r.bottom+"px";i.gutterFiller.style.width=t.gutterWidth+"px"}else i.gutterFiller.style.display=""}function N(e,t,i){var r=i&&null!=i.top?Math.max(0,i.top):e.scroller.scrollTop;r=Math.floor(r-Rt(e));var n=i&&null!=i.bottom?i.bottom:r+e.wrapper.clientHeight,o=jn(t,r),s=jn(t,n);if(i&&i.ensure){var a=i.ensure.from.line,l=i.ensure.to.line;if(o>a){o=a;s=jn(t,Wn(Bn(t,a))+e.wrapper.clientHeight)}else if(Math.min(l,t.lastLine())>=s){o=jn(t,Wn(Bn(t,l))-e.wrapper.clientHeight);s=l}}return{from:o,to:Math.max(s,o+1)}}function T(e){var t=e.display,i=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var r=y(t)-t.scroller.scrollLeft+e.doc.scrollLeft,n=t.gutters.offsetWidth,o=r+"px",s=0;s<i.length;s++)if(!i[s].hidden){e.options.fixedGutter&&i[s].gutter&&(i[s].gutter.style.left=o);var a=i[s].alignable;if(a)for(var l=0;l<a.length;l++)a[l].style.left=o}e.options.fixedGutter&&(t.gutters.style.left=r+n+"px")}}function L(e){if(!e.options.lineNumbers)return!1;var t=e.doc,i=I(e.options,t.first+t.size-1),r=e.display;if(i.length!=r.lineNumChars){var n=r.measure.appendChild(bo("div",[bo("div",i)],"CodeMirror-linenumber CodeMirror-gutter-elt")),o=n.firstChild.offsetWidth,s=n.offsetWidth-o;r.lineGutter.style.width="";r.lineNumInnerWidth=Math.max(o,r.lineGutter.offsetWidth-s);r.lineNumWidth=r.lineNumInnerWidth+s;r.lineNumChars=r.lineNumInnerWidth?i.length:-1;r.lineGutter.style.width=r.lineNumWidth+"px";p(e);return!0}return!1}function I(e,t){return String(e.lineNumberFormatter(t+e.firstLineNumber))}function y(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function A(e,t,i){var r=e.display;this.viewport=t;this.visible=N(r,e.doc,t);this.editorIsHidden=!r.wrapper.offsetWidth;this.wrapperHeight=r.wrapper.clientHeight;this.wrapperWidth=r.wrapper.clientWidth;this.oldDisplayWidth=Dt(e);this.force=i;this.dims=w(e)}function S(e){var t=e.display;if(!t.scrollbarsClipped&&t.scroller.offsetWidth){t.nativeBarWidth=t.scroller.offsetWidth-t.scroller.clientWidth;t.heightForcer.style.height=Pt(e)+"px";t.sizer.style.marginBottom=-t.nativeBarWidth+"px";t.sizer.style.borderRightWidth=Pt(e)+"px";t.scrollbarsClipped=!0}}function C(e,t){var i=e.display,r=e.doc;if(t.editorIsHidden){Ti(e);return!1}if(!t.force&&t.visible.from>=i.viewFrom&&t.visible.to<=i.viewTo&&(null==i.updateLineNumbers||i.updateLineNumbers>=i.viewTo)&&i.renderedView==i.view&&0==Ai(e))return!1;if(L(e)){Ti(e);t.dims=w(e)}var n=r.first+r.size,o=Math.max(t.visible.from-e.options.viewportMargin,r.first),s=Math.min(n,t.visible.to+e.options.viewportMargin);i.viewFrom<o&&o-i.viewFrom<20&&(o=Math.max(r.first,i.viewFrom));i.viewTo>s&&i.viewTo-s<20&&(s=Math.min(n,i.viewTo));if(Ls){o=an(e.doc,o);s=ln(e.doc,s)}var a=o!=i.viewFrom||s!=i.viewTo||i.lastWrapHeight!=t.wrapperHeight||i.lastWrapWidth!=t.wrapperWidth;yi(e,o,s);i.viewOffset=Wn(Bn(e.doc,i.viewFrom));e.display.mover.style.top=i.viewOffset+"px";var l=Ai(e);if(!a&&0==l&&!t.force&&i.renderedView==i.view&&(null==i.updateLineNumbers||i.updateLineNumbers>=i.viewTo))return!1;var u=wo();l>4&&(i.lineDiv.style.display="none");_(e,i.updateLineNumbers,t.dims);l>4&&(i.lineDiv.style.display="");i.renderedView=i.view;u&&wo()!=u&&u.offsetHeight&&u.focus();Oo(i.cursorDiv);Oo(i.selectionDiv);i.gutters.style.height=0;if(a){i.lastWrapHeight=t.wrapperHeight;i.lastWrapWidth=t.wrapperWidth;yt(e,400)}i.updateLineNumbers=null;return!0}function R(e,t){for(var i=t.force,r=t.viewport,n=!0;;n=!1){if(n&&e.options.lineWrapping&&t.oldDisplayWidth!=Dt(e))i=!0;else{i=!1;r&&null!=r.top&&(r={top:Math.min(e.doc.height+bt(e.display)-wt(e),r.top)});t.visible=N(e.display,e.doc,r);if(t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)break}if(!C(e,t))break;P(e);var o=h(e);Nt(e);O(e,o);v(e,o)}po(e,"update",e);if(e.display.viewFrom!=e.display.reportedViewFrom||e.display.viewTo!=e.display.reportedViewTo){po(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo);e.display.reportedViewFrom=e.display.viewFrom;e.display.reportedViewTo=e.display.viewTo}}function b(e,t){var i=new A(e,t);if(C(e,i)){P(e);R(e,i);var r=h(e);Nt(e);O(e,r);v(e,r)}}function O(e,t){e.display.sizer.style.minHeight=t.docHeight+"px";var i=t.docHeight+e.display.barHeight;e.display.heightForcer.style.top=i+"px";e.display.gutters.style.height=Math.max(i+Pt(e),t.clientHeight)+"px"}function P(e){for(var t=e.display,i=t.lineDiv.offsetTop,r=0;r<t.view.length;r++){var n,o=t.view[r];if(!o.hidden){if(ns&&8>os){var s=o.node.offsetTop+o.node.offsetHeight;n=s-i;i=s}else{var a=o.node.getBoundingClientRect();n=a.bottom-a.top}var l=o.line.height-n;2>n&&(n=ii(t));if(l>.001||-.001>l){Fn(o.line,n);D(o.line);if(o.rest)for(var u=0;u<o.rest.length;u++)D(o.rest[u])}}}}function D(e){if(e.widgets)for(var t=0;t<e.widgets.length;++t)e.widgets[t].height=e.widgets[t].node.offsetHeight}function w(e){for(var t=e.display,i={},r={},n=t.gutters.clientLeft,o=t.gutters.firstChild,s=0;o;o=o.nextSibling,++s){i[e.options.gutters[s]]=o.offsetLeft+o.clientLeft+n;r[e.options.gutters[s]]=o.clientWidth}return{fixedPos:y(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:i,gutterWidth:r,wrapperWidth:t.wrapper.clientWidth}}function _(e,t,i){function r(t){var i=t.nextSibling;ss&&ms&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t);return i}for(var n=e.display,o=e.options.lineNumbers,s=n.lineDiv,a=s.firstChild,l=n.view,u=n.viewFrom,p=0;p<l.length;p++){var c=l[p];if(c.hidden);else if(c.node){for(;a!=c.node;)a=r(a);var d=o&&null!=t&&u>=t&&c.lineNumber;if(c.changes){To(c.changes,"gutter")>-1&&(d=!1);M(e,c,u,i)}if(d){Oo(c.lineNumber);c.lineNumber.appendChild(document.createTextNode(I(e.options,u)))}a=c.node.nextSibling}else{var f=j(e,c,u,i);s.insertBefore(f,a)}u+=c.size}for(;a;)a=r(a)}function M(e,t,i,r){for(var n=0;n<t.changes.length;n++){var o=t.changes[n];"text"==o?U(e,t):"gutter"==o?F(e,t,i,r):"class"==o?V(t):"widget"==o&&H(t,r)}t.changes=null}function k(e){if(e.node==e.text){e.node=bo("div",null,null,"position: relative");e.text.parentNode&&e.text.parentNode.replaceChild(e.node,e.text);e.node.appendChild(e.text);ns&&8>os&&(e.node.style.zIndex=2)}return e.node}function G(e){var t=e.bgClass?e.bgClass+" "+(e.line.bgClass||""):e.line.bgClass;t&&(t+=" CodeMirror-linebackground");if(e.background)if(t)e.background.className=t;else{e.background.parentNode.removeChild(e.background);e.background=null}else if(t){var i=k(e);e.background=i.insertBefore(bo("div",null,t),i.firstChild)}}function B(e,t){var i=e.display.externalMeasured;if(i&&i.line==t.line){e.display.externalMeasured=null;t.measure=i.measure;return i.built}return An(e,t)}function U(e,t){var i=t.text.className,r=B(e,t);t.text==t.node&&(t.node=r.pre);t.text.parentNode.replaceChild(r.pre,t.text);t.text=r.pre;if(r.bgClass!=t.bgClass||r.textClass!=t.textClass){t.bgClass=r.bgClass;t.textClass=r.textClass;V(t)}else i&&(t.text.className=i)}function V(e){G(e);e.line.wrapClass?k(e).className=e.line.wrapClass:e.node!=e.text&&(e.node.className="");var t=e.textClass?e.textClass+" "+(e.line.textClass||""):e.line.textClass;e.text.className=t||""}function F(e,t,i,r){if(t.gutter){t.node.removeChild(t.gutter);t.gutter=null}var n=t.line.gutterMarkers;if(e.options.lineNumbers||n){var o=k(t),s=t.gutter=o.insertBefore(bo("div",null,"CodeMirror-gutter-wrapper","left: "+(e.options.fixedGutter?r.fixedPos:-r.gutterTotalWidth)+"px; width: "+r.gutterTotalWidth+"px"),t.text);t.line.gutterClass&&(s.className+=" "+t.line.gutterClass);!e.options.lineNumbers||n&&n["CodeMirror-linenumbers"]||(t.lineNumber=s.appendChild(bo("div",I(e.options,i),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+r.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+e.display.lineNumInnerWidth+"px")));if(n)for(var a=0;a<e.options.gutters.length;++a){var l=e.options.gutters[a],u=n.hasOwnProperty(l)&&n[l];u&&s.appendChild(bo("div",[u],"CodeMirror-gutter-elt","left: "+r.gutterLeft[l]+"px; width: "+r.gutterWidth[l]+"px"))}}}function H(e,t){e.alignable&&(e.alignable=null);for(var i,r=e.node.firstChild;r;r=i){var i=r.nextSibling;"CodeMirror-linewidget"==r.className&&e.node.removeChild(r)}W(e,t)}function j(e,t,i,r){var n=B(e,t);t.text=t.node=n.pre;n.bgClass&&(t.bgClass=n.bgClass);n.textClass&&(t.textClass=n.textClass);V(t);F(e,t,i,r);W(t,r);return t.node}function W(e,t){q(e.line,e,t,!0);if(e.rest)for(var i=0;i<e.rest.length;i++)q(e.rest[i],e,t,!1)}function q(e,t,i,r){if(e.widgets)for(var n=k(t),o=0,s=e.widgets;o<s.length;++o){var a=s[o],l=bo("div",[a.node],"CodeMirror-linewidget");a.handleMouseEvents||l.setAttribute("cm-ignore-events","true");z(a,l,t,i);r&&a.above?n.insertBefore(l,t.gutter||t.text):n.appendChild(l);po(a,"redraw")}}function z(e,t,i,r){if(e.noHScroll){(i.alignable||(i.alignable=[])).push(t);var n=r.wrapperWidth;t.style.left=r.fixedPos+"px";if(!e.coverGutter){n-=r.gutterTotalWidth;t.style.paddingLeft=r.gutterTotalWidth+"px"}t.style.width=n+"px"}if(e.coverGutter){t.style.zIndex=5;t.style.position="relative";e.noHScroll||(t.style.marginLeft=-r.gutterTotalWidth+"px")}}function X(e){return Is(e.line,e.ch)}function Y(e,t){return ys(e,t)<0?t:e}function K(e,t){return ys(e,t)<0?e:t}function $(e,t){this.ranges=e;this.primIndex=t}function Q(e,t){this.anchor=e;this.head=t}function Z(e,t){var i=e[t];e.sort(function(e,t){return ys(e.from(),t.from())});t=To(e,i);for(var r=1;r<e.length;r++){var n=e[r],o=e[r-1];if(ys(o.to(),n.from())>=0){var s=K(o.from(),n.from()),a=Y(o.to(),n.to()),l=o.empty()?n.from()==n.head:o.from()==o.head;t>=r&&--t;e.splice(--r,2,new Q(l?a:s,l?s:a))}}return new $(e,t)}function J(e,t){return new $([new Q(e,t||e)],0)}function et(e,t){return Math.max(e.first,Math.min(t,e.first+e.size-1))}function tt(e,t){if(t.line<e.first)return Is(e.first,0);var i=e.first+e.size-1;return t.line>i?Is(i,Bn(e,i).text.length):it(t,Bn(e,t.line).text.length)}function it(e,t){var i=e.ch;return null==i||i>t?Is(e.line,t):0>i?Is(e.line,0):e}function rt(e,t){return t>=e.first&&t<e.first+e.size}function nt(e,t){for(var i=[],r=0;r<t.length;r++)i[r]=tt(e,t[r]);return i}function ot(e,t,i,r){if(e.cm&&e.cm.display.shift||e.extend){var n=t.anchor;if(r){var o=ys(i,n)<0;if(o!=ys(r,n)<0){n=i;i=r}else o!=ys(i,r)<0&&(i=r)}return new Q(n,i)}return new Q(r||i,i)}function st(e,t,i,r){dt(e,new $([ot(e,e.sel.primary(),t,i)],0),r)}function at(e,t,i){for(var r=[],n=0;n<e.sel.ranges.length;n++)r[n]=ot(e,e.sel.ranges[n],t[n],null);var o=Z(r,e.sel.primIndex);dt(e,o,i)}function lt(e,t,i,r){var n=e.sel.ranges.slice(0);n[t]=i;dt(e,Z(n,e.sel.primIndex),r)}function ut(e,t,i,r){dt(e,J(t,i),r)}function pt(e,t){var i={ranges:t.ranges,update:function(t){this.ranges=[];for(var i=0;i<t.length;i++)this.ranges[i]=new Q(tt(e,t[i].anchor),tt(e,t[i].head))}};ga(e,"beforeSelectionChange",e,i);e.cm&&ga(e.cm,"beforeSelectionChange",e.cm,i);return i.ranges!=t.ranges?Z(i.ranges,i.ranges.length-1):t}function ct(e,t,i){var r=e.history.done,n=No(r);if(n&&n.ranges){r[r.length-1]=t;ft(e,t,i)}else dt(e,t,i)}function dt(e,t,i){ft(e,t,i);Zn(e,e.sel,e.cm?e.cm.curOp.id:0/0,i)}function ft(e,t,i){(Eo(e,"beforeSelectionChange")||e.cm&&Eo(e.cm,"beforeSelectionChange"))&&(t=pt(e,t));var r=i&&i.bias||(ys(t.primary().head,e.sel.primary().head)<0?-1:1);ht(e,mt(e,t,r,!0));i&&i.scroll===!1||!e.cm||yr(e.cm)}function ht(e,t){if(!t.equals(e.sel)){e.sel=t;if(e.cm){e.cm.curOp.updateInput=e.cm.curOp.selectionChanged=!0;ho(e.cm)}po(e,"cursorActivity",e)}}function Et(e){ht(e,mt(e,e.sel,null,!1),Ta)}function mt(e,t,i,r){for(var n,o=0;o<t.ranges.length;o++){var s=t.ranges[o],a=gt(e,s.anchor,i,r),l=gt(e,s.head,i,r);if(n||a!=s.anchor||l!=s.head){n||(n=t.ranges.slice(0,o));n[o]=new Q(a,l)}}return n?Z(n,t.primIndex):t}function gt(e,t,i,r){var n=!1,o=t,s=i||1;e.cantEdit=!1;e:for(;;){var a=Bn(e,o.line);if(a.markedSpans)for(var l=0;l<a.markedSpans.length;++l){var u=a.markedSpans[l],p=u.marker;if((null==u.from||(p.inclusiveLeft?u.from<=o.ch:u.from<o.ch))&&(null==u.to||(p.inclusiveRight?u.to>=o.ch:u.to>o.ch))){if(r){ga(p,"beforeCursorEnter");if(p.explicitlyCleared){if(a.markedSpans){--l;continue}break}}if(!p.atomic)continue;var c=p.find(0>s?-1:1);if(0==ys(c,o)){c.ch+=s;c.ch<0?c=c.line>e.first?tt(e,Is(c.line-1)):null:c.ch>a.text.length&&(c=c.line<e.first+e.size-1?Is(c.line+1,0):null);if(!c){if(n){if(!r)return gt(e,t,i,!0);e.cantEdit=!0;return Is(e.first,0)}n=!0;c=t;s=-s}}o=c;continue e}}return o}}function vt(e){for(var t=e.display,i=e.doc,r={},n=r.cursors=document.createDocumentFragment(),o=r.selection=document.createDocumentFragment(),s=0;s<i.sel.ranges.length;s++){var a=i.sel.ranges[s],l=a.empty();(l||e.options.showCursorWhenSelecting)&&Tt(e,a,n);l||Lt(e,a,o)}if(e.options.moveInputWithCursor){var u=Qt(e,i.sel.primary().head,"div"),p=t.wrapper.getBoundingClientRect(),c=t.lineDiv.getBoundingClientRect();r.teTop=Math.max(0,Math.min(t.wrapper.clientHeight-10,u.top+c.top-p.top));r.teLeft=Math.max(0,Math.min(t.wrapper.clientWidth-10,u.left+c.left-p.left))}return r}function xt(e,t){Po(e.display.cursorDiv,t.cursors);Po(e.display.selectionDiv,t.selection);if(null!=t.teTop){e.display.inputDiv.style.top=t.teTop+"px";e.display.inputDiv.style.left=t.teLeft+"px"}}function Nt(e){xt(e,vt(e))}function Tt(e,t,i){var r=Qt(e,t.head,"div",null,null,!e.options.singleCursorHeightPerLine),n=i.appendChild(bo("div"," ","CodeMirror-cursor"));n.style.left=r.left+"px";n.style.top=r.top+"px";n.style.height=Math.max(0,r.bottom-r.top)*e.options.cursorHeight+"px";if(r.other){var o=i.appendChild(bo("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));o.style.display="";o.style.left=r.other.left+"px";o.style.top=r.other.top+"px";o.style.height=.85*(r.other.bottom-r.other.top)+"px"}}function Lt(e,t,i){function r(e,t,i,r){0>t&&(t=0);t=Math.round(t);r=Math.round(r);a.appendChild(bo("div",null,"CodeMirror-selected","position: absolute; left: "+e+"px; top: "+t+"px; width: "+(null==i?p-e:i)+"px; height: "+(r-t)+"px"))}function n(t,i,n){function o(i,r){return $t(e,Is(t,i),"div",c,r)}var a,l,c=Bn(s,t),d=c.text.length;Ho(qn(c),i||0,null==n?d:n,function(e,t,s){var c,f,h,E=o(e,"left");if(e==t){c=E;f=h=E.left}else{c=o(t-1,"right");if("rtl"==s){var m=E;E=c;c=m}f=E.left;h=c.right}null==i&&0==e&&(f=u);if(c.top-E.top>3){r(f,E.top,null,E.bottom);f=u;E.bottom<c.top&&r(f,E.bottom,null,c.top)}null==n&&t==d&&(h=p);(!a||E.top<a.top||E.top==a.top&&E.left<a.left)&&(a=E);(!l||c.bottom>l.bottom||c.bottom==l.bottom&&c.right>l.right)&&(l=c);u+1>f&&(f=u);r(f,c.top,h-f,c.bottom)});return{start:a,end:l}}var o=e.display,s=e.doc,a=document.createDocumentFragment(),l=Ot(e.display),u=l.left,p=Math.max(o.sizerWidth,Dt(e)-o.sizer.offsetLeft)-l.right,c=t.from(),d=t.to();if(c.line==d.line)n(c.line,c.ch,d.ch);else{var f=Bn(s,c.line),h=Bn(s,d.line),E=on(f)==on(h),m=n(c.line,c.ch,E?f.text.length+1:null).end,g=n(d.line,E?0:null,d.ch).start;if(E)if(m.top<g.top-2){r(m.right,m.top,null,m.bottom);r(u,g.top,g.left,g.bottom)}else r(m.right,m.top,g.left-m.right,m.bottom);m.bottom<g.top&&r(u,m.bottom,null,g.top)}i.appendChild(a)}function It(e){if(e.state.focused){var t=e.display;clearInterval(t.blinker);var i=!0;t.cursorDiv.style.visibility="";e.options.cursorBlinkRate>0?t.blinker=setInterval(function(){t.cursorDiv.style.visibility=(i=!i)?"":"hidden"},e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}}function yt(e,t){e.doc.mode.startState&&e.doc.frontier<e.display.viewTo&&e.state.highlight.set(t,Ao(At,e))}function At(e){var t=e.doc;t.frontier<t.first&&(t.frontier=t.first);if(!(t.frontier>=e.display.viewTo)){var i=+new Date+e.options.workTime,r=Xs(t.mode,Ct(e,t.frontier)),n=[];t.iter(t.frontier,Math.min(t.first+t.size,e.display.viewTo+500),function(o){if(t.frontier>=e.display.viewFrom){var s=o.styles,a=Tn(e,o,r,!0);o.styles=a.styles;var l=o.styleClasses,u=a.classes;u?o.styleClasses=u:l&&(o.styleClasses=null);for(var p=!s||s.length!=o.styles.length||l!=u&&(!l||!u||l.bgClass!=u.bgClass||l.textClass!=u.textClass),c=0;!p&&c<s.length;++c)p=s[c]!=o.styles[c];p&&n.push(t.frontier);o.stateAfter=Xs(t.mode,r)}else{In(e,o.text,r);o.stateAfter=t.frontier%5==0?Xs(t.mode,r):null}++t.frontier;if(+new Date>i){yt(e,e.options.workDelay);return!0}});n.length&&fi(e,function(){for(var t=0;t<n.length;t++)Ni(e,n[t],"text")})}}function St(e,t,i){for(var r,n,o=e.doc,s=i?-1:t-(e.doc.mode.innerMode?1e3:100),a=t;a>s;--a){if(a<=o.first)return o.first;var l=Bn(o,a-1);if(l.stateAfter&&(!i||a<=o.frontier))return a;var u=ya(l.text,null,e.options.tabSize);if(null==n||r>u){n=a-1;r=u}}return n}function Ct(e,t,i){var r=e.doc,n=e.display;if(!r.mode.startState)return!0;var o=St(e,t,i),s=o>r.first&&Bn(r,o-1).stateAfter;s=s?Xs(r.mode,s):Ys(r.mode);r.iter(o,t,function(i){In(e,i.text,s);var a=o==t-1||o%5==0||o>=n.viewFrom&&o<n.viewTo;i.stateAfter=a?Xs(r.mode,s):null;++o});i&&(r.frontier=o);return s}function Rt(e){return e.lineSpace.offsetTop}function bt(e){return e.mover.offsetHeight-e.lineSpace.offsetHeight}function Ot(e){if(e.cachedPaddingH)return e.cachedPaddingH;var t=Po(e.measure,bo("pre","x")),i=window.getComputedStyle?window.getComputedStyle(t):t.currentStyle,r={left:parseInt(i.paddingLeft),right:parseInt(i.paddingRight)};isNaN(r.left)||isNaN(r.right)||(e.cachedPaddingH=r);return r}function Pt(e){return xa-e.display.nativeBarWidth}function Dt(e){return e.display.scroller.clientWidth-Pt(e)-e.display.barWidth}function wt(e){return e.display.scroller.clientHeight-Pt(e)-e.display.barHeight}function _t(e,t,i){var r=e.options.lineWrapping,n=r&&Dt(e);if(!t.measure.heights||r&&t.measure.width!=n){var o=t.measure.heights=[];if(r){t.measure.width=n;for(var s=t.text.firstChild.getClientRects(),a=0;a<s.length-1;a++){var l=s[a],u=s[a+1];Math.abs(l.bottom-u.bottom)>2&&o.push((l.bottom+u.top)/2-i.top)}}o.push(i.bottom-i.top)}}function Mt(e,t,i){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var r=0;r<e.rest.length;r++)if(e.rest[r]==t)return{map:e.measure.maps[r],cache:e.measure.caches[r]};for(var r=0;r<e.rest.length;r++)if(Hn(e.rest[r])>i)return{map:e.measure.maps[r],cache:e.measure.caches[r],before:!0}}function kt(e,t){t=on(t);var i=Hn(t),r=e.display.externalMeasured=new gi(e.doc,t,i);r.lineN=i;var n=r.built=An(e,r);r.text=n.pre;Po(e.display.lineMeasure,n.pre);return r}function Gt(e,t,i,r){return Vt(e,Ut(e,t),i,r)}function Bt(e,t){if(t>=e.display.viewFrom&&t<e.display.viewTo)return e.display.view[Li(e,t)];var i=e.display.externalMeasured;return i&&t>=i.lineN&&t<i.lineN+i.size?i:void 0}function Ut(e,t){var i=Hn(t),r=Bt(e,i);r&&!r.text?r=null:r&&r.changes&&M(e,r,i,w(e));r||(r=kt(e,t));var n=Mt(r,t,i);return{line:t,view:r,rect:null,map:n.map,cache:n.cache,before:n.before,hasHeights:!1}}function Vt(e,t,i,r,n){t.before&&(i=-1);var o,s=i+(r||"");if(t.cache.hasOwnProperty(s))o=t.cache[s];else{t.rect||(t.rect=t.view.text.getBoundingClientRect());if(!t.hasHeights){_t(e,t.view,t.rect);t.hasHeights=!0}o=Ft(e,t,i,r);o.bogus||(t.cache[s]=o)}return{left:o.left,right:o.right,top:n?o.rtop:o.top,bottom:n?o.rbottom:o.bottom}}function Ft(e,t,i,r){for(var n,o,s,a,l=t.map,u=0;u<l.length;u+=3){var p=l[u],c=l[u+1];if(p>i){o=0;s=1;a="left"}else if(c>i){o=i-p;s=o+1}else if(u==l.length-3||i==c&&l[u+3]>i){s=c-p;o=s-1;i>=c&&(a="right")}if(null!=o){n=l[u+2];p==c&&r==(n.insertLeft?"left":"right")&&(a=r);if("left"==r&&0==o)for(;u&&l[u-2]==l[u-3]&&l[u-1].insertLeft;){n=l[(u-=3)+2];a="left"}if("right"==r&&o==c-p)for(;u<l.length-3&&l[u+3]==l[u+4]&&!l[u+5].insertLeft;){n=l[(u+=3)+2];a="right"}break}}var d;if(3==n.nodeType){for(var u=0;4>u;u++){for(;o&&Ro(t.line.text.charAt(p+o));)--o;for(;c>p+s&&Ro(t.line.text.charAt(p+s));)++s;if(ns&&9>os&&0==o&&s==c-p)d=n.parentNode.getBoundingClientRect();else if(ns&&e.options.lineWrapping){var f=Ca(n,o,s).getClientRects();d=f.length?f["right"==r?f.length-1:0]:Rs}else d=Ca(n,o,s).getBoundingClientRect()||Rs;if(d.left||d.right||0==o)break;s=o;o-=1;a="right"}ns&&11>os&&(d=Ht(e.display.measure,d))}else{o>0&&(a=r="right");var f;d=e.options.lineWrapping&&(f=n.getClientRects()).length>1?f["right"==r?f.length-1:0]:n.getBoundingClientRect()}if(ns&&9>os&&!o&&(!d||!d.left&&!d.right)){var h=n.parentNode.getClientRects()[0];d=h?{left:h.left,right:h.left+ri(e.display),top:h.top,bottom:h.bottom}:Rs}for(var E=d.top-t.rect.top,m=d.bottom-t.rect.top,g=(E+m)/2,v=t.view.measure.heights,u=0;u<v.length-1&&!(g<v[u]);u++);var x=u?v[u-1]:0,N=v[u],T={left:("right"==a?d.right:d.left)-t.rect.left,right:("left"==a?d.left:d.right)-t.rect.left,top:x,bottom:N};d.left||d.right||(T.bogus=!0);if(!e.options.singleCursorHeightPerLine){T.rtop=E;T.rbottom=m}return T}function Ht(e,t){if(!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI||!Fo(e))return t;var i=screen.logicalXDPI/screen.deviceXDPI,r=screen.logicalYDPI/screen.deviceYDPI;return{left:t.left*i,right:t.right*i,top:t.top*r,bottom:t.bottom*r}}function jt(e){if(e.measure){e.measure.cache={};e.measure.heights=null;if(e.rest)for(var t=0;t<e.rest.length;t++)e.measure.caches[t]={}}}function Wt(e){e.display.externalMeasure=null;Oo(e.display.lineMeasure);for(var t=0;t<e.display.view.length;t++)jt(e.display.view[t])}function qt(e){Wt(e);e.display.cachedCharWidth=e.display.cachedTextHeight=e.display.cachedPaddingH=null;e.options.lineWrapping||(e.display.maxLineChanged=!0);e.display.lineNumChars=null}function zt(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft}function Xt(){return window.pageYOffset||(document.documentElement||document.body).scrollTop}function Yt(e,t,i,r){if(t.widgets)for(var n=0;n<t.widgets.length;++n)if(t.widgets[n].above){var o=dn(t.widgets[n]);i.top+=o;i.bottom+=o}if("line"==r)return i;r||(r="local");var s=Wn(t);"local"==r?s+=Rt(e.display):s-=e.display.viewOffset;if("page"==r||"window"==r){var a=e.display.lineSpace.getBoundingClientRect();s+=a.top+("window"==r?0:Xt());var l=a.left+("window"==r?0:zt());i.left+=l;i.right+=l}i.top+=s;i.bottom+=s;return i}function Kt(e,t,i){if("div"==i)return t;var r=t.left,n=t.top;if("page"==i){r-=zt();n-=Xt()}else if("local"==i||!i){var o=e.display.sizer.getBoundingClientRect();r+=o.left;n+=o.top}var s=e.display.lineSpace.getBoundingClientRect();return{left:r-s.left,top:n-s.top}}function $t(e,t,i,r,n){r||(r=Bn(e.doc,t.line));return Yt(e,r,Gt(e,r,t.ch,n),i)}function Qt(e,t,i,r,n,o){function s(t,s){var a=Vt(e,n,t,s?"right":"left",o);s?a.left=a.right:a.right=a.left;return Yt(e,r,a,i)}function a(e,t){var i=l[t],r=i.level%2;if(e==jo(i)&&t&&i.level<l[t-1].level){i=l[--t];e=Wo(i)-(i.level%2?0:1);r=!0}else if(e==Wo(i)&&t<l.length-1&&i.level<l[t+1].level){i=l[++t];e=jo(i)-i.level%2;r=!1}return r&&e==i.to&&e>i.from?s(e-1):s(e,r)}r=r||Bn(e.doc,t.line);n||(n=Ut(e,r));var l=qn(r),u=t.ch;if(!l)return s(u);var p=Qo(l,u),c=a(u,p);null!=Ha&&(c.other=a(u,Ha));return c}function Zt(e,t){var i=0,t=tt(e.doc,t);e.options.lineWrapping||(i=ri(e.display)*t.ch);var r=Bn(e.doc,t.line),n=Wn(r)+Rt(e.display);return{left:i,right:i,top:n,bottom:n+r.height}}function Jt(e,t,i,r){var n=Is(e,t);n.xRel=r;i&&(n.outside=!0);return n}function ei(e,t,i){var r=e.doc;i+=e.display.viewOffset;if(0>i)return Jt(r.first,0,!0,-1);var n=jn(r,i),o=r.first+r.size-1;if(n>o)return Jt(r.first+r.size-1,Bn(r,o).text.length,!0,1);0>t&&(t=0);for(var s=Bn(r,n);;){var a=ti(e,s,n,t,i),l=rn(s),u=l&&l.find(0,!0);if(!l||!(a.ch>u.from.ch||a.ch==u.from.ch&&a.xRel>0))return a;n=Hn(s=u.to.line)}}function ti(e,t,i,r,n){function o(r){var n=Qt(e,Is(i,r),"line",t,u);a=!0;if(s>n.bottom)return n.left-l;if(s<n.top)return n.left+l;a=!1;return n.left}var s=n-Wn(t),a=!1,l=2*e.display.wrapper.clientWidth,u=Ut(e,t),p=qn(t),c=t.text.length,d=qo(t),f=zo(t),h=o(d),E=a,m=o(f),g=a;if(r>m)return Jt(i,f,g,1);for(;;){if(p?f==d||f==Jo(t,d,1):1>=f-d){for(var v=h>r||m-r>=r-h?d:f,x=r-(v==d?h:m);Ro(t.text.charAt(v));)++v;var N=Jt(i,v,v==d?E:g,-1>x?-1:x>1?1:0);return N}var T=Math.ceil(c/2),L=d+T;if(p){L=d;for(var I=0;T>I;++I)L=Jo(t,L,1)}var y=o(L);if(y>r){f=L;m=y;(g=a)&&(m+=1e3);c=T}else{d=L;h=y;E=a;c-=T}}}function ii(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==As){As=bo("pre");for(var t=0;49>t;++t){As.appendChild(document.createTextNode("x"));As.appendChild(bo("br"))}As.appendChild(document.createTextNode("x"))}Po(e.measure,As);var i=As.offsetHeight/50;i>3&&(e.cachedTextHeight=i);Oo(e.measure);return i||1}function ri(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=bo("span","xxxxxxxxxx"),i=bo("pre",[t]);Po(e.measure,i);var r=t.getBoundingClientRect(),n=(r.right-r.left)/10;n>2&&(e.cachedCharWidth=n);return n||10}function ni(e){e.curOp={cm:e,viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,id:++Os};bs?bs.ops.push(e.curOp):e.curOp.ownsGroup=bs={ops:[e.curOp],delayedCallbacks:[]}}function oi(e){var t=e.delayedCallbacks,i=0;do{for(;i<t.length;i++)t[i]();for(var r=0;r<e.ops.length;r++){var n=e.ops[r];if(n.cursorActivityHandlers)for(;n.cursorActivityCalled<n.cursorActivityHandlers.length;)n.cursorActivityHandlers[n.cursorActivityCalled++](n.cm)}}while(i<t.length)}function si(e){var t=e.curOp,i=t.ownsGroup;if(i)try{oi(i)}finally{bs=null;for(var r=0;r<i.ops.length;r++)i.ops[r].cm.curOp=null;ai(i)}}function ai(e){for(var t=e.ops,i=0;i<t.length;i++)li(t[i]);for(var i=0;i<t.length;i++)ui(t[i]);for(var i=0;i<t.length;i++)pi(t[i]);for(var i=0;i<t.length;i++)ci(t[i]);for(var i=0;i<t.length;i++)di(t[i])}function li(e){var t=e.cm,i=t.display;S(t);e.updateMaxLine&&d(t);e.mustUpdate=e.viewChanged||e.forceUpdate||null!=e.scrollTop||e.scrollToPos&&(e.scrollToPos.from.line<i.viewFrom||e.scrollToPos.to.line>=i.viewTo)||i.maxLineChanged&&t.options.lineWrapping;e.update=e.mustUpdate&&new A(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function ui(e){e.updatedDisplay=e.mustUpdate&&C(e.cm,e.update)}function pi(e){var t=e.cm,i=t.display;e.updatedDisplay&&P(t);e.barMeasure=h(t);if(i.maxLineChanged&&!t.options.lineWrapping){e.adjustWidthTo=Gt(t,i.maxLine,i.maxLine.text.length).left+3;t.display.sizerWidth=e.adjustWidthTo;e.barMeasure.scrollWidth=Math.max(i.scroller.clientWidth,i.sizer.offsetLeft+e.adjustWidthTo+Pt(t)+t.display.barWidth);e.maxScrollLeft=Math.max(0,i.sizer.offsetLeft+e.adjustWidthTo-Dt(t))}(e.updatedDisplay||e.selectionChanged)&&(e.newSelectionNodes=vt(t))}function ci(e){var t=e.cm;if(null!=e.adjustWidthTo){t.display.sizer.style.minWidth=e.adjustWidthTo+"px";e.maxScrollLeft<t.doc.scrollLeft&&zi(t,Math.min(t.display.scroller.scrollLeft,e.maxScrollLeft),!0);t.display.maxLineChanged=!1}e.newSelectionNodes&&xt(t,e.newSelectionNodes);e.updatedDisplay&&O(t,e.barMeasure);(e.updatedDisplay||e.startHeight!=t.doc.height)&&v(t,e.barMeasure);e.selectionChanged&&It(t);t.state.focused&&e.updateInput&&bi(t,e.typing)}function di(e){var t=e.cm,i=t.display,r=t.doc;e.updatedDisplay&&R(t,e.update);null==i.wheelStartX||null==e.scrollTop&&null==e.scrollLeft&&!e.scrollToPos||(i.wheelStartX=i.wheelStartY=null);if(null!=e.scrollTop&&(i.scroller.scrollTop!=e.scrollTop||e.forceScroll)){r.scrollTop=Math.max(0,Math.min(i.scroller.scrollHeight-i.scroller.clientHeight,e.scrollTop));i.scrollbars.setScrollTop(r.scrollTop);i.scroller.scrollTop=r.scrollTop}if(null!=e.scrollLeft&&(i.scroller.scrollLeft!=e.scrollLeft||e.forceScroll)){r.scrollLeft=Math.max(0,Math.min(i.scroller.scrollWidth-Dt(t),e.scrollLeft));i.scrollbars.setScrollLeft(r.scrollLeft);i.scroller.scrollLeft=r.scrollLeft;T(t)}if(e.scrollToPos){var n=Nr(t,tt(r,e.scrollToPos.from),tt(r,e.scrollToPos.to),e.scrollToPos.margin);e.scrollToPos.isCursor&&t.state.focused&&xr(t,n)}var o=e.maybeHiddenMarkers,s=e.maybeUnhiddenMarkers;if(o)for(var a=0;a<o.length;++a)o[a].lines.length||ga(o[a],"hide");if(s)for(var a=0;a<s.length;++a)s[a].lines.length&&ga(s[a],"unhide");i.wrapper.offsetHeight&&(r.scrollTop=t.display.scroller.scrollTop);e.changeObjs&&ga(t,"changes",t,e.changeObjs)}function fi(e,t){if(e.curOp)return t();ni(e);try{return t()}finally{si(e)}}function hi(e,t){return function(){if(e.curOp)return t.apply(e,arguments);ni(e);try{return t.apply(e,arguments)}finally{si(e)}}}function Ei(e){return function(){if(this.curOp)return e.apply(this,arguments);ni(this);try{return e.apply(this,arguments)}finally{si(this)}}}function mi(e){return function(){var t=this.cm;if(!t||t.curOp)return e.apply(this,arguments);ni(t);try{return e.apply(this,arguments)}finally{si(t)}}}function gi(e,t,i){this.line=t;this.rest=sn(t);this.size=this.rest?Hn(No(this.rest))-i+1:1;this.node=this.text=null;this.hidden=un(e,t)}function vi(e,t,i){for(var r,n=[],o=t;i>o;o=r){var s=new gi(e.doc,Bn(e.doc,o),o);r=o+s.size;n.push(s)}return n}function xi(e,t,i,r){null==t&&(t=e.doc.first);null==i&&(i=e.doc.first+e.doc.size);r||(r=0);var n=e.display;r&&i<n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>t)&&(n.updateLineNumbers=t);e.curOp.viewChanged=!0;if(t>=n.viewTo)Ls&&an(e.doc,t)<n.viewTo&&Ti(e);else if(i<=n.viewFrom)if(Ls&&ln(e.doc,i+r)>n.viewFrom)Ti(e); else{n.viewFrom+=r;n.viewTo+=r}else if(t<=n.viewFrom&&i>=n.viewTo)Ti(e);else if(t<=n.viewFrom){var o=Ii(e,i,i+r,1);if(o){n.view=n.view.slice(o.index);n.viewFrom=o.lineN;n.viewTo+=r}else Ti(e)}else if(i>=n.viewTo){var o=Ii(e,t,t,-1);if(o){n.view=n.view.slice(0,o.index);n.viewTo=o.lineN}else Ti(e)}else{var s=Ii(e,t,t,-1),a=Ii(e,i,i+r,1);if(s&&a){n.view=n.view.slice(0,s.index).concat(vi(e,s.lineN,a.lineN)).concat(n.view.slice(a.index));n.viewTo+=r}else Ti(e)}var l=n.externalMeasured;l&&(i<l.lineN?l.lineN+=r:t<l.lineN+l.size&&(n.externalMeasured=null))}function Ni(e,t,i){e.curOp.viewChanged=!0;var r=e.display,n=e.display.externalMeasured;n&&t>=n.lineN&&t<n.lineN+n.size&&(r.externalMeasured=null);if(!(t<r.viewFrom||t>=r.viewTo)){var o=r.view[Li(e,t)];if(null!=o.node){var s=o.changes||(o.changes=[]);-1==To(s,i)&&s.push(i)}}}function Ti(e){e.display.viewFrom=e.display.viewTo=e.doc.first;e.display.view=[];e.display.viewOffset=0}function Li(e,t){if(t>=e.display.viewTo)return null;t-=e.display.viewFrom;if(0>t)return null;for(var i=e.display.view,r=0;r<i.length;r++){t-=i[r].size;if(0>t)return r}}function Ii(e,t,i,r){var n,o=Li(e,t),s=e.display.view;if(!Ls||i==e.doc.first+e.doc.size)return{index:o,lineN:i};for(var a=0,l=e.display.viewFrom;o>a;a++)l+=s[a].size;if(l!=t){if(r>0){if(o==s.length-1)return null;n=l+s[o].size-t;o++}else n=l-t;t+=n;i+=n}for(;an(e.doc,i)!=i;){if(o==(0>r?0:s.length-1))return null;i+=r*s[o-(0>r?1:0)].size;o+=r}return{index:o,lineN:i}}function yi(e,t,i){var r=e.display,n=r.view;if(0==n.length||t>=r.viewTo||i<=r.viewFrom){r.view=vi(e,t,i);r.viewFrom=t}else{r.viewFrom>t?r.view=vi(e,t,r.viewFrom).concat(r.view):r.viewFrom<t&&(r.view=r.view.slice(Li(e,t)));r.viewFrom=t;r.viewTo<i?r.view=r.view.concat(vi(e,r.viewTo,i)):r.viewTo>i&&(r.view=r.view.slice(0,Li(e,i)))}r.viewTo=i}function Ai(e){for(var t=e.display.view,i=0,r=0;r<t.length;r++){var n=t[r];n.hidden||n.node&&!n.changes||++i}return i}function Si(e){e.display.pollingFast||e.display.poll.set(e.options.pollInterval,function(){Ri(e);e.state.focused&&Si(e)})}function Ci(e){function t(){var r=Ri(e);if(r||i){e.display.pollingFast=!1;Si(e)}else{i=!0;e.display.poll.set(60,t)}}var i=!1;e.display.pollingFast=!0;e.display.poll.set(20,t)}function Ri(e){var t=e.display.input,i=e.display.prevInput,r=e.doc;if(!e.state.focused||Ba(t)&&!i||Di(e)||e.options.disableInput||e.state.keySeq)return!1;if(e.state.pasteIncoming&&e.state.fakedLastChar){t.value=t.value.substring(0,t.value.length-1);e.state.fakedLastChar=!1}var n=t.value;if(n==i&&!e.somethingSelected())return!1;if(ns&&os>=9&&e.display.inputHasSelection===n||ms&&/[\uf700-\uf7ff]/.test(n)){bi(e);return!1}var o=!e.curOp;o&&ni(e);e.display.shift=!1;8203!=n.charCodeAt(0)||r.sel!=e.display.selForContextMenu||i||(i="​");for(var s=0,a=Math.min(i.length,n.length);a>s&&i.charCodeAt(s)==n.charCodeAt(s);)++s;var l=n.slice(s),u=Ga(l),p=null;e.state.pasteIncoming&&r.sel.ranges.length>1&&(Ps&&Ps.join("\n")==l?p=r.sel.ranges.length%Ps.length==0&&Lo(Ps,Ga):u.length==r.sel.ranges.length&&(p=Lo(u,function(e){return[e]})));for(var c=r.sel.ranges.length-1;c>=0;c--){var d=r.sel.ranges[c],f=d.from(),h=d.to();s<i.length?f=Is(f.line,f.ch-(i.length-s)):e.state.overwrite&&d.empty()&&!e.state.pasteIncoming&&(h=Is(h.line,Math.min(Bn(r,h.line).text.length,h.ch+No(u).length)));var E=e.curOp.updateInput,m={from:f,to:h,text:p?p[c%p.length]:u,origin:e.state.pasteIncoming?"paste":e.state.cutIncoming?"cut":"+input"};dr(e.doc,m);po(e,"inputRead",e,m);if(l&&!e.state.pasteIncoming&&e.options.electricChars&&e.options.smartIndent&&d.head.ch<100&&(!c||r.sel.ranges[c-1].head.line!=d.head.line)){var g=e.getModeAt(d.head),v=Bs(m);if(g.electricChars){for(var x=0;x<g.electricChars.length;x++)if(l.indexOf(g.electricChars.charAt(x))>-1){Sr(e,v.line,"smart");break}}else g.electricInput&&g.electricInput.test(Bn(r,v.line).text.slice(0,v.ch))&&Sr(e,v.line,"smart")}}yr(e);e.curOp.updateInput=E;e.curOp.typing=!0;n.length>1e3||n.indexOf("\n")>-1?t.value=e.display.prevInput="":e.display.prevInput=n;o&&si(e);e.state.pasteIncoming=e.state.cutIncoming=!1;return!0}function bi(e,t){if(!e.display.contextMenuPending){var i,r,n=e.doc;if(e.somethingSelected()){e.display.prevInput="";var o=n.sel.primary();i=Ua&&(o.to().line-o.from().line>100||(r=e.getSelection()).length>1e3);var s=i?"-":r||e.getSelection();e.display.input.value=s;e.state.focused&&Sa(e.display.input);ns&&os>=9&&(e.display.inputHasSelection=s)}else if(!t){e.display.prevInput=e.display.input.value="";ns&&os>=9&&(e.display.inputHasSelection=null)}e.display.inaccurateSelection=i}}function Oi(e){"nocursor"==e.options.readOnly||Es&&wo()==e.display.input||e.display.input.focus()}function Pi(e){if(!e.state.focused){Oi(e);rr(e)}}function Di(e){return e.options.readOnly||e.doc.cantEdit}function wi(e){function t(t){fo(e,t)||ha(t)}function i(t){if(e.somethingSelected()){Ps=e.getSelections();if(r.inaccurateSelection){r.prevInput="";r.inaccurateSelection=!1;r.input.value=Ps.join("\n");Sa(r.input)}}else{for(var i=[],n=[],o=0;o<e.doc.sel.ranges.length;o++){var s=e.doc.sel.ranges[o].head.line,a={anchor:Is(s,0),head:Is(s+1,0)};n.push(a);i.push(e.getRange(a.anchor,a.head))}if("cut"==t.type)e.setSelections(n,null,Ta);else{r.prevInput="";r.input.value=i.join("\n");Sa(r.input)}Ps=i}"cut"==t.type&&(e.state.cutIncoming=!0)}var r=e.display;Ea(r.scroller,"mousedown",hi(e,Gi));ns&&11>os?Ea(r.scroller,"dblclick",hi(e,function(t){if(!fo(e,t)){var i=ki(e,t);if(i&&!Hi(e,t)&&!Mi(e.display,t)){da(t);var r=e.findWordAt(i);st(e.doc,r.anchor,r.head)}}})):Ea(r.scroller,"dblclick",function(t){fo(e,t)||da(t)});Ea(r.lineSpace,"selectstart",function(e){Mi(r,e)||da(e)});Ns||Ea(r.scroller,"contextmenu",function(t){or(e,t)});Ea(r.scroller,"scroll",function(){if(r.scroller.clientHeight){qi(e,r.scroller.scrollTop);zi(e,r.scroller.scrollLeft,!0);ga(e,"scroll",e)}});Ea(r.scroller,"mousewheel",function(t){Xi(e,t)});Ea(r.scroller,"DOMMouseScroll",function(t){Xi(e,t)});Ea(r.wrapper,"scroll",function(){r.wrapper.scrollTop=r.wrapper.scrollLeft=0});Ea(r.input,"keyup",function(t){tr.call(e,t)});Ea(r.input,"input",function(){ns&&os>=9&&e.display.inputHasSelection&&(e.display.inputHasSelection=null);Ri(e)});Ea(r.input,"keydown",hi(e,Ji));Ea(r.input,"keypress",hi(e,ir));Ea(r.input,"focus",Ao(rr,e));Ea(r.input,"blur",Ao(nr,e));if(e.options.dragDrop){Ea(r.scroller,"dragstart",function(t){Wi(e,t)});Ea(r.scroller,"dragenter",t);Ea(r.scroller,"dragover",t);Ea(r.scroller,"drop",hi(e,ji))}Ea(r.scroller,"paste",function(t){if(!Mi(r,t)){e.state.pasteIncoming=!0;Oi(e);Ci(e)}});Ea(r.input,"paste",function(){if(ss&&!e.state.fakedLastChar&&!(new Date-e.state.lastMiddleDown<200)){var t=r.input.selectionStart,i=r.input.selectionEnd;r.input.value+="$";r.input.selectionEnd=i;r.input.selectionStart=t;e.state.fakedLastChar=!0}e.state.pasteIncoming=!0;Ci(e)});Ea(r.input,"cut",i);Ea(r.input,"copy",i);cs&&Ea(r.sizer,"mouseup",function(){wo()==r.input&&r.input.blur();Oi(e)})}function _i(e){var t=e.display;if(t.lastWrapHeight!=t.wrapper.clientHeight||t.lastWrapWidth!=t.wrapper.clientWidth){t.cachedCharWidth=t.cachedTextHeight=t.cachedPaddingH=null;t.scrollbarsClipped=!1;e.setSize()}}function Mi(e,t){for(var i=lo(t);i!=e.wrapper;i=i.parentNode)if(!i||1==i.nodeType&&"true"==i.getAttribute("cm-ignore-events")||i.parentNode==e.sizer&&i!=e.mover)return!0}function ki(e,t,i,r){var n=e.display;if(!i&&"true"==lo(t).getAttribute("not-content"))return null;var o,s,a=n.lineSpace.getBoundingClientRect();try{o=t.clientX-a.left;s=t.clientY-a.top}catch(t){return null}var l,u=ei(e,o,s);if(r&&1==u.xRel&&(l=Bn(e.doc,u.line).text).length==u.ch){var p=ya(l,l.length,e.options.tabSize)-l.length;u=Is(u.line,Math.max(0,Math.round((o-Ot(e.display).left)/ri(e.display))-p))}return u}function Gi(e){if(!fo(this,e)){var t=this,i=t.display;i.shift=e.shiftKey;if(Mi(i,e)){if(!ss){i.scroller.draggable=!1;setTimeout(function(){i.scroller.draggable=!0},100)}}else if(!Hi(t,e)){var r=ki(t,e);window.focus();switch(uo(e)){case 1:r?Bi(t,e,r):lo(e)==i.scroller&&da(e);break;case 2:ss&&(t.state.lastMiddleDown=+new Date);r&&st(t.doc,r);setTimeout(Ao(Oi,t),20);da(e);break;case 3:Ns&&or(t,e)}}}}function Bi(e,t,i){setTimeout(Ao(Pi,e),0);var r,n=+new Date;if(Cs&&Cs.time>n-400&&0==ys(Cs.pos,i))r="triple";else if(Ss&&Ss.time>n-400&&0==ys(Ss.pos,i)){r="double";Cs={time:n,pos:i}}else{r="single";Ss={time:n,pos:i}}var o,s=e.doc.sel,a=ms?t.metaKey:t.ctrlKey;e.options.dragDrop&&ka&&!Di(e)&&"single"==r&&(o=s.contains(i))>-1&&!s.ranges[o].empty()?Ui(e,t,i,a):Vi(e,t,i,r,a)}function Ui(e,t,i,r){var n=e.display,o=hi(e,function(s){ss&&(n.scroller.draggable=!1);e.state.draggingText=!1;ma(document,"mouseup",o);ma(n.scroller,"drop",o);if(Math.abs(t.clientX-s.clientX)+Math.abs(t.clientY-s.clientY)<10){da(s);r||st(e.doc,i);Oi(e);ns&&9==os&&setTimeout(function(){document.body.focus();Oi(e)},20)}});ss&&(n.scroller.draggable=!0);e.state.draggingText=o;n.scroller.dragDrop&&n.scroller.dragDrop();Ea(document,"mouseup",o);Ea(n.scroller,"drop",o)}function Vi(e,t,i,r,n){function o(t){if(0!=ys(m,t)){m=t;if("rect"==r){for(var n=[],o=e.options.tabSize,s=ya(Bn(u,i.line).text,i.ch,o),a=ya(Bn(u,t.line).text,t.ch,o),l=Math.min(s,a),f=Math.max(s,a),h=Math.min(i.line,t.line),E=Math.min(e.lastLine(),Math.max(i.line,t.line));E>=h;h++){var g=Bn(u,h).text,v=vo(g,l,o);l==f?n.push(new Q(Is(h,v),Is(h,v))):g.length>v&&n.push(new Q(Is(h,v),Is(h,vo(g,f,o))))}n.length||n.push(new Q(i,i));dt(u,Z(d.ranges.slice(0,c).concat(n),c),{origin:"*mouse",scroll:!1});e.scrollIntoView(t)}else{var x=p,N=x.anchor,T=t;if("single"!=r){if("double"==r)var L=e.findWordAt(t);else var L=new Q(Is(t.line,0),tt(u,Is(t.line+1,0)));if(ys(L.anchor,N)>0){T=L.head;N=K(x.from(),L.anchor)}else{T=L.anchor;N=Y(x.to(),L.head)}}var n=d.ranges.slice(0);n[c]=new Q(tt(u,N),T);dt(u,Z(n,c),La)}}}function s(t){var i=++v,n=ki(e,t,!0,"rect"==r);if(n)if(0!=ys(n,m)){Pi(e);o(n);var a=N(l,u);(n.line>=a.to||n.line<a.from)&&setTimeout(hi(e,function(){v==i&&s(t)}),150)}else{var p=t.clientY<g.top?-20:t.clientY>g.bottom?20:0;p&&setTimeout(hi(e,function(){if(v==i){l.scroller.scrollTop+=p;s(t)}}),50)}}function a(t){v=1/0;da(t);Oi(e);ma(document,"mousemove",x);ma(document,"mouseup",T);u.history.lastSelOrigin=null}var l=e.display,u=e.doc;da(t);var p,c,d=u.sel,f=d.ranges;if(n&&!t.shiftKey){c=u.sel.contains(i);p=c>-1?f[c]:new Q(i,i)}else p=u.sel.primary();if(t.altKey){r="rect";n||(p=new Q(i,i));i=ki(e,t,!0,!0);c=-1}else if("double"==r){var h=e.findWordAt(i);p=e.display.shift||u.extend?ot(u,p,h.anchor,h.head):h}else if("triple"==r){var E=new Q(Is(i.line,0),tt(u,Is(i.line+1,0)));p=e.display.shift||u.extend?ot(u,p,E.anchor,E.head):E}else p=ot(u,p,i);if(n)if(-1==c){c=f.length;dt(u,Z(f.concat([p]),c),{scroll:!1,origin:"*mouse"})}else if(f.length>1&&f[c].empty()&&"single"==r){dt(u,Z(f.slice(0,c).concat(f.slice(c+1)),0));d=u.sel}else lt(u,c,p,La);else{c=0;dt(u,new $([p],0),La);d=u.sel}var m=i,g=l.wrapper.getBoundingClientRect(),v=0,x=hi(e,function(e){uo(e)?s(e):a(e)}),T=hi(e,a);Ea(document,"mousemove",x);Ea(document,"mouseup",T)}function Fi(e,t,i,r,n){try{var o=t.clientX,s=t.clientY}catch(t){return!1}if(o>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;r&&da(t);var a=e.display,l=a.lineDiv.getBoundingClientRect();if(s>l.bottom||!Eo(e,i))return ao(t);s-=l.top-a.viewOffset;for(var u=0;u<e.options.gutters.length;++u){var p=a.gutters.childNodes[u];if(p&&p.getBoundingClientRect().right>=o){var c=jn(e.doc,s),d=e.options.gutters[u];n(e,i,e,c,d,t);return ao(t)}}}function Hi(e,t){return Fi(e,t,"gutterClick",!0,po)}function ji(e){var t=this;if(!fo(t,e)&&!Mi(t.display,e)){da(e);ns&&(Ds=+new Date);var i=ki(t,e,!0),r=e.dataTransfer.files;if(i&&!Di(t))if(r&&r.length&&window.FileReader&&window.File)for(var n=r.length,o=Array(n),s=0,a=function(e,r){var a=new FileReader;a.onload=hi(t,function(){o[r]=a.result;if(++s==n){i=tt(t.doc,i);var e={from:i,to:i,text:Ga(o.join("\n")),origin:"paste"};dr(t.doc,e);ct(t.doc,J(i,Bs(e)))}});a.readAsText(e)},l=0;n>l;++l)a(r[l],l);else{if(t.state.draggingText&&t.doc.sel.contains(i)>-1){t.state.draggingText(e);setTimeout(Ao(Oi,t),20);return}try{var o=e.dataTransfer.getData("Text");if(o){if(t.state.draggingText&&!(ms?e.metaKey:e.ctrlKey))var u=t.listSelections();ft(t.doc,J(i,i));if(u)for(var l=0;l<u.length;++l)vr(t.doc,"",u[l].anchor,u[l].head,"drag");t.replaceSelection(o,"around","paste");Oi(t)}}catch(e){}}}}function Wi(e,t){if(ns&&(!e.state.draggingText||+new Date-Ds<100))ha(t);else if(!fo(e,t)&&!Mi(e.display,t)){t.dataTransfer.setData("Text",e.getSelection());if(t.dataTransfer.setDragImage&&!ps){var i=bo("img",null,null,"position: fixed; left: 0; top: 0;");i.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";if(us){i.width=i.height=1;e.display.wrapper.appendChild(i);i._top=i.offsetTop}t.dataTransfer.setDragImage(i,0,0);us&&i.parentNode.removeChild(i)}}}function qi(e,t){if(!(Math.abs(e.doc.scrollTop-t)<2)){e.doc.scrollTop=t;ts||b(e,{top:t});e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t);e.display.scrollbars.setScrollTop(t);ts&&b(e);yt(e,100)}}function zi(e,t,i){if(!(i?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)){t=Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth);e.doc.scrollLeft=t;T(e);e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t);e.display.scrollbars.setScrollLeft(t)}}function Xi(e,t){var i=Ms(t),r=i.x,n=i.y,o=e.display,s=o.scroller;if(r&&s.scrollWidth>s.clientWidth||n&&s.scrollHeight>s.clientHeight){if(n&&ms&&ss)e:for(var a=t.target,l=o.view;a!=s;a=a.parentNode)for(var u=0;u<l.length;u++)if(l[u].node==a){e.display.currentWheelTarget=a;break e}if(!r||ts||us||null==_s){if(n&&null!=_s){var p=n*_s,c=e.doc.scrollTop,d=c+o.wrapper.clientHeight;0>p?c=Math.max(0,c+p-50):d=Math.min(e.doc.height,d+p+50);b(e,{top:c,bottom:d})}if(20>ws)if(null==o.wheelStartX){o.wheelStartX=s.scrollLeft;o.wheelStartY=s.scrollTop;o.wheelDX=r;o.wheelDY=n;setTimeout(function(){if(null!=o.wheelStartX){var e=s.scrollLeft-o.wheelStartX,t=s.scrollTop-o.wheelStartY,i=t&&o.wheelDY&&t/o.wheelDY||e&&o.wheelDX&&e/o.wheelDX;o.wheelStartX=o.wheelStartY=null;if(i){_s=(_s*ws+i)/(ws+1);++ws}}},200)}else{o.wheelDX+=r;o.wheelDY+=n}}else{n&&qi(e,Math.max(0,Math.min(s.scrollTop+n*_s,s.scrollHeight-s.clientHeight)));zi(e,Math.max(0,Math.min(s.scrollLeft+r*_s,s.scrollWidth-s.clientWidth)));da(t);o.wheelStartX=null}}}function Yi(e,t,i){if("string"==typeof t){t=Ks[t];if(!t)return!1}e.display.pollingFast&&Ri(e)&&(e.display.pollingFast=!1);var r=e.display.shift,n=!1;try{Di(e)&&(e.state.suppressEdits=!0);i&&(e.display.shift=!1);n=t(e)!=Na}finally{e.display.shift=r;e.state.suppressEdits=!1}return n}function Ki(e,t,i){for(var r=0;r<e.state.keyMaps.length;r++){var n=Qs(t,e.state.keyMaps[r],i,e);if(n)return n}return e.options.extraKeys&&Qs(t,e.options.extraKeys,i,e)||Qs(t,e.options.keyMap,i,e)}function $i(e,t,i,r){var n=e.state.keySeq;if(n){if(Zs(t))return"handled";ks.set(50,function(){if(e.state.keySeq==n){e.state.keySeq=null;bi(e)}});t=n+" "+t}var o=Ki(e,t,r);"multi"==o&&(e.state.keySeq=t);"handled"==o&&po(e,"keyHandled",e,t,i);if("handled"==o||"multi"==o){da(i);It(e)}if(n&&!o&&/\'$/.test(t)){da(i);return!0}return!!o}function Qi(e,t){var i=Js(t,!0);return i?t.shiftKey&&!e.state.keySeq?$i(e,"Shift-"+i,t,function(t){return Yi(e,t,!0)})||$i(e,i,t,function(t){return("string"==typeof t?/^go[A-Z]/.test(t):t.motion)?Yi(e,t):void 0}):$i(e,i,t,function(t){return Yi(e,t)}):!1}function Zi(e,t,i){return $i(e,"'"+i+"'",t,function(t){return Yi(e,t,!0)})}function Ji(e){var t=this;Pi(t);if(!fo(t,e)){ns&&11>os&&27==e.keyCode&&(e.returnValue=!1);var i=e.keyCode;t.display.shift=16==i||e.shiftKey;var r=Qi(t,e);if(us){Gs=r?i:null;!r&&88==i&&!Ua&&(ms?e.metaKey:e.ctrlKey)&&t.replaceSelection("",null,"cut")}18!=i||/\bCodeMirror-crosshair\b/.test(t.display.lineDiv.className)||er(t)}}function er(e){function t(e){if(18==e.keyCode||!e.altKey){wa(i,"CodeMirror-crosshair");ma(document,"keyup",t);ma(document,"mouseover",t)}}var i=e.display.lineDiv;_a(i,"CodeMirror-crosshair");Ea(document,"keyup",t);Ea(document,"mouseover",t)}function tr(e){16==e.keyCode&&(this.doc.sel.shift=!1);fo(this,e)}function ir(e){var t=this;if(!(fo(t,e)||e.ctrlKey&&!e.altKey||ms&&e.metaKey)){var i=e.keyCode,r=e.charCode;if(us&&i==Gs){Gs=null;da(e)}else if(!(us&&(!e.which||e.which<10)||cs)||!Qi(t,e)){var n=String.fromCharCode(null==r?i:r);if(!Zi(t,e,n)){ns&&os>=9&&(t.display.inputHasSelection=null);Ci(t)}}}}function rr(e){if("nocursor"!=e.options.readOnly){if(!e.state.focused){ga(e,"focus",e);e.state.focused=!0;_a(e.display.wrapper,"CodeMirror-focused");if(!e.curOp&&e.display.selForContextMenu!=e.doc.sel){bi(e);ss&&setTimeout(Ao(bi,e,!0),0)}}Si(e);It(e)}}function nr(e){if(e.state.focused){ga(e,"blur",e);e.state.focused=!1;wa(e.display.wrapper,"CodeMirror-focused")}clearInterval(e.display.blinker);setTimeout(function(){e.state.focused||(e.display.shift=!1)},150)}function or(e,t){function i(){if(null!=n.input.selectionStart){var t=e.somethingSelected(),i=n.input.value="​"+(t?n.input.value:"");n.prevInput=t?"":"​";n.input.selectionStart=1;n.input.selectionEnd=i.length;n.selForContextMenu=e.doc.sel}}function r(){n.contextMenuPending=!1;n.inputDiv.style.position="relative";n.input.style.cssText=l;ns&&9>os&&n.scrollbars.setScrollTop(n.scroller.scrollTop=s);Si(e);if(null!=n.input.selectionStart){(!ns||ns&&9>os)&&i();var t=0,r=function(){n.selForContextMenu==e.doc.sel&&0==n.input.selectionStart?hi(e,Ks.selectAll)(e):t++<10?n.detectingSelectAll=setTimeout(r,500):bi(e)};n.detectingSelectAll=setTimeout(r,200)}}if(!fo(e,t,"contextmenu")){var n=e.display;if(!Mi(n,t)&&!sr(e,t)){var o=ki(e,t),s=n.scroller.scrollTop;if(o&&!us){var a=e.options.resetSelectionOnContextMenu;a&&-1==e.doc.sel.contains(o)&&hi(e,dt)(e.doc,J(o),Ta);var l=n.input.style.cssText;n.inputDiv.style.position="absolute";n.input.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(t.clientY-5)+"px; left: "+(t.clientX-5)+"px; z-index: 1000; background: "+(ns?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";if(ss)var u=window.scrollY;Oi(e);ss&&window.scrollTo(null,u);bi(e);e.somethingSelected()||(n.input.value=n.prevInput=" ");n.contextMenuPending=!0;n.selForContextMenu=e.doc.sel;clearTimeout(n.detectingSelectAll);ns&&os>=9&&i();if(Ns){ha(t);var p=function(){ma(window,"mouseup",p);setTimeout(r,20)};Ea(window,"mouseup",p)}else setTimeout(r,50)}}}}function sr(e,t){return Eo(e,"gutterContextMenu")?Fi(e,t,"gutterContextMenu",!1,ga):!1}function ar(e,t){if(ys(e,t.from)<0)return e;if(ys(e,t.to)<=0)return Bs(t);var i=e.line+t.text.length-(t.to.line-t.from.line)-1,r=e.ch;e.line==t.to.line&&(r+=Bs(t).ch-t.to.ch);return Is(i,r)}function lr(e,t){for(var i=[],r=0;r<e.sel.ranges.length;r++){var n=e.sel.ranges[r];i.push(new Q(ar(n.anchor,t),ar(n.head,t)))}return Z(i,e.sel.primIndex)}function ur(e,t,i){return e.line==t.line?Is(i.line,e.ch-t.ch+i.ch):Is(i.line+(e.line-t.line),e.ch)}function pr(e,t,i){for(var r=[],n=Is(e.first,0),o=n,s=0;s<t.length;s++){var a=t[s],l=ur(a.from,n,o),u=ur(Bs(a),n,o);n=a.to;o=u;if("around"==i){var p=e.sel.ranges[s],c=ys(p.head,p.anchor)<0;r[s]=new Q(c?u:l,c?l:u)}else r[s]=new Q(l,l)}return new $(r,e.sel.primIndex)}function cr(e,t,i){var r={canceled:!1,from:t.from,to:t.to,text:t.text,origin:t.origin,cancel:function(){this.canceled=!0}};i&&(r.update=function(t,i,r,n){t&&(this.from=tt(e,t));i&&(this.to=tt(e,i));r&&(this.text=r);void 0!==n&&(this.origin=n)});ga(e,"beforeChange",e,r);e.cm&&ga(e.cm,"beforeChange",e.cm,r);return r.canceled?null:{from:r.from,to:r.to,text:r.text,origin:r.origin}}function dr(e,t,i){if(e.cm){if(!e.cm.curOp)return hi(e.cm,dr)(e,t,i);if(e.cm.state.suppressEdits)return}if(Eo(e,"beforeChange")||e.cm&&Eo(e.cm,"beforeChange")){t=cr(e,t,!0);if(!t)return}var r=Ts&&!i&&Yr(e,t.from,t.to);if(r)for(var n=r.length-1;n>=0;--n)fr(e,{from:r[n].from,to:r[n].to,text:n?[""]:t.text});else fr(e,t)}function fr(e,t){if(1!=t.text.length||""!=t.text[0]||0!=ys(t.from,t.to)){var i=lr(e,t);$n(e,t,i,e.cm?e.cm.curOp.id:0/0);mr(e,t,i,qr(e,t));var r=[];kn(e,function(e,i){if(!i&&-1==To(r,e.history)){so(e.history,t);r.push(e.history)}mr(e,t,null,qr(e,t))})}}function hr(e,t,i){if(!e.cm||!e.cm.state.suppressEdits){for(var r,n=e.history,o=e.sel,s="undo"==t?n.done:n.undone,a="undo"==t?n.undone:n.done,l=0;l<s.length;l++){r=s[l];if(i?r.ranges&&!r.equals(e.sel):!r.ranges)break}if(l!=s.length){n.lastOrigin=n.lastSelOrigin=null;for(;;){r=s.pop();if(!r.ranges)break;Jn(r,a);if(i&&!r.equals(e.sel)){dt(e,r,{clearRedo:!1});return}o=r}var u=[];Jn(o,a);a.push({changes:u,generation:n.generation});n.generation=r.generation||++n.maxGeneration;for(var p=Eo(e,"beforeChange")||e.cm&&Eo(e.cm,"beforeChange"),l=r.changes.length-1;l>=0;--l){var c=r.changes[l];c.origin=t;if(p&&!cr(e,c,!1)){s.length=0;return}u.push(Xn(e,c));var d=l?lr(e,c):No(s);mr(e,c,d,Xr(e,c));!l&&e.cm&&e.cm.scrollIntoView({from:c.from,to:Bs(c)});var f=[];kn(e,function(e,t){if(!t&&-1==To(f,e.history)){so(e.history,c);f.push(e.history)}mr(e,c,null,Xr(e,c))})}}}}function Er(e,t){if(0!=t){e.first+=t;e.sel=new $(Lo(e.sel.ranges,function(e){return new Q(Is(e.anchor.line+t,e.anchor.ch),Is(e.head.line+t,e.head.ch))}),e.sel.primIndex);if(e.cm){xi(e.cm,e.first,e.first-t,t);for(var i=e.cm.display,r=i.viewFrom;r<i.viewTo;r++)Ni(e.cm,r,"gutter")}}}function mr(e,t,i,r){if(e.cm&&!e.cm.curOp)return hi(e.cm,mr)(e,t,i,r);if(t.to.line<e.first)Er(e,t.text.length-1-(t.to.line-t.from.line));else if(!(t.from.line>e.lastLine())){if(t.from.line<e.first){var n=t.text.length-1-(e.first-t.from.line);Er(e,n);t={from:Is(e.first,0),to:Is(t.to.line+n,t.to.ch),text:[No(t.text)],origin:t.origin}}var o=e.lastLine();t.to.line>o&&(t={from:t.from,to:Is(o,Bn(e,o).text.length),text:[t.text[0]],origin:t.origin});t.removed=Un(e,t.from,t.to);i||(i=lr(e,t));e.cm?gr(e.cm,t,r):wn(e,t,r);ft(e,i,Ta)}}function gr(e,t,i){var r=e.doc,n=e.display,s=t.from,a=t.to,l=!1,u=s.line;if(!e.options.lineWrapping){u=Hn(on(Bn(r,s.line)));r.iter(u,a.line+1,function(e){if(e==n.maxLine){l=!0;return!0}})}r.sel.contains(t.from,t.to)>-1&&ho(e);wn(r,t,i,o(e));if(!e.options.lineWrapping){r.iter(u,s.line+t.text.length,function(e){var t=c(e);if(t>n.maxLineLength){n.maxLine=e;n.maxLineLength=t;n.maxLineChanged=!0;l=!1}});l&&(e.curOp.updateMaxLine=!0)}r.frontier=Math.min(r.frontier,s.line);yt(e,400);var p=t.text.length-(a.line-s.line)-1;t.full?xi(e):s.line!=a.line||1!=t.text.length||Dn(e.doc,t)?xi(e,s.line,a.line+1,p):Ni(e,s.line,"text");var d=Eo(e,"changes"),f=Eo(e,"change");if(f||d){var h={from:s,to:a,text:t.text,removed:t.removed,origin:t.origin};f&&po(e,"change",e,h);d&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(h)}e.display.selForContextMenu=null}function vr(e,t,i,r,n){r||(r=i);if(ys(r,i)<0){var o=r;r=i;i=o}"string"==typeof t&&(t=Ga(t));dr(e,{from:i,to:r,text:t,origin:n})}function xr(e,t){if(!fo(e,"scrollCursorIntoView")){var i=e.display,r=i.sizer.getBoundingClientRect(),n=null;t.top+r.top<0?n=!0:t.bottom+r.top>(window.innerHeight||document.documentElement.clientHeight)&&(n=!1);if(null!=n&&!fs){var o=bo("div","​",null,"position: absolute; top: "+(t.top-i.viewOffset-Rt(e.display))+"px; height: "+(t.bottom-t.top+Pt(e)+i.barHeight)+"px; left: "+t.left+"px; width: 2px;");e.display.lineSpace.appendChild(o);o.scrollIntoView(n);e.display.lineSpace.removeChild(o)}}}function Nr(e,t,i,r){null==r&&(r=0);for(var n=0;5>n;n++){var o=!1,s=Qt(e,t),a=i&&i!=t?Qt(e,i):s,l=Lr(e,Math.min(s.left,a.left),Math.min(s.top,a.top)-r,Math.max(s.left,a.left),Math.max(s.bottom,a.bottom)+r),u=e.doc.scrollTop,p=e.doc.scrollLeft;if(null!=l.scrollTop){qi(e,l.scrollTop);Math.abs(e.doc.scrollTop-u)>1&&(o=!0)}if(null!=l.scrollLeft){zi(e,l.scrollLeft);Math.abs(e.doc.scrollLeft-p)>1&&(o=!0)}if(!o)break}return s}function Tr(e,t,i,r,n){var o=Lr(e,t,i,r,n);null!=o.scrollTop&&qi(e,o.scrollTop);null!=o.scrollLeft&&zi(e,o.scrollLeft)}function Lr(e,t,i,r,n){var o=e.display,s=ii(e.display);0>i&&(i=0);var a=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:o.scroller.scrollTop,l=wt(e),u={};n-i>l&&(n=i+l);var p=e.doc.height+bt(o),c=s>i,d=n>p-s;if(a>i)u.scrollTop=c?0:i;else if(n>a+l){var f=Math.min(i,(d?p:n)-l);f!=a&&(u.scrollTop=f)}var h=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:o.scroller.scrollLeft,E=Dt(e)-(e.options.fixedGutter?o.gutters.offsetWidth:0),m=r-t>E;m&&(r=t+E);10>t?u.scrollLeft=0:h>t?u.scrollLeft=Math.max(0,t-(m?0:10)):r>E+h-3&&(u.scrollLeft=r+(m?0:10)-E);return u}function Ir(e,t,i){(null!=t||null!=i)&&Ar(e);null!=t&&(e.curOp.scrollLeft=(null==e.curOp.scrollLeft?e.doc.scrollLeft:e.curOp.scrollLeft)+t);null!=i&&(e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+i)}function yr(e){Ar(e);var t=e.getCursor(),i=t,r=t;if(!e.options.lineWrapping){i=t.ch?Is(t.line,t.ch-1):t;r=Is(t.line,t.ch+1)}e.curOp.scrollToPos={from:i,to:r,margin:e.options.cursorScrollMargin,isCursor:!0}}function Ar(e){var t=e.curOp.scrollToPos;if(t){e.curOp.scrollToPos=null;var i=Zt(e,t.from),r=Zt(e,t.to),n=Lr(e,Math.min(i.left,r.left),Math.min(i.top,r.top)-t.margin,Math.max(i.right,r.right),Math.max(i.bottom,r.bottom)+t.margin);e.scrollTo(n.scrollLeft,n.scrollTop)}}function Sr(e,t,i,r){var n,o=e.doc;null==i&&(i="add");"smart"==i&&(o.mode.indent?n=Ct(e,t):i="prev");var s=e.options.tabSize,a=Bn(o,t),l=ya(a.text,null,s);a.stateAfter&&(a.stateAfter=null);var u,p=a.text.match(/^\s*/)[0];if(r||/\S/.test(a.text)){if("smart"==i){u=o.mode.indent(n,a.text.slice(p.length),a.text);if(u==Na||u>150){if(!r)return;i="prev"}}}else{u=0;i="not"}"prev"==i?u=t>o.first?ya(Bn(o,t-1).text,null,s):0:"add"==i?u=l+e.options.indentUnit:"subtract"==i?u=l-e.options.indentUnit:"number"==typeof i&&(u=l+i);u=Math.max(0,u);var c="",d=0;if(e.options.indentWithTabs)for(var f=Math.floor(u/s);f;--f){d+=s;c+=" "}u>d&&(c+=xo(u-d));if(c!=p)vr(o,c,Is(t,0),Is(t,p.length),"+input");else for(var f=0;f<o.sel.ranges.length;f++){var h=o.sel.ranges[f];if(h.head.line==t&&h.head.ch<p.length){var d=Is(t,p.length);lt(o,f,new Q(d,d));break}}a.stateAfter=null}function Cr(e,t,i,r){var n=t,o=t;"number"==typeof t?o=Bn(e,et(e,t)):n=Hn(t);if(null==n)return null;r(o,n)&&e.cm&&Ni(e.cm,n,i);return o}function Rr(e,t){for(var i=e.doc.sel.ranges,r=[],n=0;n<i.length;n++){for(var o=t(i[n]);r.length&&ys(o.from,No(r).to)<=0;){var s=r.pop();if(ys(s.from,o.from)<0){o.from=s.from;break}}r.push(o)}fi(e,function(){for(var t=r.length-1;t>=0;t--)vr(e.doc,"",r[t].from,r[t].to,"+delete");yr(e)})}function br(e,t,i,r,n){function o(){var t=a+i;if(t<e.first||t>=e.first+e.size)return c=!1;a=t;return p=Bn(e,t)}function s(e){var t=(n?Jo:es)(p,l,i,!0);if(null==t){if(e||!o())return c=!1;l=n?(0>i?zo:qo)(p):0>i?p.text.length:0}else l=t;return!0}var a=t.line,l=t.ch,u=i,p=Bn(e,a),c=!0;if("char"==r)s();else if("column"==r)s(!0);else if("word"==r||"group"==r)for(var d=null,f="group"==r,h=e.cm&&e.cm.getHelper(t,"wordChars"),E=!0;!(0>i)||s(!E);E=!1){var m=p.text.charAt(l)||"\n",g=So(m,h)?"w":f&&"\n"==m?"n":!f||/\s/.test(m)?null:"p";!f||E||g||(g="s");if(d&&d!=g){if(0>i){i=1;s()}break}g&&(d=g);if(i>0&&!s(!E))break}var v=gt(e,Is(a,l),u,!0);c||(v.hitSide=!0);return v}function Or(e,t,i,r){var n,o=e.doc,s=t.left;if("page"==r){var a=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);n=t.top+i*(a-(0>i?1.5:.5)*ii(e.display))}else"line"==r&&(n=i>0?t.bottom+3:t.top-3);for(;;){var l=ei(e,s,n);if(!l.outside)break;if(0>i?0>=n:n>=o.height){l.hitSide=!0;break}n+=5*i}return l}function Pr(t,i,r,n){e.defaults[t]=i;r&&(Vs[t]=n?function(e,t,i){i!=Fs&&r(e,t,i)}:r)}function Dr(e){for(var t,i,r,n,o=e.split(/-(?!$)/),e=o[o.length-1],s=0;s<o.length-1;s++){var a=o[s];if(/^(cmd|meta|m)$/i.test(a))n=!0;else if(/^a(lt)?$/i.test(a))t=!0;else if(/^(c|ctrl|control)$/i.test(a))i=!0;else{if(!/^s(hift)$/i.test(a))throw new Error("Unrecognized modifier name: "+a);r=!0}}t&&(e="Alt-"+e);i&&(e="Ctrl-"+e);n&&(e="Cmd-"+e);r&&(e="Shift-"+e);return e}function wr(e){return"string"==typeof e?$s[e]:e}function _r(e,t,i,r,n){if(r&&r.shared)return Mr(e,t,i,r,n);if(e.cm&&!e.cm.curOp)return hi(e.cm,_r)(e,t,i,r,n);var o=new ta(e,n),s=ys(t,i);r&&yo(r,o,!1);if(s>0||0==s&&o.clearWhenEmpty!==!1)return o;if(o.replacedWith){o.collapsed=!0;o.widgetNode=bo("span",[o.replacedWith],"CodeMirror-widget");r.handleMouseEvents||o.widgetNode.setAttribute("cm-ignore-events","true");r.insertLeft&&(o.widgetNode.insertLeft=!0)}if(o.collapsed){if(nn(e,t.line,t,i,o)||t.line!=i.line&&nn(e,i.line,t,i,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");Ls=!0}o.addToHistory&&$n(e,{from:t,to:i,origin:"markText"},e.sel,0/0);var a,l=t.line,u=e.cm;e.iter(l,i.line+1,function(e){u&&o.collapsed&&!u.options.lineWrapping&&on(e)==u.display.maxLine&&(a=!0);o.collapsed&&l!=t.line&&Fn(e,0);Hr(e,new Ur(o,l==t.line?t.ch:null,l==i.line?i.ch:null));++l});o.collapsed&&e.iter(t.line,i.line+1,function(t){un(e,t)&&Fn(t,0)});o.clearOnEnter&&Ea(o,"beforeCursorEnter",function(){o.clear()});if(o.readOnly){Ts=!0;(e.history.done.length||e.history.undone.length)&&e.clearHistory()}if(o.collapsed){o.id=++ia;o.atomic=!0}if(u){a&&(u.curOp.updateMaxLine=!0);if(o.collapsed)xi(u,t.line,i.line+1);else if(o.className||o.title||o.startStyle||o.endStyle||o.css)for(var p=t.line;p<=i.line;p++)Ni(u,p,"text");o.atomic&&Et(u.doc);po(u,"markerAdded",u,o)}return o}function Mr(e,t,i,r,n){r=yo(r);r.shared=!1;var o=[_r(e,t,i,r,n)],s=o[0],a=r.widgetNode;kn(e,function(e){a&&(r.widgetNode=a.cloneNode(!0));o.push(_r(e,tt(e,t),tt(e,i),r,n));for(var l=0;l<e.linked.length;++l)if(e.linked[l].isParent)return;s=No(o)});return new ra(o,s)}function kr(e){return e.findMarks(Is(e.first,0),e.clipPos(Is(e.lastLine())),function(e){return e.parent})}function Gr(e,t){for(var i=0;i<t.length;i++){var r=t[i],n=r.find(),o=e.clipPos(n.from),s=e.clipPos(n.to);if(ys(o,s)){var a=_r(e,o,s,r.primary,r.primary.type);r.markers.push(a);a.parent=r}}}function Br(e){for(var t=0;t<e.length;t++){var i=e[t],r=[i.primary.doc];kn(i.primary.doc,function(e){r.push(e)});for(var n=0;n<i.markers.length;n++){var o=i.markers[n];if(-1==To(r,o.doc)){o.parent=null;i.markers.splice(n--,1)}}}}function Ur(e,t,i){this.marker=e;this.from=t;this.to=i}function Vr(e,t){if(e)for(var i=0;i<e.length;++i){var r=e[i];if(r.marker==t)return r}}function Fr(e,t){for(var i,r=0;r<e.length;++r)e[r]!=t&&(i||(i=[])).push(e[r]);return i}function Hr(e,t){e.markedSpans=e.markedSpans?e.markedSpans.concat([t]):[t];t.marker.attachLine(e)}function jr(e,t,i){if(e)for(var r,n=0;n<e.length;++n){var o=e[n],s=o.marker,a=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);if(a||o.from==t&&"bookmark"==s.type&&(!i||!o.marker.insertLeft)){var l=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);(r||(r=[])).push(new Ur(s,o.from,l?null:o.to))}}return r}function Wr(e,t,i){if(e)for(var r,n=0;n<e.length;++n){var o=e[n],s=o.marker,a=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);if(a||o.from==t&&"bookmark"==s.type&&(!i||o.marker.insertLeft)){var l=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);(r||(r=[])).push(new Ur(s,l?null:o.from-t,null==o.to?null:o.to-t))}}return r}function qr(e,t){if(t.full)return null;var i=rt(e,t.from.line)&&Bn(e,t.from.line).markedSpans,r=rt(e,t.to.line)&&Bn(e,t.to.line).markedSpans;if(!i&&!r)return null;var n=t.from.ch,o=t.to.ch,s=0==ys(t.from,t.to),a=jr(i,n,s),l=Wr(r,o,s),u=1==t.text.length,p=No(t.text).length+(u?n:0);if(a)for(var c=0;c<a.length;++c){var d=a[c];if(null==d.to){var f=Vr(l,d.marker);f?u&&(d.to=null==f.to?null:f.to+p):d.to=n}}if(l)for(var c=0;c<l.length;++c){var d=l[c];null!=d.to&&(d.to+=p);if(null==d.from){var f=Vr(a,d.marker);if(!f){d.from=p;u&&(a||(a=[])).push(d)}}else{d.from+=p;u&&(a||(a=[])).push(d)}}a&&(a=zr(a));l&&l!=a&&(l=zr(l));var h=[a];if(!u){var E,m=t.text.length-2;if(m>0&&a)for(var c=0;c<a.length;++c)null==a[c].to&&(E||(E=[])).push(new Ur(a[c].marker,null,null));for(var c=0;m>c;++c)h.push(E);h.push(l)}return h}function zr(e){for(var t=0;t<e.length;++t){var i=e[t];null!=i.from&&i.from==i.to&&i.marker.clearWhenEmpty!==!1&&e.splice(t--,1)}return e.length?e:null}function Xr(e,t){var i=io(e,t),r=qr(e,t); if(!i)return r;if(!r)return i;for(var n=0;n<i.length;++n){var o=i[n],s=r[n];if(o&&s)e:for(var a=0;a<s.length;++a){for(var l=s[a],u=0;u<o.length;++u)if(o[u].marker==l.marker)continue e;o.push(l)}else s&&(i[n]=s)}return i}function Yr(e,t,i){var r=null;e.iter(t.line,i.line+1,function(e){if(e.markedSpans)for(var t=0;t<e.markedSpans.length;++t){var i=e.markedSpans[t].marker;!i.readOnly||r&&-1!=To(r,i)||(r||(r=[])).push(i)}});if(!r)return null;for(var n=[{from:t,to:i}],o=0;o<r.length;++o)for(var s=r[o],a=s.find(0),l=0;l<n.length;++l){var u=n[l];if(!(ys(u.to,a.from)<0||ys(u.from,a.to)>0)){var p=[l,1],c=ys(u.from,a.from),d=ys(u.to,a.to);(0>c||!s.inclusiveLeft&&!c)&&p.push({from:u.from,to:a.from});(d>0||!s.inclusiveRight&&!d)&&p.push({from:a.to,to:u.to});n.splice.apply(n,p);l+=p.length-1}}return n}function Kr(e){var t=e.markedSpans;if(t){for(var i=0;i<t.length;++i)t[i].marker.detachLine(e);e.markedSpans=null}}function $r(e,t){if(t){for(var i=0;i<t.length;++i)t[i].marker.attachLine(e);e.markedSpans=t}}function Qr(e){return e.inclusiveLeft?-1:0}function Zr(e){return e.inclusiveRight?1:0}function Jr(e,t){var i=e.lines.length-t.lines.length;if(0!=i)return i;var r=e.find(),n=t.find(),o=ys(r.from,n.from)||Qr(e)-Qr(t);if(o)return-o;var s=ys(r.to,n.to)||Zr(e)-Zr(t);return s?s:t.id-e.id}function en(e,t){var i,r=Ls&&e.markedSpans;if(r)for(var n,o=0;o<r.length;++o){n=r[o];n.marker.collapsed&&null==(t?n.from:n.to)&&(!i||Jr(i,n.marker)<0)&&(i=n.marker)}return i}function tn(e){return en(e,!0)}function rn(e){return en(e,!1)}function nn(e,t,i,r,n){var o=Bn(e,t),s=Ls&&o.markedSpans;if(s)for(var a=0;a<s.length;++a){var l=s[a];if(l.marker.collapsed){var u=l.marker.find(0),p=ys(u.from,i)||Qr(l.marker)-Qr(n),c=ys(u.to,r)||Zr(l.marker)-Zr(n);if(!(p>=0&&0>=c||0>=p&&c>=0)&&(0>=p&&(ys(u.to,i)>0||l.marker.inclusiveRight&&n.inclusiveLeft)||p>=0&&(ys(u.from,r)<0||l.marker.inclusiveLeft&&n.inclusiveRight)))return!0}}}function on(e){for(var t;t=tn(e);)e=t.find(-1,!0).line;return e}function sn(e){for(var t,i;t=rn(e);){e=t.find(1,!0).line;(i||(i=[])).push(e)}return i}function an(e,t){var i=Bn(e,t),r=on(i);return i==r?t:Hn(r)}function ln(e,t){if(t>e.lastLine())return t;var i,r=Bn(e,t);if(!un(e,r))return t;for(;i=rn(r);)r=i.find(1,!0).line;return Hn(r)+1}function un(e,t){var i=Ls&&t.markedSpans;if(i)for(var r,n=0;n<i.length;++n){r=i[n];if(r.marker.collapsed){if(null==r.from)return!0;if(!r.marker.widgetNode&&0==r.from&&r.marker.inclusiveLeft&&pn(e,t,r))return!0}}}function pn(e,t,i){if(null==i.to){var r=i.marker.find(1,!0);return pn(e,r.line,Vr(r.line.markedSpans,i.marker))}if(i.marker.inclusiveRight&&i.to==t.text.length)return!0;for(var n,o=0;o<t.markedSpans.length;++o){n=t.markedSpans[o];if(n.marker.collapsed&&!n.marker.widgetNode&&n.from==i.to&&(null==n.to||n.to!=i.from)&&(n.marker.inclusiveLeft||i.marker.inclusiveRight)&&pn(e,t,n))return!0}}function cn(e,t,i){Wn(t)<(e.curOp&&e.curOp.scrollTop||e.doc.scrollTop)&&Ir(e,null,i)}function dn(e){if(null!=e.height)return e.height;if(!Do(document.body,e.node)){var t="position: relative;";e.coverGutter&&(t+="margin-left: -"+e.cm.display.gutters.offsetWidth+"px;");e.noHScroll&&(t+="width: "+e.cm.display.wrapper.clientWidth+"px;");Po(e.cm.display.measure,bo("div",[e.node],null,t))}return e.height=e.node.offsetHeight}function fn(e,t,i,r){var n=new na(e,i,r);n.noHScroll&&(e.display.alignWidgets=!0);Cr(e.doc,t,"widget",function(t){var i=t.widgets||(t.widgets=[]);null==n.insertAt?i.push(n):i.splice(Math.min(i.length-1,Math.max(0,n.insertAt)),0,n);n.line=t;if(!un(e.doc,t)){var r=Wn(t)<e.doc.scrollTop;Fn(t,t.height+dn(n));r&&Ir(e,null,n.height);e.curOp.forceUpdate=!0}return!0});return n}function hn(e,t,i,r){e.text=t;e.stateAfter&&(e.stateAfter=null);e.styles&&(e.styles=null);null!=e.order&&(e.order=null);Kr(e);$r(e,i);var n=r?r(e):1;n!=e.height&&Fn(e,n)}function En(e){e.parent=null;Kr(e)}function mn(e,t){if(e)for(;;){var i=e.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!i)break;e=e.slice(0,i.index)+e.slice(i.index+i[0].length);var r=i[1]?"bgClass":"textClass";null==t[r]?t[r]=i[2]:new RegExp("(?:^|s)"+i[2]+"(?:$|s)").test(t[r])||(t[r]+=" "+i[2])}return e}function gn(t,i){if(t.blankLine)return t.blankLine(i);if(t.innerMode){var r=e.innerMode(t,i);return r.mode.blankLine?r.mode.blankLine(r.state):void 0}}function vn(t,i,r,n){for(var o=0;10>o;o++){n&&(n[0]=e.innerMode(t,r).mode);var s=t.token(i,r);if(i.pos>i.start)return s}throw new Error("Mode "+t.name+" failed to advance stream.")}function xn(e,t,i,r){function n(e){return{start:c.start,end:c.pos,string:c.current(),type:o||null,state:e?Xs(s.mode,p):p}}var o,s=e.doc,a=s.mode;t=tt(s,t);var l,u=Bn(s,t.line),p=Ct(e,t.line,i),c=new ea(u.text,e.options.tabSize);r&&(l=[]);for(;(r||c.pos<t.ch)&&!c.eol();){c.start=c.pos;o=vn(a,c,p);r&&l.push(n(!0))}return r?l:n()}function Nn(e,t,i,r,n,o,s){var a=i.flattenSpans;null==a&&(a=e.options.flattenSpans);var l,u=0,p=null,c=new ea(t,e.options.tabSize),d=e.options.addModeClass&&[null];""==t&&mn(gn(i,r),o);for(;!c.eol();){if(c.pos>e.options.maxHighlightLength){a=!1;s&&In(e,t,r,c.pos);c.pos=t.length;l=null}else l=mn(vn(i,c,r,d),o);if(d){var f=d[0].name;f&&(l="m-"+(l?f+" "+l:f))}if(!a||p!=l){for(;u<c.start;){u=Math.min(c.start,u+5e4);n(u,p)}p=l}c.start=c.pos}for(;u<c.pos;){var h=Math.min(c.pos,u+5e4);n(h,p);u=h}}function Tn(e,t,i,r){var n=[e.state.modeGen],o={};Nn(e,t.text,e.doc.mode,i,function(e,t){n.push(e,t)},o,r);for(var s=0;s<e.state.overlays.length;++s){var a=e.state.overlays[s],l=1,u=0;Nn(e,t.text,a.mode,!0,function(e,t){for(var i=l;e>u;){var r=n[l];r>e&&n.splice(l,1,e,n[l+1],r);l+=2;u=Math.min(e,r)}if(t)if(a.opaque){n.splice(i,l-i,e,"cm-overlay "+t);l=i+2}else for(;l>i;i+=2){var o=n[i+1];n[i+1]=(o?o+" ":"")+"cm-overlay "+t}},o)}return{styles:n,classes:o.bgClass||o.textClass?o:null}}function Ln(e,t,i){if(!t.styles||t.styles[0]!=e.state.modeGen){var r=Tn(e,t,t.stateAfter=Ct(e,Hn(t)));t.styles=r.styles;r.classes?t.styleClasses=r.classes:t.styleClasses&&(t.styleClasses=null);i===e.doc.frontier&&e.doc.frontier++}return t.styles}function In(e,t,i,r){var n=e.doc.mode,o=new ea(t,e.options.tabSize);o.start=o.pos=r||0;""==t&&gn(n,i);for(;!o.eol()&&o.pos<=e.options.maxHighlightLength;){vn(n,o,i);o.start=o.pos}}function yn(e,t){if(!e||/^\s*$/.test(e))return null;var i=t.addModeClass?aa:sa;return i[e]||(i[e]=e.replace(/\S+/g,"cm-$&"))}function An(e,t){var i=bo("span",null,null,ss?"padding-right: .1px":null),r={pre:bo("pre",[i]),content:i,col:0,pos:0,cm:e};t.measure={};for(var n=0;n<=(t.rest?t.rest.length:0);n++){var o,s=n?t.rest[n-1]:t.line;r.pos=0;r.addToken=Cn;(ns||ss)&&e.getOption("lineWrapping")&&(r.addToken=Rn(r.addToken));Vo(e.display.measure)&&(o=qn(s))&&(r.addToken=bn(r.addToken,o));r.map=[];var a=t!=e.display.externalMeasured&&Hn(s);Pn(s,r,Ln(e,s,a));if(s.styleClasses){s.styleClasses.bgClass&&(r.bgClass=Mo(s.styleClasses.bgClass,r.bgClass||""));s.styleClasses.textClass&&(r.textClass=Mo(s.styleClasses.textClass,r.textClass||""))}0==r.map.length&&r.map.push(0,0,r.content.appendChild(Uo(e.display.measure)));if(0==n){t.measure.map=r.map;t.measure.cache={}}else{(t.measure.maps||(t.measure.maps=[])).push(r.map);(t.measure.caches||(t.measure.caches=[])).push({})}}ss&&/\bcm-tab\b/.test(r.content.lastChild.className)&&(r.content.className="cm-tab-wrap-hack");ga(e,"renderLine",e,t.line,r.pre);r.pre.className&&(r.textClass=Mo(r.pre.className,r.textClass||""));return r}function Sn(e){var t=bo("span","•","cm-invalidchar");t.title="\\u"+e.charCodeAt(0).toString(16);return t}function Cn(e,t,i,r,n,o,s){if(t){var a=e.cm.options.specialChars,l=!1;if(a.test(t))for(var u=document.createDocumentFragment(),p=0;;){a.lastIndex=p;var c=a.exec(t),d=c?c.index-p:t.length-p;if(d){var f=document.createTextNode(t.slice(p,p+d));u.appendChild(ns&&9>os?bo("span",[f]):f);e.map.push(e.pos,e.pos+d,f);e.col+=d;e.pos+=d}if(!c)break;p+=d+1;if(" "==c[0]){var h=e.cm.options.tabSize,E=h-e.col%h,f=u.appendChild(bo("span",xo(E),"cm-tab"));e.col+=E}else{var f=e.cm.options.specialCharPlaceholder(c[0]);u.appendChild(ns&&9>os?bo("span",[f]):f);e.col+=1}e.map.push(e.pos,e.pos+1,f);e.pos++}else{e.col+=t.length;var u=document.createTextNode(t);e.map.push(e.pos,e.pos+t.length,u);ns&&9>os&&(l=!0);e.pos+=t.length}if(i||r||n||l||s){var m=i||"";r&&(m+=r);n&&(m+=n);var g=bo("span",[u],m,s);o&&(g.title=o);return e.content.appendChild(g)}e.content.appendChild(u)}}function Rn(e){function t(e){for(var t=" ",i=0;i<e.length-2;++i)t+=i%2?" ":" ";t+=" ";return t}return function(i,r,n,o,s,a){e(i,r.replace(/ {3,}/g,t),n,o,s,a)}}function bn(e,t){return function(i,r,n,o,s,a){n=n?n+" cm-force-border":"cm-force-border";for(var l=i.pos,u=l+r.length;;){for(var p=0;p<t.length;p++){var c=t[p];if(c.to>l&&c.from<=l)break}if(c.to>=u)return e(i,r,n,o,s,a);e(i,r.slice(0,c.to-l),n,o,null,a);o=null;r=r.slice(c.to-l);l=c.to}}}function On(e,t,i,r){var n=!r&&i.widgetNode;if(n){e.map.push(e.pos,e.pos+t,n);e.content.appendChild(n)}e.pos+=t}function Pn(e,t,i){var r=e.markedSpans,n=e.text,o=0;if(r)for(var s,a,l,u,p,c,d,f=n.length,h=0,E=1,m="",g=0;;){if(g==h){l=u=p=c=a="";d=null;g=1/0;for(var v=[],x=0;x<r.length;++x){var N=r[x],T=N.marker;if(N.from<=h&&(null==N.to||N.to>h)){if(null!=N.to&&g>N.to){g=N.to;u=""}T.className&&(l+=" "+T.className);T.css&&(a=T.css);T.startStyle&&N.from==h&&(p+=" "+T.startStyle);T.endStyle&&N.to==g&&(u+=" "+T.endStyle);T.title&&!c&&(c=T.title);T.collapsed&&(!d||Jr(d.marker,T)<0)&&(d=N)}else N.from>h&&g>N.from&&(g=N.from);"bookmark"==T.type&&N.from==h&&T.widgetNode&&v.push(T)}if(d&&(d.from||0)==h){On(t,(null==d.to?f+1:d.to)-h,d.marker,null==d.from);if(null==d.to)return}if(!d&&v.length)for(var x=0;x<v.length;++x)On(t,0,v[x])}if(h>=f)break;for(var L=Math.min(f,g);;){if(m){var I=h+m.length;if(!d){var y=I>L?m.slice(0,L-h):m;t.addToken(t,y,s?s+l:l,p,h+y.length==g?u:"",c,a)}if(I>=L){m=m.slice(L-h);h=L;break}h=I;p=""}m=n.slice(o,o=i[E++]);s=yn(i[E++],t.cm.options)}}else for(var E=1;E<i.length;E+=2)t.addToken(t,n.slice(o,o=i[E]),yn(i[E+1],t.cm.options))}function Dn(e,t){return 0==t.from.ch&&0==t.to.ch&&""==No(t.text)&&(!e.cm||e.cm.options.wholeLineUpdateBefore)}function wn(e,t,i,r){function n(e){return i?i[e]:null}function o(e,i,n){hn(e,i,n,r);po(e,"change",e,t)}function s(e,t){for(var i=e,o=[];t>i;++i)o.push(new oa(u[i],n(i),r));return o}var a=t.from,l=t.to,u=t.text,p=Bn(e,a.line),c=Bn(e,l.line),d=No(u),f=n(u.length-1),h=l.line-a.line;if(t.full){e.insert(0,s(0,u.length));e.remove(u.length,e.size-u.length)}else if(Dn(e,t)){var E=s(0,u.length-1);o(c,c.text,f);h&&e.remove(a.line,h);E.length&&e.insert(a.line,E)}else if(p==c)if(1==u.length)o(p,p.text.slice(0,a.ch)+d+p.text.slice(l.ch),f);else{var E=s(1,u.length-1);E.push(new oa(d+p.text.slice(l.ch),f,r));o(p,p.text.slice(0,a.ch)+u[0],n(0));e.insert(a.line+1,E)}else if(1==u.length){o(p,p.text.slice(0,a.ch)+u[0]+c.text.slice(l.ch),n(0));e.remove(a.line+1,h)}else{o(p,p.text.slice(0,a.ch)+u[0],n(0));o(c,d+c.text.slice(l.ch),f);var E=s(1,u.length-1);h>1&&e.remove(a.line+1,h-1);e.insert(a.line+1,E)}po(e,"change",e,t)}function _n(e){this.lines=e;this.parent=null;for(var t=0,i=0;t<e.length;++t){e[t].parent=this;i+=e[t].height}this.height=i}function Mn(e){this.children=e;for(var t=0,i=0,r=0;r<e.length;++r){var n=e[r];t+=n.chunkSize();i+=n.height;n.parent=this}this.size=t;this.height=i;this.parent=null}function kn(e,t,i){function r(e,n,o){if(e.linked)for(var s=0;s<e.linked.length;++s){var a=e.linked[s];if(a.doc!=n){var l=o&&a.sharedHist;if(!i||l){t(a.doc,l);r(a.doc,e,l)}}}}r(e,null,!0)}function Gn(e,t){if(t.cm)throw new Error("This document is already in use.");e.doc=t;t.cm=e;s(e);i(e);e.options.lineWrapping||d(e);e.options.mode=t.modeOption;xi(e)}function Bn(e,t){t-=e.first;if(0>t||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var i=e;!i.lines;)for(var r=0;;++r){var n=i.children[r],o=n.chunkSize();if(o>t){i=n;break}t-=o}return i.lines[t]}function Un(e,t,i){var r=[],n=t.line;e.iter(t.line,i.line+1,function(e){var o=e.text;n==i.line&&(o=o.slice(0,i.ch));n==t.line&&(o=o.slice(t.ch));r.push(o);++n});return r}function Vn(e,t,i){var r=[];e.iter(t,i,function(e){r.push(e.text)});return r}function Fn(e,t){var i=t-e.height;if(i)for(var r=e;r;r=r.parent)r.height+=i}function Hn(e){if(null==e.parent)return null;for(var t=e.parent,i=To(t.lines,e),r=t.parent;r;t=r,r=r.parent)for(var n=0;r.children[n]!=t;++n)i+=r.children[n].chunkSize();return i+t.first}function jn(e,t){var i=e.first;e:do{for(var r=0;r<e.children.length;++r){var n=e.children[r],o=n.height;if(o>t){e=n;continue e}t-=o;i+=n.chunkSize()}return i}while(!e.lines);for(var r=0;r<e.lines.length;++r){var s=e.lines[r],a=s.height;if(a>t)break;t-=a}return i+r}function Wn(e){e=on(e);for(var t=0,i=e.parent,r=0;r<i.lines.length;++r){var n=i.lines[r];if(n==e)break;t+=n.height}for(var o=i.parent;o;i=o,o=i.parent)for(var r=0;r<o.children.length;++r){var s=o.children[r];if(s==i)break;t+=s.height}return t}function qn(e){var t=e.order;null==t&&(t=e.order=ja(e.text));return t}function zn(e){this.done=[];this.undone=[];this.undoDepth=1/0;this.lastModTime=this.lastSelTime=0;this.lastOp=this.lastSelOp=null;this.lastOrigin=this.lastSelOrigin=null;this.generation=this.maxGeneration=e||1}function Xn(e,t){var i={from:X(t.from),to:Bs(t),text:Un(e,t.from,t.to)};eo(e,i,t.from.line,t.to.line+1);kn(e,function(e){eo(e,i,t.from.line,t.to.line+1)},!0);return i}function Yn(e){for(;e.length;){var t=No(e);if(!t.ranges)break;e.pop()}}function Kn(e,t){if(t){Yn(e.done);return No(e.done)}if(e.done.length&&!No(e.done).ranges)return No(e.done);if(e.done.length>1&&!e.done[e.done.length-2].ranges){e.done.pop();return No(e.done)}}function $n(e,t,i,r){var n=e.history;n.undone.length=0;var o,s=+new Date;if((n.lastOp==r||n.lastOrigin==t.origin&&t.origin&&("+"==t.origin.charAt(0)&&e.cm&&n.lastModTime>s-e.cm.options.historyEventDelay||"*"==t.origin.charAt(0)))&&(o=Kn(n,n.lastOp==r))){var a=No(o.changes);0==ys(t.from,t.to)&&0==ys(t.from,a.to)?a.to=Bs(t):o.changes.push(Xn(e,t))}else{var l=No(n.done);l&&l.ranges||Jn(e.sel,n.done);o={changes:[Xn(e,t)],generation:n.generation};n.done.push(o);for(;n.done.length>n.undoDepth;){n.done.shift();n.done[0].ranges||n.done.shift()}}n.done.push(i);n.generation=++n.maxGeneration;n.lastModTime=n.lastSelTime=s;n.lastOp=n.lastSelOp=r;n.lastOrigin=n.lastSelOrigin=t.origin;a||ga(e,"historyAdded")}function Qn(e,t,i,r){var n=t.charAt(0);return"*"==n||"+"==n&&i.ranges.length==r.ranges.length&&i.somethingSelected()==r.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}function Zn(e,t,i,r){var n=e.history,o=r&&r.origin;i==n.lastSelOp||o&&n.lastSelOrigin==o&&(n.lastModTime==n.lastSelTime&&n.lastOrigin==o||Qn(e,o,No(n.done),t))?n.done[n.done.length-1]=t:Jn(t,n.done);n.lastSelTime=+new Date;n.lastSelOrigin=o;n.lastSelOp=i;r&&r.clearRedo!==!1&&Yn(n.undone)}function Jn(e,t){var i=No(t);i&&i.ranges&&i.equals(e)||t.push(e)}function eo(e,t,i,r){var n=t["spans_"+e.id],o=0;e.iter(Math.max(e.first,i),Math.min(e.first+e.size,r),function(i){i.markedSpans&&((n||(n=t["spans_"+e.id]={}))[o]=i.markedSpans);++o})}function to(e){if(!e)return null;for(var t,i=0;i<e.length;++i)e[i].marker.explicitlyCleared?t||(t=e.slice(0,i)):t&&t.push(e[i]);return t?t.length?t:null:e}function io(e,t){var i=t["spans_"+e.id];if(!i)return null;for(var r=0,n=[];r<t.text.length;++r)n.push(to(i[r]));return n}function ro(e,t,i){for(var r=0,n=[];r<e.length;++r){var o=e[r];if(o.ranges)n.push(i?$.prototype.deepCopy.call(o):o);else{var s=o.changes,a=[];n.push({changes:a});for(var l=0;l<s.length;++l){var u,p=s[l];a.push({from:p.from,to:p.to,text:p.text});if(t)for(var c in p)if((u=c.match(/^spans_(\d+)$/))&&To(t,Number(u[1]))>-1){No(a)[c]=p[c];delete p[c]}}}}return n}function no(e,t,i,r){if(i<e.line)e.line+=r;else if(t<e.line){e.line=t;e.ch=0}}function oo(e,t,i,r){for(var n=0;n<e.length;++n){var o=e[n],s=!0;if(o.ranges){if(!o.copied){o=e[n]=o.deepCopy();o.copied=!0}for(var a=0;a<o.ranges.length;a++){no(o.ranges[a].anchor,t,i,r);no(o.ranges[a].head,t,i,r)}}else{for(var a=0;a<o.changes.length;++a){var l=o.changes[a];if(i<l.from.line){l.from=Is(l.from.line+r,l.from.ch);l.to=Is(l.to.line+r,l.to.ch)}else if(t<=l.to.line){s=!1;break}}if(!s){e.splice(0,n+1);n=0}}}}function so(e,t){var i=t.from.line,r=t.to.line,n=t.text.length-(r-i)-1;oo(e.done,i,r,n);oo(e.undone,i,r,n)}function ao(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function lo(e){return e.target||e.srcElement}function uo(e){var t=e.which;null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2));ms&&e.ctrlKey&&1==t&&(t=3);return t}function po(e,t){function i(e){return function(){e.apply(null,o)}}var r=e._handlers&&e._handlers[t];if(r){var n,o=Array.prototype.slice.call(arguments,2);if(bs)n=bs.delayedCallbacks;else if(va)n=va;else{n=va=[];setTimeout(co,0)}for(var s=0;s<r.length;++s)n.push(i(r[s]))}}function co(){var e=va;va=null;for(var t=0;t<e.length;++t)e[t]()}function fo(e,t,i){"string"==typeof t&&(t={type:t,preventDefault:function(){this.defaultPrevented=!0}});ga(e,i||t.type,e,t);return ao(t)||t.codemirrorIgnore}function ho(e){var t=e._handlers&&e._handlers.cursorActivity;if(t)for(var i=e.curOp.cursorActivityHandlers||(e.curOp.cursorActivityHandlers=[]),r=0;r<t.length;++r)-1==To(i,t[r])&&i.push(t[r])}function Eo(e,t){var i=e._handlers&&e._handlers[t];return i&&i.length>0}function mo(e){e.prototype.on=function(e,t){Ea(this,e,t)};e.prototype.off=function(e,t){ma(this,e,t)}}function go(){this.id=null}function vo(e,t,i){for(var r=0,n=0;;){var o=e.indexOf(" ",r);-1==o&&(o=e.length);var s=o-r;if(o==e.length||n+s>=t)return r+Math.min(s,t-n);n+=o-r;n+=i-n%i;r=o+1;if(n>=t)return r}}function xo(e){for(;Aa.length<=e;)Aa.push(No(Aa)+" ");return Aa[e]}function No(e){return e[e.length-1]}function To(e,t){for(var i=0;i<e.length;++i)if(e[i]==t)return i;return-1}function Lo(e,t){for(var i=[],r=0;r<e.length;r++)i[r]=t(e[r],r);return i}function Io(e,t){var i;if(Object.create)i=Object.create(e);else{var r=function(){};r.prototype=e;i=new r}t&&yo(t,i);return i}function yo(e,t,i){t||(t={});for(var r in e)!e.hasOwnProperty(r)||i===!1&&t.hasOwnProperty(r)||(t[r]=e[r]);return t}function Ao(e){var t=Array.prototype.slice.call(arguments,1);return function(){return e.apply(null,t)}}function So(e,t){return t?t.source.indexOf("\\w")>-1&&ba(e)?!0:t.test(e):ba(e)}function Co(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}function Ro(e){return e.charCodeAt(0)>=768&&Oa.test(e)}function bo(e,t,i,r){var n=document.createElement(e);i&&(n.className=i);r&&(n.style.cssText=r);if("string"==typeof t)n.appendChild(document.createTextNode(t));else if(t)for(var o=0;o<t.length;++o)n.appendChild(t[o]);return n}function Oo(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function Po(e,t){return Oo(e).appendChild(t)}function Do(e,t){if(e.contains)return e.contains(t);for(;t=t.parentNode;)if(t==e)return!0}function wo(){return document.activeElement}function _o(e){return new RegExp("(^|\\s)"+e+"(?:$|\\s)\\s*")}function Mo(e,t){for(var i=e.split(" "),r=0;r<i.length;r++)i[r]&&!_o(i[r]).test(t)&&(t+=" "+i[r]);return t}function ko(e){if(document.body.getElementsByClassName)for(var t=document.body.getElementsByClassName("CodeMirror"),i=0;i<t.length;i++){var r=t[i].CodeMirror;r&&e(r)}}function Go(){if(!Ma){Bo();Ma=!0}}function Bo(){var e;Ea(window,"resize",function(){null==e&&(e=setTimeout(function(){e=null;ko(_i)},100))});Ea(window,"blur",function(){ko(nr)})}function Uo(e){if(null==Pa){var t=bo("span","​");Po(e,bo("span",[t,document.createTextNode("x")]));0!=e.firstChild.offsetHeight&&(Pa=t.offsetWidth<=1&&t.offsetHeight>2&&!(ns&&8>os))}return Pa?bo("span","​"):bo("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")}function Vo(e){if(null!=Da)return Da;var t=Po(e,document.createTextNode("AخA")),i=Ca(t,0,1).getBoundingClientRect();if(!i||i.left==i.right)return!1;var r=Ca(t,1,2).getBoundingClientRect();return Da=r.right-i.right<3}function Fo(e){if(null!=Va)return Va;var t=Po(e,bo("span","x")),i=t.getBoundingClientRect(),r=Ca(t,0,1).getBoundingClientRect();return Va=Math.abs(i.left-r.left)>1}function Ho(e,t,i,r){if(!e)return r(t,i,"ltr");for(var n=!1,o=0;o<e.length;++o){var s=e[o];if(s.from<i&&s.to>t||t==i&&s.to==t){r(Math.max(s.from,t),Math.min(s.to,i),1==s.level?"rtl":"ltr");n=!0}}n||r(t,i,"ltr")}function jo(e){return e.level%2?e.to:e.from}function Wo(e){return e.level%2?e.from:e.to}function qo(e){var t=qn(e);return t?jo(t[0]):0}function zo(e){var t=qn(e);return t?Wo(No(t)):e.text.length}function Xo(e,t){var i=Bn(e.doc,t),r=on(i);r!=i&&(t=Hn(r));var n=qn(r),o=n?n[0].level%2?zo(r):qo(r):0;return Is(t,o)}function Yo(e,t){for(var i,r=Bn(e.doc,t);i=rn(r);){r=i.find(1,!0).line;t=null}var n=qn(r),o=n?n[0].level%2?qo(r):zo(r):r.text.length;return Is(null==t?Hn(r):t,o)}function Ko(e,t){var i=Xo(e,t.line),r=Bn(e.doc,i.line),n=qn(r);if(!n||0==n[0].level){var o=Math.max(0,r.text.search(/\S/)),s=t.line==i.line&&t.ch<=o&&t.ch;return Is(i.line,s?0:o)}return i}function $o(e,t,i){var r=e[0].level;return t==r?!0:i==r?!1:i>t}function Qo(e,t){Ha=null;for(var i,r=0;r<e.length;++r){var n=e[r];if(n.from<t&&n.to>t)return r;if(n.from==t||n.to==t){if(null!=i){if($o(e,n.level,e[i].level)){n.from!=n.to&&(Ha=i);return r}n.from!=n.to&&(Ha=r);return i}i=r}}return i}function Zo(e,t,i,r){if(!r)return t+i;do t+=i;while(t>0&&Ro(e.text.charAt(t)));return t}function Jo(e,t,i,r){var n=qn(e);if(!n)return es(e,t,i,r);for(var o=Qo(n,t),s=n[o],a=Zo(e,t,s.level%2?-i:i,r);;){if(a>s.from&&a<s.to)return a;if(a==s.from||a==s.to){if(Qo(n,a)==o)return a;s=n[o+=i];return i>0==s.level%2?s.to:s.from}s=n[o+=i];if(!s)return null;a=i>0==s.level%2?Zo(e,s.to,-1,r):Zo(e,s.from,1,r)}}function es(e,t,i,r){var n=t+i;if(r)for(;n>0&&Ro(e.text.charAt(n));)n+=i;return 0>n||n>e.text.length?null:n}var ts=/gecko\/\d/i.test(navigator.userAgent),is=/MSIE \d/.test(navigator.userAgent),rs=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),ns=is||rs,os=ns&&(is?document.documentMode||6:rs[1]),ss=/WebKit\//.test(navigator.userAgent),as=ss&&/Qt\/\d+\.\d+/.test(navigator.userAgent),ls=/Chrome\//.test(navigator.userAgent),us=/Opera\//.test(navigator.userAgent),ps=/Apple Computer/.test(navigator.vendor),cs=/KHTML\//.test(navigator.userAgent),ds=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),fs=/PhantomJS/.test(navigator.userAgent),hs=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),Es=hs||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),ms=hs||/Mac/.test(navigator.platform),gs=/win/i.test(navigator.platform),vs=us&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);vs&&(vs=Number(vs[1]));if(vs&&vs>=15){us=!1;ss=!0}var xs=ms&&(as||us&&(null==vs||12.11>vs)),Ns=ts||ns&&os>=9,Ts=!1,Ls=!1;E.prototype=yo({update:function(e){var t=e.scrollWidth>e.clientWidth+1,i=e.scrollHeight>e.clientHeight+1,r=e.nativeBarWidth;if(i){this.vert.style.display="block";this.vert.style.bottom=t?r+"px":"0";var n=e.viewHeight-(t?r:0);this.vert.firstChild.style.height=Math.max(0,e.scrollHeight-e.clientHeight+n)+"px"}else{this.vert.style.display="";this.vert.firstChild.style.height="0"}if(t){this.horiz.style.display="block";this.horiz.style.right=i?r+"px":"0";this.horiz.style.left=e.barLeft+"px";var o=e.viewWidth-e.barLeft-(i?r:0);this.horiz.firstChild.style.width=e.scrollWidth-e.clientWidth+o+"px"}else{this.horiz.style.display="";this.horiz.firstChild.style.width="0"}if(!this.checkedOverlay&&e.clientHeight>0){0==r&&this.overlayHack();this.checkedOverlay=!0}return{right:i?r:0,bottom:t?r:0}},setScrollLeft:function(e){this.horiz.scrollLeft!=e&&(this.horiz.scrollLeft=e)},setScrollTop:function(e){this.vert.scrollTop!=e&&(this.vert.scrollTop=e)},overlayHack:function(){var e=ms&&!ds?"12px":"18px";this.horiz.style.minHeight=this.vert.style.minWidth=e;var t=this,i=function(e){lo(e)!=t.vert&&lo(e)!=t.horiz&&hi(t.cm,Gi)(e)};Ea(this.vert,"mousedown",i);Ea(this.horiz,"mousedown",i)},clear:function(){var e=this.horiz.parentNode;e.removeChild(this.horiz);e.removeChild(this.vert)}},E.prototype);m.prototype=yo({update:function(){return{bottom:0,right:0}},setScrollLeft:function(){},setScrollTop:function(){},clear:function(){}},m.prototype);e.scrollbarModel={"native":E,"null":m};var Is=e.Pos=function(e,t){if(!(this instanceof Is))return new Is(e,t);this.line=e;this.ch=t},ys=e.cmpPos=function(e,t){return e.line-t.line||e.ch-t.ch};$.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(e){if(e==this)return!0;if(e.primIndex!=this.primIndex||e.ranges.length!=this.ranges.length)return!1;for(var t=0;t<this.ranges.length;t++){var i=this.ranges[t],r=e.ranges[t];if(0!=ys(i.anchor,r.anchor)||0!=ys(i.head,r.head))return!1}return!0},deepCopy:function(){for(var e=[],t=0;t<this.ranges.length;t++)e[t]=new Q(X(this.ranges[t].anchor),X(this.ranges[t].head));return new $(e,this.primIndex)},somethingSelected:function(){for(var e=0;e<this.ranges.length;e++)if(!this.ranges[e].empty())return!0;return!1},contains:function(e,t){t||(t=e);for(var i=0;i<this.ranges.length;i++){var r=this.ranges[i];if(ys(t,r.from())>=0&&ys(e,r.to())<=0)return i}return-1}};Q.prototype={from:function(){return K(this.anchor,this.head)},to:function(){return Y(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var As,Ss,Cs,Rs={left:0,right:0,top:0,bottom:0},bs=null,Os=0,Ps=null,Ds=0,ws=0,_s=null;ns?_s=-.53:ts?_s=15:ls?_s=-.7:ps&&(_s=-1/3);var Ms=function(e){var t=e.wheelDeltaX,i=e.wheelDeltaY;null==t&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(t=e.detail);null==i&&e.detail&&e.axis==e.VERTICAL_AXIS?i=e.detail:null==i&&(i=e.wheelDelta);return{x:t,y:i}};e.wheelEventPixels=function(e){var t=Ms(e);t.x*=_s;t.y*=_s;return t};var ks=new go,Gs=null,Bs=e.changeEnd=function(e){return e.text?Is(e.from.line+e.text.length-1,No(e.text).length+(1==e.text.length?e.from.ch:0)):e.to};e.prototype={constructor:e,focus:function(){window.focus();Oi(this);Ci(this)},setOption:function(e,t){var i=this.options,r=i[e];if(i[e]!=t||"mode"==e){i[e]=t;Vs.hasOwnProperty(e)&&hi(this,Vs[e])(this,t,r)}},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](wr(e))},removeKeyMap:function(e){for(var t=this.state.keyMaps,i=0;i<t.length;++i)if(t[i]==e||t[i].name==e){t.splice(i,1);return!0}},addOverlay:Ei(function(t,i){var r=t.token?t:e.getMode(this.options,t);if(r.startState)throw new Error("Overlays may not be stateful.");this.state.overlays.push({mode:r,modeSpec:t,opaque:i&&i.opaque});this.state.modeGen++;xi(this)}),removeOverlay:Ei(function(e){for(var t=this.state.overlays,i=0;i<t.length;++i){var r=t[i].modeSpec;if(r==e||"string"==typeof e&&r.name==e){t.splice(i,1);this.state.modeGen++;xi(this);return}}}),indentLine:Ei(function(e,t,i){"string"!=typeof t&&"number"!=typeof t&&(t=null==t?this.options.smartIndent?"smart":"prev":t?"add":"subtract");rt(this.doc,e)&&Sr(this,e,t,i)}),indentSelection:Ei(function(e){for(var t=this.doc.sel.ranges,i=-1,r=0;r<t.length;r++){var n=t[r];if(n.empty()){if(n.head.line>i){Sr(this,n.head.line,e,!0);i=n.head.line;r==this.doc.sel.primIndex&&yr(this)}}else{var o=n.from(),s=n.to(),a=Math.max(i,o.line);i=Math.min(this.lastLine(),s.line-(s.ch?0:1))+1;for(var l=a;i>l;++l)Sr(this,l,e);var u=this.doc.sel.ranges;0==o.ch&&t.length==u.length&&u[r].from().ch>0&&lt(this.doc,r,new Q(o,u[r].to()),Ta)}}}),getTokenAt:function(e,t){return xn(this,e,t)},getLineTokens:function(e,t){return xn(this,Is(e),t,!0)},getTokenTypeAt:function(e){e=tt(this.doc,e);var t,i=Ln(this,Bn(this.doc,e.line)),r=0,n=(i.length-1)/2,o=e.ch;if(0==o)t=i[2];else for(;;){var s=r+n>>1;if((s?i[2*s-1]:0)>=o)n=s;else{if(!(i[2*s+1]<o)){t=i[2*s+2];break}r=s+1}}var a=t?t.indexOf("cm-overlay "):-1;return 0>a?t:0==a?null:t.slice(0,a-1)},getModeAt:function(t){var i=this.doc.mode;return i.innerMode?e.innerMode(i,this.getTokenAt(t).state).mode:i},getHelper:function(e,t){return this.getHelpers(e,t)[0]},getHelpers:function(e,t){var i=[];if(!zs.hasOwnProperty(t))return zs;var r=zs[t],n=this.getModeAt(e);if("string"==typeof n[t])r[n[t]]&&i.push(r[n[t]]);else if(n[t])for(var o=0;o<n[t].length;o++){var s=r[n[t][o]];s&&i.push(s)}else n.helperType&&r[n.helperType]?i.push(r[n.helperType]):r[n.name]&&i.push(r[n.name]);for(var o=0;o<r._global.length;o++){var a=r._global[o];a.pred(n,this)&&-1==To(i,a.val)&&i.push(a.val)}return i},getStateAfter:function(e,t){var i=this.doc;e=et(i,null==e?i.first+i.size-1:e);return Ct(this,e+1,t)},cursorCoords:function(e,t){var i,r=this.doc.sel.primary();i=null==e?r.head:"object"==typeof e?tt(this.doc,e):e?r.from():r.to();return Qt(this,i,t||"page")},charCoords:function(e,t){return $t(this,tt(this.doc,e),t||"page")},coordsChar:function(e,t){e=Kt(this,e,t||"page");return ei(this,e.left,e.top)},lineAtHeight:function(e,t){e=Kt(this,{top:e,left:0},t||"page").top;return jn(this.doc,e+this.display.viewOffset)},heightAtLine:function(e,t){var i=!1,r=this.doc.first+this.doc.size-1;if(e<this.doc.first)e=this.doc.first;else if(e>r){e=r;i=!0}var n=Bn(this.doc,e);return Yt(this,n,{top:0,left:0},t||"page").top+(i?this.doc.height-Wn(n):0)},defaultTextHeight:function(){return ii(this.display)},defaultCharWidth:function(){return ri(this.display)},setGutterMarker:Ei(function(e,t,i){return Cr(this.doc,e,"gutter",function(e){var r=e.gutterMarkers||(e.gutterMarkers={});r[t]=i;!i&&Co(r)&&(e.gutterMarkers=null);return!0})}),clearGutter:Ei(function(e){var t=this,i=t.doc,r=i.first;i.iter(function(i){if(i.gutterMarkers&&i.gutterMarkers[e]){i.gutterMarkers[e]=null;Ni(t,r,"gutter");Co(i.gutterMarkers)&&(i.gutterMarkers=null)}++r})}),addLineWidget:Ei(function(e,t,i){return fn(this,e,t,i)}),removeLineWidget:function(e){e.clear()},lineInfo:function(e){if("number"==typeof e){if(!rt(this.doc,e))return null;var t=e;e=Bn(this.doc,e);if(!e)return null}else{var t=Hn(e);if(null==t)return null}return{line:t,handle:e,text:e.text,gutterMarkers:e.gutterMarkers,textClass:e.textClass,bgClass:e.bgClass,wrapClass:e.wrapClass,widgets:e.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,i,r,n){var o=this.display;e=Qt(this,tt(this.doc,e));var s=e.bottom,a=e.left;t.style.position="absolute";t.setAttribute("cm-ignore-events","true");o.sizer.appendChild(t);if("over"==r)s=e.top;else if("above"==r||"near"==r){var l=Math.max(o.wrapper.clientHeight,this.doc.height),u=Math.max(o.sizer.clientWidth,o.lineSpace.clientWidth);("above"==r||e.bottom+t.offsetHeight>l)&&e.top>t.offsetHeight?s=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=l&&(s=e.bottom);a+t.offsetWidth>u&&(a=u-t.offsetWidth)}t.style.top=s+"px";t.style.left=t.style.right="";if("right"==n){a=o.sizer.clientWidth-t.offsetWidth;t.style.right="0px"}else{"left"==n?a=0:"middle"==n&&(a=(o.sizer.clientWidth-t.offsetWidth)/2);t.style.left=a+"px"}i&&Tr(this,a,s,a+t.offsetWidth,s+t.offsetHeight)},triggerOnKeyDown:Ei(Ji),triggerOnKeyPress:Ei(ir),triggerOnKeyUp:tr,execCommand:function(e){return Ks.hasOwnProperty(e)?Ks[e](this):void 0},findPosH:function(e,t,i,r){var n=1;if(0>t){n=-1;t=-t}for(var o=0,s=tt(this.doc,e);t>o;++o){s=br(this.doc,s,n,i,r);if(s.hitSide)break}return s},moveH:Ei(function(e,t){var i=this;i.extendSelectionsBy(function(r){return i.display.shift||i.doc.extend||r.empty()?br(i.doc,r.head,e,t,i.options.rtlMoveVisually):0>e?r.from():r.to()},Ia)}),deleteH:Ei(function(e,t){var i=this.doc.sel,r=this.doc;i.somethingSelected()?r.replaceSelection("",null,"+delete"):Rr(this,function(i){var n=br(r,i.head,e,t,!1);return 0>e?{from:n,to:i.head}:{from:i.head,to:n}})}),findPosV:function(e,t,i,r){var n=1,o=r;if(0>t){n=-1;t=-t}for(var s=0,a=tt(this.doc,e);t>s;++s){var l=Qt(this,a,"div");null==o?o=l.left:l.left=o;a=Or(this,l,n,i);if(a.hitSide)break}return a},moveV:Ei(function(e,t){var i=this,r=this.doc,n=[],o=!i.display.shift&&!r.extend&&r.sel.somethingSelected();r.extendSelectionsBy(function(s){if(o)return 0>e?s.from():s.to();var a=Qt(i,s.head,"div");null!=s.goalColumn&&(a.left=s.goalColumn);n.push(a.left);var l=Or(i,a,e,t); "page"==t&&s==r.sel.primary()&&Ir(i,null,$t(i,l,"div").top-a.top);return l},Ia);if(n.length)for(var s=0;s<r.sel.ranges.length;s++)r.sel.ranges[s].goalColumn=n[s]}),findWordAt:function(e){var t=this.doc,i=Bn(t,e.line).text,r=e.ch,n=e.ch;if(i){var o=this.getHelper(e,"wordChars");(e.xRel<0||n==i.length)&&r?--r:++n;for(var s=i.charAt(r),a=So(s,o)?function(e){return So(e,o)}:/\s/.test(s)?function(e){return/\s/.test(e)}:function(e){return!/\s/.test(e)&&!So(e)};r>0&&a(i.charAt(r-1));)--r;for(;n<i.length&&a(i.charAt(n));)++n}return new Q(Is(e.line,r),Is(e.line,n))},toggleOverwrite:function(e){if(null==e||e!=this.state.overwrite){(this.state.overwrite=!this.state.overwrite)?_a(this.display.cursorDiv,"CodeMirror-overwrite"):wa(this.display.cursorDiv,"CodeMirror-overwrite");ga(this,"overwriteToggle",this,this.state.overwrite)}},hasFocus:function(){return wo()==this.display.input},scrollTo:Ei(function(e,t){(null!=e||null!=t)&&Ar(this);null!=e&&(this.curOp.scrollLeft=e);null!=t&&(this.curOp.scrollTop=t)}),getScrollInfo:function(){var e=this.display.scroller;return{left:e.scrollLeft,top:e.scrollTop,height:e.scrollHeight-Pt(this)-this.display.barHeight,width:e.scrollWidth-Pt(this)-this.display.barWidth,clientHeight:wt(this),clientWidth:Dt(this)}},scrollIntoView:Ei(function(e,t){if(null==e){e={from:this.doc.sel.primary().head,to:null};null==t&&(t=this.options.cursorScrollMargin)}else"number"==typeof e?e={from:Is(e,0),to:null}:null==e.from&&(e={from:e,to:null});e.to||(e.to=e.from);e.margin=t||0;if(null!=e.from.line){Ar(this);this.curOp.scrollToPos=e}else{var i=Lr(this,Math.min(e.from.left,e.to.left),Math.min(e.from.top,e.to.top)-e.margin,Math.max(e.from.right,e.to.right),Math.max(e.from.bottom,e.to.bottom)+e.margin);this.scrollTo(i.scrollLeft,i.scrollTop)}}),setSize:Ei(function(e,t){function i(e){return"number"==typeof e||/^\d+$/.test(String(e))?e+"px":e}var r=this;null!=e&&(r.display.wrapper.style.width=i(e));null!=t&&(r.display.wrapper.style.height=i(t));r.options.lineWrapping&&Wt(this);var n=r.display.viewFrom;r.doc.iter(n,r.display.viewTo,function(e){if(e.widgets)for(var t=0;t<e.widgets.length;t++)if(e.widgets[t].noHScroll){Ni(r,n,"widget");break}++n});r.curOp.forceUpdate=!0;ga(r,"refresh",this)}),operation:function(e){return fi(this,e)},refresh:Ei(function(){var e=this.display.cachedTextHeight;xi(this);this.curOp.forceUpdate=!0;qt(this);this.scrollTo(this.doc.scrollLeft,this.doc.scrollTop);p(this);(null==e||Math.abs(e-ii(this.display))>.5)&&s(this);ga(this,"refresh",this)}),swapDoc:Ei(function(e){var t=this.doc;t.cm=null;Gn(this,e);qt(this);bi(this);this.scrollTo(e.scrollLeft,e.scrollTop);this.curOp.forceScroll=!0;po(this,"swapDoc",this,t);return t}),getInputField:function(){return this.display.input},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}};mo(e);var Us=e.defaults={},Vs=e.optionHandlers={},Fs=e.Init={toString:function(){return"CodeMirror.Init"}};Pr("value","",function(e,t){e.setValue(t)},!0);Pr("mode",null,function(e,t){e.doc.modeOption=t;i(e)},!0);Pr("indentUnit",2,i,!0);Pr("indentWithTabs",!1);Pr("smartIndent",!0);Pr("tabSize",4,function(e){r(e);qt(e);xi(e)},!0);Pr("specialChars",/[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g,function(e,t){e.options.specialChars=new RegExp(t.source+(t.test(" ")?"":"| "),"g");e.refresh()},!0);Pr("specialCharPlaceholder",Sn,function(e){e.refresh()},!0);Pr("electricChars",!0);Pr("rtlMoveVisually",!gs);Pr("wholeLineUpdateBefore",!0);Pr("theme","default",function(e){a(e);l(e)},!0);Pr("keyMap","default",function(t,i,r){var n=wr(i),o=r!=e.Init&&wr(r);o&&o.detach&&o.detach(t,n);n.attach&&n.attach(t,o||null)});Pr("extraKeys",null);Pr("lineWrapping",!1,n,!0);Pr("gutters",[],function(e){f(e.options);l(e)},!0);Pr("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?y(e.display)+"px":"0";e.refresh()},!0);Pr("coverGutterNextToScrollbar",!1,function(e){v(e)},!0);Pr("scrollbarStyle","native",function(e){g(e);v(e);e.display.scrollbars.setScrollTop(e.doc.scrollTop);e.display.scrollbars.setScrollLeft(e.doc.scrollLeft)},!0);Pr("lineNumbers",!1,function(e){f(e.options);l(e)},!0);Pr("firstLineNumber",1,l,!0);Pr("lineNumberFormatter",function(e){return e},l,!0);Pr("showCursorWhenSelecting",!1,Nt,!0);Pr("resetSelectionOnContextMenu",!0);Pr("readOnly",!1,function(e,t){if("nocursor"==t){nr(e);e.display.input.blur();e.display.disabled=!0}else{e.display.disabled=!1;t||bi(e)}});Pr("disableInput",!1,function(e,t){t||bi(e)},!0);Pr("dragDrop",!0);Pr("cursorBlinkRate",530);Pr("cursorScrollMargin",0);Pr("cursorHeight",1,Nt,!0);Pr("singleCursorHeightPerLine",!0,Nt,!0);Pr("workTime",100);Pr("workDelay",100);Pr("flattenSpans",!0,r,!0);Pr("addModeClass",!1,r,!0);Pr("pollInterval",100);Pr("undoDepth",200,function(e,t){e.doc.history.undoDepth=t});Pr("historyEventDelay",1250);Pr("viewportMargin",10,function(e){e.refresh()},!0);Pr("maxHighlightLength",1e4,r,!0);Pr("moveInputWithCursor",!0,function(e,t){t||(e.display.inputDiv.style.top=e.display.inputDiv.style.left=0)});Pr("tabindex",null,function(e,t){e.display.input.tabIndex=t||""});Pr("autofocus",null);var Hs=e.modes={},js=e.mimeModes={};e.defineMode=function(t,i){e.defaults.mode||"null"==t||(e.defaults.mode=t);arguments.length>2&&(i.dependencies=Array.prototype.slice.call(arguments,2));Hs[t]=i};e.defineMIME=function(e,t){js[e]=t};e.resolveMode=function(t){if("string"==typeof t&&js.hasOwnProperty(t))t=js[t];else if(t&&"string"==typeof t.name&&js.hasOwnProperty(t.name)){var i=js[t.name];"string"==typeof i&&(i={name:i});t=Io(i,t);t.name=i.name}else if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+xml$/.test(t))return e.resolveMode("application/xml");return"string"==typeof t?{name:t}:t||{name:"null"}};e.getMode=function(t,i){var i=e.resolveMode(i),r=Hs[i.name];if(!r)return e.getMode(t,"text/plain");var n=r(t,i);if(Ws.hasOwnProperty(i.name)){var o=Ws[i.name];for(var s in o)if(o.hasOwnProperty(s)){n.hasOwnProperty(s)&&(n["_"+s]=n[s]);n[s]=o[s]}}n.name=i.name;i.helperType&&(n.helperType=i.helperType);if(i.modeProps)for(var s in i.modeProps)n[s]=i.modeProps[s];return n};e.defineMode("null",function(){return{token:function(e){e.skipToEnd()}}});e.defineMIME("text/plain","null");var Ws=e.modeExtensions={};e.extendMode=function(e,t){var i=Ws.hasOwnProperty(e)?Ws[e]:Ws[e]={};yo(t,i)};e.defineExtension=function(t,i){e.prototype[t]=i};e.defineDocExtension=function(e,t){ua.prototype[e]=t};e.defineOption=Pr;var qs=[];e.defineInitHook=function(e){qs.push(e)};var zs=e.helpers={};e.registerHelper=function(t,i,r){zs.hasOwnProperty(t)||(zs[t]=e[t]={_global:[]});zs[t][i]=r};e.registerGlobalHelper=function(t,i,r,n){e.registerHelper(t,i,n);zs[t]._global.push({pred:r,val:n})};var Xs=e.copyState=function(e,t){if(t===!0)return t;if(e.copyState)return e.copyState(t);var i={};for(var r in t){var n=t[r];n instanceof Array&&(n=n.concat([]));i[r]=n}return i},Ys=e.startState=function(e,t,i){return e.startState?e.startState(t,i):!0};e.innerMode=function(e,t){for(;e.innerMode;){var i=e.innerMode(t);if(!i||i.mode==e)break;t=i.state;e=i.mode}return i||{mode:e,state:t}};var Ks=e.commands={selectAll:function(e){e.setSelection(Is(e.firstLine(),0),Is(e.lastLine()),Ta)},singleSelection:function(e){e.setSelection(e.getCursor("anchor"),e.getCursor("head"),Ta)},killLine:function(e){Rr(e,function(t){if(t.empty()){var i=Bn(e.doc,t.head.line).text.length;return t.head.ch==i&&t.head.line<e.lastLine()?{from:t.head,to:Is(t.head.line+1,0)}:{from:t.head,to:Is(t.head.line,i)}}return{from:t.from(),to:t.to()}})},deleteLine:function(e){Rr(e,function(t){return{from:Is(t.from().line,0),to:tt(e.doc,Is(t.to().line+1,0))}})},delLineLeft:function(e){Rr(e,function(e){return{from:Is(e.from().line,0),to:e.from()}})},delWrappedLineLeft:function(e){Rr(e,function(t){var i=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:i},"div");return{from:r,to:t.from()}})},delWrappedLineRight:function(e){Rr(e,function(t){var i=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:i},"div");return{from:t.from(),to:r}})},undo:function(e){e.undo()},redo:function(e){e.redo()},undoSelection:function(e){e.undoSelection()},redoSelection:function(e){e.redoSelection()},goDocStart:function(e){e.extendSelection(Is(e.firstLine(),0))},goDocEnd:function(e){e.extendSelection(Is(e.lastLine()))},goLineStart:function(e){e.extendSelectionsBy(function(t){return Xo(e,t.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(e){e.extendSelectionsBy(function(t){return Ko(e,t.head)},{origin:"+move",bias:1})},goLineEnd:function(e){e.extendSelectionsBy(function(t){return Yo(e,t.head.line)},{origin:"+move",bias:-1})},goLineRight:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:i},"div")},Ia)},goLineLeft:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:0,top:i},"div")},Ia)},goLineLeftSmart:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:i},"div");return r.ch<e.getLine(r.line).search(/\S/)?Ko(e,t.head):r},Ia)},goLineUp:function(e){e.moveV(-1,"line")},goLineDown:function(e){e.moveV(1,"line")},goPageUp:function(e){e.moveV(-1,"page")},goPageDown:function(e){e.moveV(1,"page")},goCharLeft:function(e){e.moveH(-1,"char")},goCharRight:function(e){e.moveH(1,"char")},goColumnLeft:function(e){e.moveH(-1,"column")},goColumnRight:function(e){e.moveH(1,"column")},goWordLeft:function(e){e.moveH(-1,"word")},goGroupRight:function(e){e.moveH(1,"group")},goGroupLeft:function(e){e.moveH(-1,"group")},goWordRight:function(e){e.moveH(1,"word")},delCharBefore:function(e){e.deleteH(-1,"char")},delCharAfter:function(e){e.deleteH(1,"char")},delWordBefore:function(e){e.deleteH(-1,"word")},delWordAfter:function(e){e.deleteH(1,"word")},delGroupBefore:function(e){e.deleteH(-1,"group")},delGroupAfter:function(e){e.deleteH(1,"group")},indentAuto:function(e){e.indentSelection("smart")},indentMore:function(e){e.indentSelection("add")},indentLess:function(e){e.indentSelection("subtract")},insertTab:function(e){e.replaceSelection(" ")},insertSoftTab:function(e){for(var t=[],i=e.listSelections(),r=e.options.tabSize,n=0;n<i.length;n++){var o=i[n].from(),s=ya(e.getLine(o.line),o.ch,r);t.push(new Array(r-s%r+1).join(" "))}e.replaceSelections(t)},defaultTab:function(e){e.somethingSelected()?e.indentSelection("add"):e.execCommand("insertTab")},transposeChars:function(e){fi(e,function(){for(var t=e.listSelections(),i=[],r=0;r<t.length;r++){var n=t[r].head,o=Bn(e.doc,n.line).text;if(o){n.ch==o.length&&(n=new Is(n.line,n.ch-1));if(n.ch>0){n=new Is(n.line,n.ch+1);e.replaceRange(o.charAt(n.ch-1)+o.charAt(n.ch-2),Is(n.line,n.ch-2),n,"+transpose")}else if(n.line>e.doc.first){var s=Bn(e.doc,n.line-1).text;s&&e.replaceRange(o.charAt(0)+"\n"+s.charAt(s.length-1),Is(n.line-1,s.length-1),Is(n.line,1),"+transpose")}}i.push(new Q(n,n))}e.setSelections(i)})},newlineAndIndent:function(e){fi(e,function(){for(var t=e.listSelections().length,i=0;t>i;i++){var r=e.listSelections()[i];e.replaceRange("\n",r.anchor,r.head,"+input");e.indentLine(r.from().line+1,null,!0);yr(e)}})},toggleOverwrite:function(e){e.toggleOverwrite()}},$s=e.keyMap={};$s.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"};$s.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"};$s.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars"};$s.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]};$s["default"]=ms?$s.macDefault:$s.pcDefault;e.normalizeKeyMap=function(e){var t={};for(var i in e)if(e.hasOwnProperty(i)){var r=e[i];if(/^(name|fallthrough|(de|at)tach)$/.test(i))continue;if("..."==r){delete e[i];continue}for(var n=Lo(i.split(" "),Dr),o=0;o<n.length;o++){var s,a;if(o==n.length-1){a=i;s=r}else{a=n.slice(0,o+1).join(" ");s="..."}var l=t[a];if(l){if(l!=s)throw new Error("Inconsistent bindings for "+a)}else t[a]=s}delete e[i]}for(var u in t)e[u]=t[u];return e};var Qs=e.lookupKey=function(e,t,i,r){t=wr(t);var n=t.call?t.call(e,r):t[e];if(n===!1)return"nothing";if("..."===n)return"multi";if(null!=n&&i(n))return"handled";if(t.fallthrough){if("[object Array]"!=Object.prototype.toString.call(t.fallthrough))return Qs(e,t.fallthrough,i,r);for(var o=0;o<t.fallthrough.length;o++){var s=Qs(e,t.fallthrough[o],i,r);if(s)return s}}},Zs=e.isModifierKey=function(e){var t="string"==typeof e?e:Fa[e.keyCode];return"Ctrl"==t||"Alt"==t||"Shift"==t||"Mod"==t},Js=e.keyName=function(e,t){if(us&&34==e.keyCode&&e["char"])return!1;var i=Fa[e.keyCode],r=i;if(null==r||e.altGraphKey)return!1;e.altKey&&"Alt"!=i&&(r="Alt-"+r);(xs?e.metaKey:e.ctrlKey)&&"Ctrl"!=i&&(r="Ctrl-"+r);(xs?e.ctrlKey:e.metaKey)&&"Cmd"!=i&&(r="Cmd-"+r);!t&&e.shiftKey&&"Shift"!=i&&(r="Shift-"+r);return r};e.fromTextArea=function(t,i){function r(){t.value=u.getValue()}i||(i={});i.value=t.value;!i.tabindex&&t.tabindex&&(i.tabindex=t.tabindex);!i.placeholder&&t.placeholder&&(i.placeholder=t.placeholder);if(null==i.autofocus){var n=wo();i.autofocus=n==t||null!=t.getAttribute("autofocus")&&n==document.body}if(t.form){Ea(t.form,"submit",r);if(!i.leaveSubmitMethodAlone){var o=t.form,s=o.submit;try{var a=o.submit=function(){r();o.submit=s;o.submit();o.submit=a}}catch(l){}}}t.style.display="none";var u=e(function(e){t.parentNode.insertBefore(e,t.nextSibling)},i);u.save=r;u.getTextArea=function(){return t};u.toTextArea=function(){u.toTextArea=isNaN;r();t.parentNode.removeChild(u.getWrapperElement());t.style.display="";if(t.form){ma(t.form,"submit",r);"function"==typeof t.form.submit&&(t.form.submit=s)}};return u};var ea=e.StringStream=function(e,t){this.pos=this.start=0;this.string=e;this.tabSize=t||8;this.lastColumnPos=this.lastColumnValue=0;this.lineStart=0};ea.prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){return this.pos<this.string.length?this.string.charAt(this.pos++):void 0},eat:function(e){var t=this.string.charAt(this.pos);if("string"==typeof e)var i=t==e;else var i=t&&(e.test?e.test(t):e(t));if(i){++this.pos;return t}},eatWhile:function(e){for(var t=this.pos;this.eat(e););return this.pos>t},eatSpace:function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},skipToEnd:function(){this.pos=this.string.length},skipTo:function(e){var t=this.string.indexOf(e,this.pos);if(t>-1){this.pos=t;return!0}},backUp:function(e){this.pos-=e},column:function(){if(this.lastColumnPos<this.start){this.lastColumnValue=ya(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue);this.lastColumnPos=this.start}return this.lastColumnValue-(this.lineStart?ya(this.string,this.lineStart,this.tabSize):0)},indentation:function(){return ya(this.string,null,this.tabSize)-(this.lineStart?ya(this.string,this.lineStart,this.tabSize):0)},match:function(e,t,i){if("string"!=typeof e){var r=this.string.slice(this.pos).match(e);if(r&&r.index>0)return null;r&&t!==!1&&(this.pos+=r[0].length);return r}var n=function(e){return i?e.toLowerCase():e},o=this.string.substr(this.pos,e.length);if(n(o)==n(e)){t!==!1&&(this.pos+=e.length);return!0}},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}}};var ta=e.TextMarker=function(e,t){this.lines=[];this.type=t;this.doc=e};mo(ta);ta.prototype.clear=function(){if(!this.explicitlyCleared){var e=this.doc.cm,t=e&&!e.curOp;t&&ni(e);if(Eo(this,"clear")){var i=this.find();i&&po(this,"clear",i.from,i.to)}for(var r=null,n=null,o=0;o<this.lines.length;++o){var s=this.lines[o],a=Vr(s.markedSpans,this);if(e&&!this.collapsed)Ni(e,Hn(s),"text");else if(e){null!=a.to&&(n=Hn(s));null!=a.from&&(r=Hn(s))}s.markedSpans=Fr(s.markedSpans,a);null==a.from&&this.collapsed&&!un(this.doc,s)&&e&&Fn(s,ii(e.display))}if(e&&this.collapsed&&!e.options.lineWrapping)for(var o=0;o<this.lines.length;++o){var l=on(this.lines[o]),u=c(l);if(u>e.display.maxLineLength){e.display.maxLine=l;e.display.maxLineLength=u;e.display.maxLineChanged=!0}}null!=r&&e&&this.collapsed&&xi(e,r,n+1);this.lines.length=0;this.explicitlyCleared=!0;if(this.atomic&&this.doc.cantEdit){this.doc.cantEdit=!1;e&&Et(e.doc)}e&&po(e,"markerCleared",e,this);t&&si(e);this.parent&&this.parent.clear()}};ta.prototype.find=function(e,t){null==e&&"bookmark"==this.type&&(e=1);for(var i,r,n=0;n<this.lines.length;++n){var o=this.lines[n],s=Vr(o.markedSpans,this);if(null!=s.from){i=Is(t?o:Hn(o),s.from);if(-1==e)return i}if(null!=s.to){r=Is(t?o:Hn(o),s.to);if(1==e)return r}}return i&&{from:i,to:r}};ta.prototype.changed=function(){var e=this.find(-1,!0),t=this,i=this.doc.cm;e&&i&&fi(i,function(){var r=e.line,n=Hn(e.line),o=Bt(i,n);if(o){jt(o);i.curOp.selectionChanged=i.curOp.forceUpdate=!0}i.curOp.updateMaxLine=!0;if(!un(t.doc,r)&&null!=t.height){var s=t.height;t.height=null;var a=dn(t)-s;a&&Fn(r,r.height+a)}})};ta.prototype.attachLine=function(e){if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;t.maybeHiddenMarkers&&-1!=To(t.maybeHiddenMarkers,this)||(t.maybeUnhiddenMarkers||(t.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(e)};ta.prototype.detachLine=function(e){this.lines.splice(To(this.lines,e),1);if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;(t.maybeHiddenMarkers||(t.maybeHiddenMarkers=[])).push(this)}};var ia=0,ra=e.SharedTextMarker=function(e,t){this.markers=e;this.primary=t;for(var i=0;i<e.length;++i)e[i].parent=this};mo(ra);ra.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var e=0;e<this.markers.length;++e)this.markers[e].clear();po(this,"clear")}};ra.prototype.find=function(e,t){return this.primary.find(e,t)};var na=e.LineWidget=function(e,t,i){if(i)for(var r in i)i.hasOwnProperty(r)&&(this[r]=i[r]);this.cm=e;this.node=t};mo(na);na.prototype.clear=function(){var e=this.cm,t=this.line.widgets,i=this.line,r=Hn(i);if(null!=r&&t){for(var n=0;n<t.length;++n)t[n]==this&&t.splice(n--,1);t.length||(i.widgets=null);var o=dn(this);fi(e,function(){cn(e,i,-o);Ni(e,r,"widget");Fn(i,Math.max(0,i.height-o))})}};na.prototype.changed=function(){var e=this.height,t=this.cm,i=this.line;this.height=null;var r=dn(this)-e;r&&fi(t,function(){t.curOp.forceUpdate=!0;cn(t,i,r);Fn(i,i.height+r)})};var oa=e.Line=function(e,t,i){this.text=e;$r(this,t);this.height=i?i(this):1};mo(oa);oa.prototype.lineNo=function(){return Hn(this)};var sa={},aa={};_n.prototype={chunkSize:function(){return this.lines.length},removeInner:function(e,t){for(var i=e,r=e+t;r>i;++i){var n=this.lines[i];this.height-=n.height;En(n);po(n,"delete")}this.lines.splice(e,t)},collapse:function(e){e.push.apply(e,this.lines)},insertInner:function(e,t,i){this.height+=i;this.lines=this.lines.slice(0,e).concat(t).concat(this.lines.slice(e));for(var r=0;r<t.length;++r)t[r].parent=this},iterN:function(e,t,i){for(var r=e+t;r>e;++e)if(i(this.lines[e]))return!0}};Mn.prototype={chunkSize:function(){return this.size},removeInner:function(e,t){this.size-=t;for(var i=0;i<this.children.length;++i){var r=this.children[i],n=r.chunkSize();if(n>e){var o=Math.min(t,n-e),s=r.height;r.removeInner(e,o);this.height-=s-r.height;if(n==o){this.children.splice(i--,1);r.parent=null}if(0==(t-=o))break;e=0}else e-=n}if(this.size-t<25&&(this.children.length>1||!(this.children[0]instanceof _n))){var a=[];this.collapse(a);this.children=[new _n(a)];this.children[0].parent=this}},collapse:function(e){for(var t=0;t<this.children.length;++t)this.children[t].collapse(e)},insertInner:function(e,t,i){this.size+=t.length;this.height+=i;for(var r=0;r<this.children.length;++r){var n=this.children[r],o=n.chunkSize();if(o>=e){n.insertInner(e,t,i);if(n.lines&&n.lines.length>50){for(;n.lines.length>50;){var s=n.lines.splice(n.lines.length-25,25),a=new _n(s);n.height-=a.height;this.children.splice(r+1,0,a);a.parent=this}this.maybeSpill()}break}e-=o}},maybeSpill:function(){if(!(this.children.length<=10)){var e=this;do{var t=e.children.splice(e.children.length-5,5),i=new Mn(t);if(e.parent){e.size-=i.size;e.height-=i.height;var r=To(e.parent.children,e);e.parent.children.splice(r+1,0,i)}else{var n=new Mn(e.children);n.parent=e;e.children=[n,i];e=n}i.parent=e.parent}while(e.children.length>10);e.parent.maybeSpill()}},iterN:function(e,t,i){for(var r=0;r<this.children.length;++r){var n=this.children[r],o=n.chunkSize();if(o>e){var s=Math.min(t,o-e);if(n.iterN(e,s,i))return!0;if(0==(t-=s))break;e=0}else e-=o}}};var la=0,ua=e.Doc=function(e,t,i){if(!(this instanceof ua))return new ua(e,t,i);null==i&&(i=0);Mn.call(this,[new _n([new oa("",null)])]);this.first=i;this.scrollTop=this.scrollLeft=0;this.cantEdit=!1;this.cleanGeneration=1;this.frontier=i;var r=Is(i,0);this.sel=J(r);this.history=new zn(null);this.id=++la;this.modeOption=t;"string"==typeof e&&(e=Ga(e));wn(this,{from:r,to:r,text:e});dt(this,J(r),Ta)};ua.prototype=Io(Mn.prototype,{constructor:ua,iter:function(e,t,i){i?this.iterN(e-this.first,t-e,i):this.iterN(this.first,this.first+this.size,e)},insert:function(e,t){for(var i=0,r=0;r<t.length;++r)i+=t[r].height;this.insertInner(e-this.first,t,i)},remove:function(e,t){this.removeInner(e-this.first,t)},getValue:function(e){var t=Vn(this,this.first,this.first+this.size);return e===!1?t:t.join(e||"\n")},setValue:mi(function(e){var t=Is(this.first,0),i=this.first+this.size-1;dr(this,{from:t,to:Is(i,Bn(this,i).text.length),text:Ga(e),origin:"setValue",full:!0},!0);dt(this,J(t))}),replaceRange:function(e,t,i,r){t=tt(this,t);i=i?tt(this,i):t;vr(this,e,t,i,r)},getRange:function(e,t,i){var r=Un(this,tt(this,e),tt(this,t));return i===!1?r:r.join(i||"\n")},getLine:function(e){var t=this.getLineHandle(e);return t&&t.text},getLineHandle:function(e){return rt(this,e)?Bn(this,e):void 0},getLineNumber:function(e){return Hn(e)},getLineHandleVisualStart:function(e){"number"==typeof e&&(e=Bn(this,e));return on(e)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(e){return tt(this,e)},getCursor:function(e){var t,i=this.sel.primary();t=null==e||"head"==e?i.head:"anchor"==e?i.anchor:"end"==e||"to"==e||e===!1?i.to():i.from();return t},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:mi(function(e,t,i){ut(this,tt(this,"number"==typeof e?Is(e,t||0):e),null,i)}),setSelection:mi(function(e,t,i){ut(this,tt(this,e),tt(this,t||e),i)}),extendSelection:mi(function(e,t,i){st(this,tt(this,e),t&&tt(this,t),i)}),extendSelections:mi(function(e,t){at(this,nt(this,e,t))}),extendSelectionsBy:mi(function(e,t){at(this,Lo(this.sel.ranges,e),t)}),setSelections:mi(function(e,t,i){if(e.length){for(var r=0,n=[];r<e.length;r++)n[r]=new Q(tt(this,e[r].anchor),tt(this,e[r].head));null==t&&(t=Math.min(e.length-1,this.sel.primIndex));dt(this,Z(n,t),i)}}),addSelection:mi(function(e,t,i){var r=this.sel.ranges.slice(0);r.push(new Q(tt(this,e),tt(this,t||e)));dt(this,Z(r,r.length-1),i)}),getSelection:function(e){for(var t,i=this.sel.ranges,r=0;r<i.length;r++){var n=Un(this,i[r].from(),i[r].to());t=t?t.concat(n):n}return e===!1?t:t.join(e||"\n")},getSelections:function(e){for(var t=[],i=this.sel.ranges,r=0;r<i.length;r++){var n=Un(this,i[r].from(),i[r].to());e!==!1&&(n=n.join(e||"\n"));t[r]=n}return t},replaceSelection:function(e,t,i){for(var r=[],n=0;n<this.sel.ranges.length;n++)r[n]=e;this.replaceSelections(r,t,i||"+input")},replaceSelections:mi(function(e,t,i){for(var r=[],n=this.sel,o=0;o<n.ranges.length;o++){var s=n.ranges[o];r[o]={from:s.from(),to:s.to(),text:Ga(e[o]),origin:i}}for(var a=t&&"end"!=t&&pr(this,r,t),o=r.length-1;o>=0;o--)dr(this,r[o]);a?ct(this,a):this.cm&&yr(this.cm)}),undo:mi(function(){hr(this,"undo")}),redo:mi(function(){hr(this,"redo")}),undoSelection:mi(function(){hr(this,"undo",!0)}),redoSelection:mi(function(){hr(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,i=0,r=0;r<e.done.length;r++)e.done[r].ranges||++t;for(var r=0;r<e.undone.length;r++)e.undone[r].ranges||++i;return{undo:t,redo:i}},clearHistory:function(){this.history=new zn(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(e){e&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null);return this.history.generation},isClean:function(e){return this.history.generation==(e||this.cleanGeneration)},getHistory:function(){return{done:ro(this.history.done),undone:ro(this.history.undone)}},setHistory:function(e){var t=this.history=new zn(this.history.maxGeneration);t.done=ro(e.done.slice(0),null,!0);t.undone=ro(e.undone.slice(0),null,!0)},addLineClass:mi(function(e,t,i){return Cr(this,e,"gutter"==t?"gutter":"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"gutter"==t?"gutterClass":"wrapClass";if(e[r]){if(_o(i).test(e[r]))return!1;e[r]+=" "+i}else e[r]=i;return!0})}),removeLineClass:mi(function(e,t,i){return Cr(this,e,"gutter"==t?"gutter":"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"gutter"==t?"gutterClass":"wrapClass",n=e[r];if(!n)return!1;if(null==i)e[r]=null;else{var o=n.match(_o(i));if(!o)return!1;var s=o.index+o[0].length;e[r]=n.slice(0,o.index)+(o.index&&s!=n.length?" ":"")+n.slice(s)||null}return!0})}),markText:function(e,t,i){return _r(this,tt(this,e),tt(this,t),i,"range")},setBookmark:function(e,t){var i={replacedWith:t&&(null==t.nodeType?t.widget:t),insertLeft:t&&t.insertLeft,clearWhenEmpty:!1,shared:t&&t.shared};e=tt(this,e);return _r(this,e,e,i,"bookmark")},findMarksAt:function(e){e=tt(this,e);var t=[],i=Bn(this,e.line).markedSpans;if(i)for(var r=0;r<i.length;++r){var n=i[r];(null==n.from||n.from<=e.ch)&&(null==n.to||n.to>=e.ch)&&t.push(n.marker.parent||n.marker)}return t},findMarks:function(e,t,i){e=tt(this,e);t=tt(this,t);var r=[],n=e.line;this.iter(e.line,t.line+1,function(o){var s=o.markedSpans;if(s)for(var a=0;a<s.length;a++){var l=s[a];n==e.line&&e.ch>l.to||null==l.from&&n!=e.line||n==t.line&&l.from>t.ch||i&&!i(l.marker)||r.push(l.marker.parent||l.marker)}++n});return r},getAllMarks:function(){var e=[];this.iter(function(t){var i=t.markedSpans;if(i)for(var r=0;r<i.length;++r)null!=i[r].from&&e.push(i[r].marker)});return e},posFromIndex:function(e){var t,i=this.first;this.iter(function(r){var n=r.text.length+1;if(n>e){t=e;return!0}e-=n;++i});return tt(this,Is(i,t))},indexFromPos:function(e){e=tt(this,e);var t=e.ch;if(e.line<this.first||e.ch<0)return 0;this.iter(this.first,e.line,function(e){t+=e.text.length+1});return t},copy:function(e){var t=new ua(Vn(this,this.first,this.first+this.size),this.modeOption,this.first);t.scrollTop=this.scrollTop;t.scrollLeft=this.scrollLeft;t.sel=this.sel;t.extend=!1;if(e){t.history.undoDepth=this.history.undoDepth;t.setHistory(this.getHistory())}return t},linkedDoc:function(e){e||(e={});var t=this.first,i=this.first+this.size;null!=e.from&&e.from>t&&(t=e.from);null!=e.to&&e.to<i&&(i=e.to);var r=new ua(Vn(this,t,i),e.mode||this.modeOption,t);e.sharedHist&&(r.history=this.history);(this.linked||(this.linked=[])).push({doc:r,sharedHist:e.sharedHist});r.linked=[{doc:this,isParent:!0,sharedHist:e.sharedHist}];Gr(r,kr(this));return r},unlinkDoc:function(t){t instanceof e&&(t=t.doc);if(this.linked)for(var i=0;i<this.linked.length;++i){var r=this.linked[i];if(r.doc==t){this.linked.splice(i,1);t.unlinkDoc(this);Br(kr(this));break}}if(t.history==this.history){var n=[t.id];kn(t,function(e){n.push(e.id)},!0);t.history=new zn(null);t.history.done=ro(this.history.done,n);t.history.undone=ro(this.history.undone,n)}},iterLinkedDocs:function(e){kn(this,e)},getMode:function(){return this.mode},getEditor:function(){return this.cm}});ua.prototype.eachLine=ua.prototype.iter;var pa="iter insert remove copy getEditor".split(" ");for(var ca in ua.prototype)ua.prototype.hasOwnProperty(ca)&&To(pa,ca)<0&&(e.prototype[ca]=function(e){return function(){return e.apply(this.doc,arguments)}}(ua.prototype[ca]));mo(ua);var da=e.e_preventDefault=function(e){e.preventDefault?e.preventDefault():e.returnValue=!1},fa=e.e_stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},ha=e.e_stop=function(e){da(e);fa(e)},Ea=e.on=function(e,t,i){if(e.addEventListener)e.addEventListener(t,i,!1);else if(e.attachEvent)e.attachEvent("on"+t,i);else{var r=e._handlers||(e._handlers={}),n=r[t]||(r[t]=[]);n.push(i)}},ma=e.off=function(e,t,i){if(e.removeEventListener)e.removeEventListener(t,i,!1);else if(e.detachEvent)e.detachEvent("on"+t,i);else{var r=e._handlers&&e._handlers[t];if(!r)return;for(var n=0;n<r.length;++n)if(r[n]==i){r.splice(n,1);break}}},ga=e.signal=function(e,t){var i=e._handlers&&e._handlers[t];if(i)for(var r=Array.prototype.slice.call(arguments,2),n=0;n<i.length;++n)i[n].apply(null,r)},va=null,xa=30,Na=e.Pass={toString:function(){return"CodeMirror.Pass"}},Ta={scroll:!1},La={origin:"*mouse"},Ia={origin:"+move"};go.prototype.set=function(e,t){clearTimeout(this.id);this.id=setTimeout(t,e)};var ya=e.countColumn=function(e,t,i,r,n){if(null==t){t=e.search(/[^\s\u00a0]/);-1==t&&(t=e.length)}for(var o=r||0,s=n||0;;){var a=e.indexOf(" ",o);if(0>a||a>=t)return s+(t-o);s+=a-o;s+=i-s%i;o=a+1}},Aa=[""],Sa=function(e){e.select()};hs?Sa=function(e){e.selectionStart=0;e.selectionEnd=e.value.length}:ns&&(Sa=function(e){try{e.select()}catch(t){}});var Ca,Ra=/[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,ba=e.isWordChar=function(e){return/\w/.test(e)||e>"€"&&(e.toUpperCase()!=e.toLowerCase()||Ra.test(e))},Oa=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; Ca=document.createRange?function(e,t,i){var r=document.createRange();r.setEnd(e,i);r.setStart(e,t);return r}:function(e,t,i){var r=document.body.createTextRange();try{r.moveToElementText(e.parentNode)}catch(n){return r}r.collapse(!0);r.moveEnd("character",i);r.moveStart("character",t);return r};ns&&11>os&&(wo=function(){try{return document.activeElement}catch(e){return document.body}});var Pa,Da,wa=e.rmClass=function(e,t){var i=e.className,r=_o(t).exec(i);if(r){var n=i.slice(r.index+r[0].length);e.className=i.slice(0,r.index)+(n?r[1]+n:"")}},_a=e.addClass=function(e,t){var i=e.className;_o(t).test(i)||(e.className+=(i?" ":"")+t)},Ma=!1,ka=function(){if(ns&&9>os)return!1;var e=bo("div");return"draggable"in e||"dragDrop"in e}(),Ga=e.splitLines=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,i=[],r=e.length;r>=t;){var n=e.indexOf("\n",t);-1==n&&(n=e.length);var o=e.slice(t,"\r"==e.charAt(n-1)?n-1:n),s=o.indexOf("\r");if(-1!=s){i.push(o.slice(0,s));t+=s+1}else{i.push(o);t=n+1}}return i}:function(e){return e.split(/\r\n?|\n/)},Ba=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(t){return!1}}:function(e){try{var t=e.ownerDocument.selection.createRange()}catch(i){}return t&&t.parentElement()==e?0!=t.compareEndPoints("StartToEnd",t):!1},Ua=function(){var e=bo("div");if("oncopy"in e)return!0;e.setAttribute("oncopy","return;");return"function"==typeof e.oncopy}(),Va=null,Fa={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",107:"=",109:"-",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};e.keyNames=Fa;(function(){for(var e=0;10>e;e++)Fa[e+48]=Fa[e+96]=String(e);for(var e=65;90>=e;e++)Fa[e]=String.fromCharCode(e);for(var e=1;12>=e;e++)Fa[e+111]=Fa[e+63235]="F"+e})();var Ha,ja=function(){function e(e){return 247>=e?i.charAt(e):e>=1424&&1524>=e?"R":e>=1536&&1773>=e?r.charAt(e-1536):e>=1774&&2220>=e?"r":e>=8192&&8203>=e?"w":8204==e?"b":"L"}function t(e,t,i){this.level=e;this.from=t;this.to=i}var i="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",r="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",n=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,o=/[stwN]/,s=/[LRr]/,a=/[Lb1n]/,l=/[1n]/,u="L";return function(i){if(!n.test(i))return!1;for(var r,p=i.length,c=[],d=0;p>d;++d)c.push(r=e(i.charCodeAt(d)));for(var d=0,f=u;p>d;++d){var r=c[d];"m"==r?c[d]=f:f=r}for(var d=0,h=u;p>d;++d){var r=c[d];if("1"==r&&"r"==h)c[d]="n";else if(s.test(r)){h=r;"r"==r&&(c[d]="R")}}for(var d=1,f=c[0];p-1>d;++d){var r=c[d];"+"==r&&"1"==f&&"1"==c[d+1]?c[d]="1":","!=r||f!=c[d+1]||"1"!=f&&"n"!=f||(c[d]=f);f=r}for(var d=0;p>d;++d){var r=c[d];if(","==r)c[d]="N";else if("%"==r){for(var E=d+1;p>E&&"%"==c[E];++E);for(var m=d&&"!"==c[d-1]||p>E&&"1"==c[E]?"1":"N",g=d;E>g;++g)c[g]=m;d=E-1}}for(var d=0,h=u;p>d;++d){var r=c[d];"L"==h&&"1"==r?c[d]="L":s.test(r)&&(h=r)}for(var d=0;p>d;++d)if(o.test(c[d])){for(var E=d+1;p>E&&o.test(c[E]);++E);for(var v="L"==(d?c[d-1]:u),x="L"==(p>E?c[E]:u),m=v||x?"L":"R",g=d;E>g;++g)c[g]=m;d=E-1}for(var N,T=[],d=0;p>d;)if(a.test(c[d])){var L=d;for(++d;p>d&&a.test(c[d]);++d);T.push(new t(0,L,d))}else{var I=d,y=T.length;for(++d;p>d&&"L"!=c[d];++d);for(var g=I;d>g;)if(l.test(c[g])){g>I&&T.splice(y,0,new t(1,I,g));var A=g;for(++g;d>g&&l.test(c[g]);++g);T.splice(y,0,new t(2,A,g));I=g}else++g;d>I&&T.splice(y,0,new t(1,I,d))}if(1==T[0].level&&(N=i.match(/^\s+/))){T[0].from=N[0].length;T.unshift(new t(0,0,N[0].length))}if(1==No(T).level&&(N=i.match(/\s+$/))){No(T).to-=N[0].length;T.push(new t(0,p-N[0].length,p))}T[0].level!=No(T).level&&T.push(new t(T[0].level,p,p));return T}}();e.version="4.12.0";return e})},{}],15:[function(t,i){(function(e,t){"object"==typeof i&&"object"==typeof i.exports?i.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)})("undefined"!=typeof window?window:this,function(t,i){function r(e){var t=e.length,i=ot.type(e);return"function"===i||ot.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===i||0===t||"number"==typeof t&&t>0&&t-1 in e}function n(e,t,i){if(ot.isFunction(t))return ot.grep(e,function(e,r){return!!t.call(e,r,e)!==i});if(t.nodeType)return ot.grep(e,function(e){return e===t!==i});if("string"==typeof t){if(ft.test(t))return ot.filter(t,e,i);t=ot.filter(t,e)}return ot.grep(e,function(e){return ot.inArray(e,t)>=0!==i})}function o(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function s(e){var t=Tt[e]={};ot.each(e.match(Nt)||[],function(e,i){t[i]=!0});return t}function a(){if(Et.addEventListener){Et.removeEventListener("DOMContentLoaded",l,!1);t.removeEventListener("load",l,!1)}else{Et.detachEvent("onreadystatechange",l);t.detachEvent("onload",l)}}function l(){if(Et.addEventListener||"load"===event.type||"complete"===Et.readyState){a();ot.ready()}}function u(e,t,i){if(void 0===i&&1===e.nodeType){var r="data-"+t.replace(St,"-$1").toLowerCase();i=e.getAttribute(r);if("string"==typeof i){try{i="true"===i?!0:"false"===i?!1:"null"===i?null:+i+""===i?+i:At.test(i)?ot.parseJSON(i):i}catch(n){}ot.data(e,t,i)}else i=void 0}return i}function p(e){var t;for(t in e)if(("data"!==t||!ot.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function c(e,t,i,r){if(ot.acceptData(e)){var n,o,s=ot.expando,a=e.nodeType,l=a?ot.cache:e,u=a?e[s]:e[s]&&s;if(u&&l[u]&&(r||l[u].data)||void 0!==i||"string"!=typeof t){u||(u=a?e[s]=K.pop()||ot.guid++:s);l[u]||(l[u]=a?{}:{toJSON:ot.noop});("object"==typeof t||"function"==typeof t)&&(r?l[u]=ot.extend(l[u],t):l[u].data=ot.extend(l[u].data,t));o=l[u];if(!r){o.data||(o.data={});o=o.data}void 0!==i&&(o[ot.camelCase(t)]=i);if("string"==typeof t){n=o[t];null==n&&(n=o[ot.camelCase(t)])}else n=o;return n}}}function d(e,t,i){if(ot.acceptData(e)){var r,n,o=e.nodeType,s=o?ot.cache:e,a=o?e[ot.expando]:ot.expando;if(s[a]){if(t){r=i?s[a]:s[a].data;if(r){if(ot.isArray(t))t=t.concat(ot.map(t,ot.camelCase));else if(t in r)t=[t];else{t=ot.camelCase(t);t=t in r?[t]:t.split(" ")}n=t.length;for(;n--;)delete r[t[n]];if(i?!p(r):!ot.isEmptyObject(r))return}}if(!i){delete s[a].data;if(!p(s[a]))return}o?ot.cleanData([e],!0):rt.deleteExpando||s!=s.window?delete s[a]:s[a]=null}}}function f(){return!0}function h(){return!1}function E(){try{return Et.activeElement}catch(e){}}function m(e){var t=Gt.split("|"),i=e.createDocumentFragment();if(i.createElement)for(;t.length;)i.createElement(t.pop());return i}function g(e,t){var i,r,n=0,o=typeof e.getElementsByTagName!==yt?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==yt?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],i=e.childNodes||e;null!=(r=i[n]);n++)!t||ot.nodeName(r,t)?o.push(r):ot.merge(o,g(r,t));return void 0===t||t&&ot.nodeName(e,t)?ot.merge([e],o):o}function v(e){Pt.test(e.type)&&(e.defaultChecked=e.checked)}function x(e,t){return ot.nodeName(e,"table")&&ot.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function N(e){e.type=(null!==ot.find.attr(e,"type"))+"/"+e.type;return e}function T(e){var t=Yt.exec(e.type);t?e.type=t[1]:e.removeAttribute("type");return e}function L(e,t){for(var i,r=0;null!=(i=e[r]);r++)ot._data(i,"globalEval",!t||ot._data(t[r],"globalEval"))}function I(e,t){if(1===t.nodeType&&ot.hasData(e)){var i,r,n,o=ot._data(e),s=ot._data(t,o),a=o.events;if(a){delete s.handle;s.events={};for(i in a)for(r=0,n=a[i].length;n>r;r++)ot.event.add(t,i,a[i][r])}s.data&&(s.data=ot.extend({},s.data))}}function y(e,t){var i,r,n;if(1===t.nodeType){i=t.nodeName.toLowerCase();if(!rt.noCloneEvent&&t[ot.expando]){n=ot._data(t);for(r in n.events)ot.removeEvent(t,r,n.handle);t.removeAttribute(ot.expando)}if("script"===i&&t.text!==e.text){N(t).text=e.text;T(t)}else if("object"===i){t.parentNode&&(t.outerHTML=e.outerHTML);rt.html5Clone&&e.innerHTML&&!ot.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)}else if("input"===i&&Pt.test(e.type)){t.defaultChecked=t.checked=e.checked;t.value!==e.value&&(t.value=e.value)}else"option"===i?t.defaultSelected=t.selected=e.defaultSelected:("input"===i||"textarea"===i)&&(t.defaultValue=e.defaultValue)}}function A(e,i){var r,n=ot(i.createElement(e)).appendTo(i.body),o=t.getDefaultComputedStyle&&(r=t.getDefaultComputedStyle(n[0]))?r.display:ot.css(n[0],"display");n.detach();return o}function S(e){var t=Et,i=ei[e];if(!i){i=A(e,t);if("none"===i||!i){Jt=(Jt||ot("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement);t=(Jt[0].contentWindow||Jt[0].contentDocument).document;t.write();t.close();i=A(e,t);Jt.detach()}ei[e]=i}return i}function C(e,t){return{get:function(){var i=e();if(null!=i){if(!i)return(this.get=t).apply(this,arguments);delete this.get}}}}function R(e,t){if(t in e)return t;for(var i=t.charAt(0).toUpperCase()+t.slice(1),r=t,n=fi.length;n--;){t=fi[n]+i;if(t in e)return t}return r}function b(e,t){for(var i,r,n,o=[],s=0,a=e.length;a>s;s++){r=e[s];if(r.style){o[s]=ot._data(r,"olddisplay");i=r.style.display;if(t){o[s]||"none"!==i||(r.style.display="");""===r.style.display&&bt(r)&&(o[s]=ot._data(r,"olddisplay",S(r.nodeName)))}else{n=bt(r);(i&&"none"!==i||!n)&&ot._data(r,"olddisplay",n?i:ot.css(r,"display"))}}}for(s=0;a>s;s++){r=e[s];r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[s]||"":"none"))}return e}function O(e,t,i){var r=ui.exec(t);return r?Math.max(0,r[1]-(i||0))+(r[2]||"px"):t}function P(e,t,i,r,n){for(var o=i===(r?"border":"content")?4:"width"===t?1:0,s=0;4>o;o+=2){"margin"===i&&(s+=ot.css(e,i+Rt[o],!0,n));if(r){"content"===i&&(s-=ot.css(e,"padding"+Rt[o],!0,n));"margin"!==i&&(s-=ot.css(e,"border"+Rt[o]+"Width",!0,n))}else{s+=ot.css(e,"padding"+Rt[o],!0,n);"padding"!==i&&(s+=ot.css(e,"border"+Rt[o]+"Width",!0,n))}}return s}function D(e,t,i){var r=!0,n="width"===t?e.offsetWidth:e.offsetHeight,o=ti(e),s=rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,o);if(0>=n||null==n){n=ii(e,t,o);(0>n||null==n)&&(n=e.style[t]);if(ni.test(n))return n;r=s&&(rt.boxSizingReliable()||n===e.style[t]);n=parseFloat(n)||0}return n+P(e,t,i||(s?"border":"content"),r,o)+"px"}function w(e,t,i,r,n){return new w.prototype.init(e,t,i,r,n)}function _(){setTimeout(function(){hi=void 0});return hi=ot.now()}function M(e,t){var i,r={height:e},n=0;t=t?1:0;for(;4>n;n+=2-t){i=Rt[n];r["margin"+i]=r["padding"+i]=e}t&&(r.opacity=r.width=e);return r}function k(e,t,i){for(var r,n=(Ni[t]||[]).concat(Ni["*"]),o=0,s=n.length;s>o;o++)if(r=n[o].call(i,t,e))return r}function G(e,t,i){var r,n,o,s,a,l,u,p,c=this,d={},f=e.style,h=e.nodeType&&bt(e),E=ot._data(e,"fxshow");if(!i.queue){a=ot._queueHooks(e,"fx");if(null==a.unqueued){a.unqueued=0;l=a.empty.fire;a.empty.fire=function(){a.unqueued||l()}}a.unqueued++;c.always(function(){c.always(function(){a.unqueued--;ot.queue(e,"fx").length||a.empty.fire()})})}if(1===e.nodeType&&("height"in t||"width"in t)){i.overflow=[f.overflow,f.overflowX,f.overflowY];u=ot.css(e,"display");p="none"===u?ot._data(e,"olddisplay")||S(e.nodeName):u;"inline"===p&&"none"===ot.css(e,"float")&&(rt.inlineBlockNeedsLayout&&"inline"!==S(e.nodeName)?f.zoom=1:f.display="inline-block")}if(i.overflow){f.overflow="hidden";rt.shrinkWrapBlocks()||c.always(function(){f.overflow=i.overflow[0];f.overflowX=i.overflow[1];f.overflowY=i.overflow[2]})}for(r in t){n=t[r];if(mi.exec(n)){delete t[r];o=o||"toggle"===n;if(n===(h?"hide":"show")){if("show"!==n||!E||void 0===E[r])continue;h=!0}d[r]=E&&E[r]||ot.style(e,r)}else u=void 0}if(ot.isEmptyObject(d))"inline"===("none"===u?S(e.nodeName):u)&&(f.display=u);else{E?"hidden"in E&&(h=E.hidden):E=ot._data(e,"fxshow",{});o&&(E.hidden=!h);h?ot(e).show():c.done(function(){ot(e).hide()});c.done(function(){var t;ot._removeData(e,"fxshow");for(t in d)ot.style(e,t,d[t])});for(r in d){s=k(h?E[r]:0,r,c);if(!(r in E)){E[r]=s.start;if(h){s.end=s.start;s.start="width"===r||"height"===r?1:0}}}}}function B(e,t){var i,r,n,o,s;for(i in e){r=ot.camelCase(i);n=t[r];o=e[i];if(ot.isArray(o)){n=o[1];o=e[i]=o[0]}if(i!==r){e[r]=o;delete e[i]}s=ot.cssHooks[r];if(s&&"expand"in s){o=s.expand(o);delete e[r];for(i in o)if(!(i in e)){e[i]=o[i];t[i]=n}}else t[r]=n}}function U(e,t,i){var r,n,o=0,s=xi.length,a=ot.Deferred().always(function(){delete l.elem}),l=function(){if(n)return!1;for(var t=hi||_(),i=Math.max(0,u.startTime+u.duration-t),r=i/u.duration||0,o=1-r,s=0,l=u.tweens.length;l>s;s++)u.tweens[s].run(o);a.notifyWith(e,[u,o,i]);if(1>o&&l)return i;a.resolveWith(e,[u]);return!1},u=a.promise({elem:e,props:ot.extend({},t),opts:ot.extend(!0,{specialEasing:{}},i),originalProperties:t,originalOptions:i,startTime:hi||_(),duration:i.duration,tweens:[],createTween:function(t,i){var r=ot.Tween(e,u.opts,t,i,u.opts.specialEasing[t]||u.opts.easing);u.tweens.push(r);return r},stop:function(t){var i=0,r=t?u.tweens.length:0;if(n)return this;n=!0;for(;r>i;i++)u.tweens[i].run(1);t?a.resolveWith(e,[u,t]):a.rejectWith(e,[u,t]);return this}}),p=u.props;B(p,u.opts.specialEasing);for(;s>o;o++){r=xi[o].call(u,e,p,u.opts);if(r)return r}ot.map(p,k,u);ot.isFunction(u.opts.start)&&u.opts.start.call(e,u);ot.fx.timer(ot.extend(l,{elem:e,anim:u,queue:u.opts.queue}));return u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function V(e){return function(t,i){if("string"!=typeof t){i=t;t="*"}var r,n=0,o=t.toLowerCase().match(Nt)||[];if(ot.isFunction(i))for(;r=o[n++];)if("+"===r.charAt(0)){r=r.slice(1)||"*";(e[r]=e[r]||[]).unshift(i)}else(e[r]=e[r]||[]).push(i)}}function F(e,t,i,r){function n(a){var l;o[a]=!0;ot.each(e[a]||[],function(e,a){var u=a(t,i,r);if("string"==typeof u&&!s&&!o[u]){t.dataTypes.unshift(u);n(u);return!1}return s?!(l=u):void 0});return l}var o={},s=e===Wi;return n(t.dataTypes[0])||!o["*"]&&n("*")}function H(e,t){var i,r,n=ot.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((n[r]?e:i||(i={}))[r]=t[r]);i&&ot.extend(!0,e,i);return e}function j(e,t,i){for(var r,n,o,s,a=e.contents,l=e.dataTypes;"*"===l[0];){l.shift();void 0===n&&(n=e.mimeType||t.getResponseHeader("Content-Type"))}if(n)for(s in a)if(a[s]&&a[s].test(n)){l.unshift(s);break}if(l[0]in i)o=l[0];else{for(s in i){if(!l[0]||e.converters[s+" "+l[0]]){o=s;break}r||(r=s)}o=o||r}if(o){o!==l[0]&&l.unshift(o);return i[o]}}function W(e,t,i,r){var n,o,s,a,l,u={},p=e.dataTypes.slice();if(p[1])for(s in e.converters)u[s.toLowerCase()]=e.converters[s];o=p.shift();for(;o;){e.responseFields[o]&&(i[e.responseFields[o]]=t);!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType));l=o;o=p.shift();if(o)if("*"===o)o=l;else if("*"!==l&&l!==o){s=u[l+" "+o]||u["* "+o];if(!s)for(n in u){a=n.split(" ");if(a[1]===o){s=u[l+" "+a[0]]||u["* "+a[0]];if(s){if(s===!0)s=u[n];else if(u[n]!==!0){o=a[0];p.unshift(a[1])}break}}}if(s!==!0)if(s&&e["throws"])t=s(t);else try{t=s(t)}catch(c){return{state:"parsererror",error:s?c:"No conversion from "+l+" to "+o}}}}return{state:"success",data:t}}function q(e,t,i,r){var n;if(ot.isArray(t))ot.each(t,function(t,n){i||Yi.test(e)?r(e,n):q(e+"["+("object"==typeof n?t:"")+"]",n,i,r)});else if(i||"object"!==ot.type(t))r(e,t);else for(n in t)q(e+"["+n+"]",t[n],i,r)}function z(){try{return new t.XMLHttpRequest}catch(e){}}function X(){try{return new t.ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}function Y(e){return ot.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var K=[],$=K.slice,Q=K.concat,Z=K.push,J=K.indexOf,et={},tt=et.toString,it=et.hasOwnProperty,rt={},nt="1.11.2",ot=function(e,t){return new ot.fn.init(e,t)},st=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,at=/^-ms-/,lt=/-([\da-z])/gi,ut=function(e,t){return t.toUpperCase()};ot.fn=ot.prototype={jquery:nt,constructor:ot,selector:"",length:0,toArray:function(){return $.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:$.call(this)},pushStack:function(e){var t=ot.merge(this.constructor(),e);t.prevObject=this;t.context=this.context;return t},each:function(e,t){return ot.each(this,e,t)},map:function(e){return this.pushStack(ot.map(this,function(t,i){return e.call(t,i,t)}))},slice:function(){return this.pushStack($.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,i=+e+(0>e?t:0);return this.pushStack(i>=0&&t>i?[this[i]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Z,sort:K.sort,splice:K.splice};ot.extend=ot.fn.extend=function(){var e,t,i,r,n,o,s=arguments[0]||{},a=1,l=arguments.length,u=!1;if("boolean"==typeof s){u=s;s=arguments[a]||{};a++}"object"==typeof s||ot.isFunction(s)||(s={});if(a===l){s=this;a--}for(;l>a;a++)if(null!=(n=arguments[a]))for(r in n){e=s[r];i=n[r];if(s!==i)if(u&&i&&(ot.isPlainObject(i)||(t=ot.isArray(i)))){if(t){t=!1;o=e&&ot.isArray(e)?e:[]}else o=e&&ot.isPlainObject(e)?e:{};s[r]=ot.extend(u,o,i)}else void 0!==i&&(s[r]=i)}return s};ot.extend({expando:"jQuery"+(nt+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===ot.type(e)},isArray:Array.isArray||function(e){return"array"===ot.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!ot.isArray(e)&&e-parseFloat(e)+1>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==ot.type(e)||e.nodeType||ot.isWindow(e))return!1;try{if(e.constructor&&!it.call(e,"constructor")&&!it.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(i){return!1}if(rt.ownLast)for(t in e)return it.call(e,t);for(t in e);return void 0===t||it.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?et[tt.call(e)]||"object":typeof e},globalEval:function(e){e&&ot.trim(e)&&(t.execScript||function(e){t.eval.call(t,e)})(e)},camelCase:function(e){return e.replace(at,"ms-").replace(lt,ut)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,i){var n,o=0,s=e.length,a=r(e);if(i)if(a)for(;s>o;o++){n=t.apply(e[o],i);if(n===!1)break}else for(o in e){n=t.apply(e[o],i);if(n===!1)break}else if(a)for(;s>o;o++){n=t.call(e[o],o,e[o]);if(n===!1)break}else for(o in e){n=t.call(e[o],o,e[o]);if(n===!1)break}return e},trim:function(e){return null==e?"":(e+"").replace(st,"")},makeArray:function(e,t){var i=t||[];null!=e&&(r(Object(e))?ot.merge(i,"string"==typeof e?[e]:e):Z.call(i,e));return i},inArray:function(e,t,i){var r;if(t){if(J)return J.call(t,e,i);r=t.length;i=i?0>i?Math.max(0,r+i):i:0;for(;r>i;i++)if(i in t&&t[i]===e)return i}return-1},merge:function(e,t){for(var i=+t.length,r=0,n=e.length;i>r;)e[n++]=t[r++];if(i!==i)for(;void 0!==t[r];)e[n++]=t[r++];e.length=n;return e},grep:function(e,t,i){for(var r,n=[],o=0,s=e.length,a=!i;s>o;o++){r=!t(e[o],o);r!==a&&n.push(e[o])}return n},map:function(e,t,i){var n,o=0,s=e.length,a=r(e),l=[];if(a)for(;s>o;o++){n=t(e[o],o,i);null!=n&&l.push(n)}else for(o in e){n=t(e[o],o,i);null!=n&&l.push(n)}return Q.apply([],l)},guid:1,proxy:function(e,t){var i,r,n;if("string"==typeof t){n=e[t];t=e;e=n}if(!ot.isFunction(e))return void 0;i=$.call(arguments,2);r=function(){return e.apply(t||this,i.concat($.call(arguments)))};r.guid=e.guid=e.guid||ot.guid++;return r},now:function(){return+new Date},support:rt});ot.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){et["[object "+t+"]"]=t.toLowerCase()});var pt=function(e){function t(e,t,i,r){var n,o,s,a,l,u,c,f,h,E;(t?t.ownerDocument||t:V)!==D&&P(t);t=t||D;i=i||[];a=t.nodeType;if("string"!=typeof e||!e||1!==a&&9!==a&&11!==a)return i;if(!r&&_){if(11!==a&&(n=vt.exec(e)))if(s=n[1]){if(9===a){o=t.getElementById(s);if(!o||!o.parentNode)return i;if(o.id===s){i.push(o);return i}}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(s))&&B(t,o)&&o.id===s){i.push(o);return i}}else{if(n[2]){Z.apply(i,t.getElementsByTagName(e));return i}if((s=n[3])&&T.getElementsByClassName){Z.apply(i,t.getElementsByClassName(s));return i}}if(T.qsa&&(!M||!M.test(e))){f=c=U;h=t;E=1!==a&&e;if(1===a&&"object"!==t.nodeName.toLowerCase()){u=A(e);(c=t.getAttribute("id"))?f=c.replace(Nt,"\\$&"):t.setAttribute("id",f);f="[id='"+f+"'] ";l=u.length;for(;l--;)u[l]=f+d(u[l]);h=xt.test(e)&&p(t.parentNode)||t;E=u.join(",")}if(E)try{Z.apply(i,h.querySelectorAll(E));return i}catch(m){}finally{c||t.removeAttribute("id")}}}return C(e.replace(lt,"$1"),t,i,r)}function i(){function e(i,r){t.push(i+" ")>L.cacheLength&&delete e[t.shift()];return e[i+" "]=r}var t=[];return e}function r(e){e[U]=!0;return e}function n(e){var t=D.createElement("div");try{return!!e(t)}catch(i){return!1}finally{t.parentNode&&t.parentNode.removeChild(t);t=null}}function o(e,t){for(var i=e.split("|"),r=e.length;r--;)L.attrHandle[i[r]]=t}function s(e,t){var i=t&&e,r=i&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||X)-(~e.sourceIndex||X);if(r)return r;if(i)for(;i=i.nextSibling;)if(i===t)return-1;return e?1:-1}function a(e){return function(t){var i=t.nodeName.toLowerCase();return"input"===i&&t.type===e}}function l(e){return function(t){var i=t.nodeName.toLowerCase();return("input"===i||"button"===i)&&t.type===e}}function u(e){return r(function(t){t=+t;return r(function(i,r){for(var n,o=e([],i.length,t),s=o.length;s--;)i[n=o[s]]&&(i[n]=!(r[n]=i[n]))})})}function p(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function c(){}function d(e){for(var t=0,i=e.length,r="";i>t;t++)r+=e[t].value;return r}function f(e,t,i){var r=t.dir,n=i&&"parentNode"===r,o=H++;return t.first?function(t,i,o){for(;t=t[r];)if(1===t.nodeType||n)return e(t,i,o)}:function(t,i,s){var a,l,u=[F,o];if(s){for(;t=t[r];)if((1===t.nodeType||n)&&e(t,i,s))return!0}else for(;t=t[r];)if(1===t.nodeType||n){l=t[U]||(t[U]={});if((a=l[r])&&a[0]===F&&a[1]===o)return u[2]=a[2];l[r]=u;if(u[2]=e(t,i,s))return!0}}}function h(e){return e.length>1?function(t,i,r){for(var n=e.length;n--;)if(!e[n](t,i,r))return!1;return!0}:e[0]}function E(e,i,r){for(var n=0,o=i.length;o>n;n++)t(e,i[n],r);return r}function m(e,t,i,r,n){for(var o,s=[],a=0,l=e.length,u=null!=t;l>a;a++)if((o=e[a])&&(!i||i(o,r,n))){s.push(o);u&&t.push(a)}return s}function g(e,t,i,n,o,s){n&&!n[U]&&(n=g(n));o&&!o[U]&&(o=g(o,s));return r(function(r,s,a,l){var u,p,c,d=[],f=[],h=s.length,g=r||E(t||"*",a.nodeType?[a]:a,[]),v=!e||!r&&t?g:m(g,d,e,a,l),x=i?o||(r?e:h||n)?[]:s:v;i&&i(v,x,a,l);if(n){u=m(x,f);n(u,[],a,l);p=u.length;for(;p--;)(c=u[p])&&(x[f[p]]=!(v[f[p]]=c))}if(r){if(o||e){if(o){u=[];p=x.length;for(;p--;)(c=x[p])&&u.push(v[p]=c);o(null,x=[],u,l)}p=x.length;for(;p--;)(c=x[p])&&(u=o?et(r,c):d[p])>-1&&(r[u]=!(s[u]=c))}}else{x=m(x===s?x.splice(h,x.length):x);o?o(null,s,x,l):Z.apply(s,x)}})}function v(e){for(var t,i,r,n=e.length,o=L.relative[e[0].type],s=o||L.relative[" "],a=o?1:0,l=f(function(e){return e===t},s,!0),u=f(function(e){return et(t,e)>-1},s,!0),p=[function(e,i,r){var n=!o&&(r||i!==R)||((t=i).nodeType?l(e,i,r):u(e,i,r));t=null;return n}];n>a;a++)if(i=L.relative[e[a].type])p=[f(h(p),i)];else{i=L.filter[e[a].type].apply(null,e[a].matches);if(i[U]){r=++a;for(;n>r&&!L.relative[e[r].type];r++);return g(a>1&&h(p),a>1&&d(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(lt,"$1"),i,r>a&&v(e.slice(a,r)),n>r&&v(e=e.slice(r)),n>r&&d(e))}p.push(i)}return h(p)}function x(e,i){var n=i.length>0,o=e.length>0,s=function(r,s,a,l,u){var p,c,d,f=0,h="0",E=r&&[],g=[],v=R,x=r||o&&L.find.TAG("*",u),N=F+=null==v?1:Math.random()||.1,T=x.length;u&&(R=s!==D&&s);for(;h!==T&&null!=(p=x[h]);h++){if(o&&p){c=0;for(;d=e[c++];)if(d(p,s,a)){l.push(p);break}u&&(F=N)}if(n){(p=!d&&p)&&f--;r&&E.push(p)}}f+=h;if(n&&h!==f){c=0;for(;d=i[c++];)d(E,g,s,a);if(r){if(f>0)for(;h--;)E[h]||g[h]||(g[h]=$.call(l));g=m(g)}Z.apply(l,g);u&&!r&&g.length>0&&f+i.length>1&&t.uniqueSort(l)}if(u){F=N;R=v}return E};return n?r(s):s}var N,T,L,I,y,A,S,C,R,b,O,P,D,w,_,M,k,G,B,U="sizzle"+1*new Date,V=e.document,F=0,H=0,j=i(),W=i(),q=i(),z=function(e,t){e===t&&(O=!0);return 0},X=1<<31,Y={}.hasOwnProperty,K=[],$=K.pop,Q=K.push,Z=K.push,J=K.slice,et=function(e,t){for(var i=0,r=e.length;r>i;i++)if(e[i]===t)return i;return-1},tt="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",it="[\\x20\\t\\r\\n\\f]",rt="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",nt=rt.replace("w","w#"),ot="\\["+it+"*("+rt+")(?:"+it+"*([*^$|!~]?=)"+it+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+nt+"))|)"+it+"*\\]",st=":("+rt+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+ot+")*)|.*)\\)|)",at=new RegExp(it+"+","g"),lt=new RegExp("^"+it+"+|((?:^|[^\\\\])(?:\\\\.)*)"+it+"+$","g"),ut=new RegExp("^"+it+"*,"+it+"*"),pt=new RegExp("^"+it+"*([>+~]|"+it+")"+it+"*"),ct=new RegExp("="+it+"*([^\\]'\"]*?)"+it+"*\\]","g"),dt=new RegExp(st),ft=new RegExp("^"+nt+"$"),ht={ID:new RegExp("^#("+rt+")"),CLASS:new RegExp("^\\.("+rt+")"),TAG:new RegExp("^("+rt.replace("w","w*")+")"),ATTR:new RegExp("^"+ot),PSEUDO:new RegExp("^"+st),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+it+"*(even|odd|(([+-]|)(\\d*)n|)"+it+"*(?:([+-]|)"+it+"*(\\d+)|))"+it+"*\\)|)","i"),bool:new RegExp("^(?:"+tt+")$","i"),needsContext:new RegExp("^"+it+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+it+"*((?:-\\d)?\\d*)"+it+"*\\)|)(?=[^-]|$)","i")},Et=/^(?:input|select|textarea|button)$/i,mt=/^h\d$/i,gt=/^[^{]+\{\s*\[native \w/,vt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,xt=/[+~]/,Nt=/'|\\/g,Tt=new RegExp("\\\\([\\da-f]{1,6}"+it+"?|("+it+")|.)","ig"),Lt=function(e,t,i){var r="0x"+t-65536;return r!==r||i?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},It=function(){P()};try{Z.apply(K=J.call(V.childNodes),V.childNodes);K[V.childNodes.length].nodeType}catch(yt){Z={apply:K.length?function(e,t){Q.apply(e,J.call(t))}:function(e,t){for(var i=e.length,r=0;e[i++]=t[r++];);e.length=i-1}}}T=t.support={};y=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1};P=t.setDocument=function(e){var t,i,r=e?e.ownerDocument||e:V;if(r===D||9!==r.nodeType||!r.documentElement)return D;D=r;w=r.documentElement;i=r.defaultView;i&&i!==i.top&&(i.addEventListener?i.addEventListener("unload",It,!1):i.attachEvent&&i.attachEvent("onunload",It));_=!y(r);T.attributes=n(function(e){e.className="i";return!e.getAttribute("className")});T.getElementsByTagName=n(function(e){e.appendChild(r.createComment(""));return!e.getElementsByTagName("*").length});T.getElementsByClassName=gt.test(r.getElementsByClassName);T.getById=n(function(e){w.appendChild(e).id=U;return!r.getElementsByName||!r.getElementsByName(U).length});if(T.getById){L.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&_){var i=t.getElementById(e);return i&&i.parentNode?[i]:[]}};L.filter.ID=function(e){var t=e.replace(Tt,Lt);return function(e){return e.getAttribute("id")===t}}}else{delete L.find.ID;L.filter.ID=function(e){var t=e.replace(Tt,Lt);return function(e){var i="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return i&&i.value===t}}}L.find.TAG=T.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):T.qsa?t.querySelectorAll(e):void 0}:function(e,t){var i,r=[],n=0,o=t.getElementsByTagName(e);if("*"===e){for(;i=o[n++];)1===i.nodeType&&r.push(i);return r}return o};L.find.CLASS=T.getElementsByClassName&&function(e,t){return _?t.getElementsByClassName(e):void 0};k=[];M=[];if(T.qsa=gt.test(r.querySelectorAll)){n(function(e){w.appendChild(e).innerHTML="<a id='"+U+"'></a><select id='"+U+"-\f]' msallowcapture=''><option selected=''></option></select>";e.querySelectorAll("[msallowcapture^='']").length&&M.push("[*^$]="+it+"*(?:''|\"\")");e.querySelectorAll("[selected]").length||M.push("\\["+it+"*(?:value|"+tt+")");e.querySelectorAll("[id~="+U+"-]").length||M.push("~=");e.querySelectorAll(":checked").length||M.push(":checked");e.querySelectorAll("a#"+U+"+*").length||M.push(".#.+[+~]")});n(function(e){var t=r.createElement("input");t.setAttribute("type","hidden");e.appendChild(t).setAttribute("name","D");e.querySelectorAll("[name=d]").length&&M.push("name"+it+"*[*^$|!~]?=");e.querySelectorAll(":enabled").length||M.push(":enabled",":disabled");e.querySelectorAll("*,:x");M.push(",.*:")})}(T.matchesSelector=gt.test(G=w.matches||w.webkitMatchesSelector||w.mozMatchesSelector||w.oMatchesSelector||w.msMatchesSelector))&&n(function(e){T.disconnectedMatch=G.call(e,"div");G.call(e,"[s!='']:x");k.push("!=",st)});M=M.length&&new RegExp(M.join("|"));k=k.length&&new RegExp(k.join("|"));t=gt.test(w.compareDocumentPosition);B=t||gt.test(w.contains)?function(e,t){var i=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(i.contains?i.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1};z=t?function(e,t){if(e===t){O=!0;return 0}var i=!e.compareDocumentPosition-!t.compareDocumentPosition;if(i)return i;i=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1;return 1&i||!T.sortDetached&&t.compareDocumentPosition(e)===i?e===r||e.ownerDocument===V&&B(V,e)?-1:t===r||t.ownerDocument===V&&B(V,t)?1:b?et(b,e)-et(b,t):0:4&i?-1:1}:function(e,t){if(e===t){O=!0;return 0}var i,n=0,o=e.parentNode,a=t.parentNode,l=[e],u=[t];if(!o||!a)return e===r?-1:t===r?1:o?-1:a?1:b?et(b,e)-et(b,t):0;if(o===a)return s(e,t);i=e;for(;i=i.parentNode;)l.unshift(i);i=t;for(;i=i.parentNode;)u.unshift(i);for(;l[n]===u[n];)n++;return n?s(l[n],u[n]):l[n]===V?-1:u[n]===V?1:0};return r};t.matches=function(e,i){return t(e,null,null,i)};t.matchesSelector=function(e,i){(e.ownerDocument||e)!==D&&P(e);i=i.replace(ct,"='$1']");if(!(!T.matchesSelector||!_||k&&k.test(i)||M&&M.test(i)))try{var r=G.call(e,i);if(r||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(n){}return t(i,D,null,[e]).length>0};t.contains=function(e,t){(e.ownerDocument||e)!==D&&P(e);return B(e,t)};t.attr=function(e,t){(e.ownerDocument||e)!==D&&P(e);var i=L.attrHandle[t.toLowerCase()],r=i&&Y.call(L.attrHandle,t.toLowerCase())?i(e,t,!_):void 0;return void 0!==r?r:T.attributes||!_?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null};t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)};t.uniqueSort=function(e){var t,i=[],r=0,n=0;O=!T.detectDuplicates;b=!T.sortStable&&e.slice(0);e.sort(z);if(O){for(;t=e[n++];)t===e[n]&&(r=i.push(n));for(;r--;)e.splice(i[r],1)}b=null;return e};I=t.getText=function(e){var t,i="",r=0,n=e.nodeType;if(n){if(1===n||9===n||11===n){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)i+=I(e)}else if(3===n||4===n)return e.nodeValue}else for(;t=e[r++];)i+=I(t);return i};L=t.selectors={cacheLength:50,createPseudo:r,match:ht,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){e[1]=e[1].replace(Tt,Lt);e[3]=(e[3]||e[4]||e[5]||"").replace(Tt,Lt);"~="===e[2]&&(e[3]=" "+e[3]+" ");return e.slice(0,4)},CHILD:function(e){e[1]=e[1].toLowerCase();if("nth"===e[1].slice(0,3)){e[3]||t.error(e[0]);e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3]));e[5]=+(e[7]+e[8]||"odd"===e[3])}else e[3]&&t.error(e[0]);return e},PSEUDO:function(e){var t,i=!e[6]&&e[2]; if(ht.CHILD.test(e[0]))return null;if(e[3])e[2]=e[4]||e[5]||"";else if(i&&dt.test(i)&&(t=A(i,!0))&&(t=i.indexOf(")",i.length-t)-i.length)){e[0]=e[0].slice(0,t);e[2]=i.slice(0,t)}return e.slice(0,3)}},filter:{TAG:function(e){var t=e.replace(Tt,Lt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=j[e+" "];return t||(t=new RegExp("(^|"+it+")"+e+"("+it+"|$)"))&&j(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,i,r){return function(n){var o=t.attr(n,e);if(null==o)return"!="===i;if(!i)return!0;o+="";return"="===i?o===r:"!="===i?o!==r:"^="===i?r&&0===o.indexOf(r):"*="===i?r&&o.indexOf(r)>-1:"$="===i?r&&o.slice(-r.length)===r:"~="===i?(" "+o.replace(at," ")+" ").indexOf(r)>-1:"|="===i?o===r||o.slice(0,r.length+1)===r+"-":!1}},CHILD:function(e,t,i,r,n){var o="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===r&&0===n?function(e){return!!e.parentNode}:function(t,i,l){var u,p,c,d,f,h,E=o!==s?"nextSibling":"previousSibling",m=t.parentNode,g=a&&t.nodeName.toLowerCase(),v=!l&&!a;if(m){if(o){for(;E;){c=t;for(;c=c[E];)if(a?c.nodeName.toLowerCase()===g:1===c.nodeType)return!1;h=E="only"===e&&!h&&"nextSibling"}return!0}h=[s?m.firstChild:m.lastChild];if(s&&v){p=m[U]||(m[U]={});u=p[e]||[];f=u[0]===F&&u[1];d=u[0]===F&&u[2];c=f&&m.childNodes[f];for(;c=++f&&c&&c[E]||(d=f=0)||h.pop();)if(1===c.nodeType&&++d&&c===t){p[e]=[F,f,d];break}}else if(v&&(u=(t[U]||(t[U]={}))[e])&&u[0]===F)d=u[1];else for(;c=++f&&c&&c[E]||(d=f=0)||h.pop();)if((a?c.nodeName.toLowerCase()===g:1===c.nodeType)&&++d){v&&((c[U]||(c[U]={}))[e]=[F,d]);if(c===t)break}d-=n;return d===r||d%r===0&&d/r>=0}}},PSEUDO:function(e,i){var n,o=L.pseudos[e]||L.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);if(o[U])return o(i);if(o.length>1){n=[e,e,"",i];return L.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,n=o(e,i),s=n.length;s--;){r=et(e,n[s]);e[r]=!(t[r]=n[s])}}):function(e){return o(e,0,n)}}return o}},pseudos:{not:r(function(e){var t=[],i=[],n=S(e.replace(lt,"$1"));return n[U]?r(function(e,t,i,r){for(var o,s=n(e,null,r,[]),a=e.length;a--;)(o=s[a])&&(e[a]=!(t[a]=o))}):function(e,r,o){t[0]=e;n(t,null,o,i);t[0]=null;return!i.pop()}}),has:r(function(e){return function(i){return t(e,i).length>0}}),contains:r(function(e){e=e.replace(Tt,Lt);return function(t){return(t.textContent||t.innerText||I(t)).indexOf(e)>-1}}),lang:r(function(e){ft.test(e||"")||t.error("unsupported lang: "+e);e=e.replace(Tt,Lt).toLowerCase();return function(t){var i;do if(i=_?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang")){i=i.toLowerCase();return i===e||0===i.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var i=e.location&&e.location.hash;return i&&i.slice(1)===t.id},root:function(e){return e===w},focus:function(e){return e===D.activeElement&&(!D.hasFocus||D.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){e.parentNode&&e.parentNode.selectedIndex;return e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!L.pseudos.empty(e)},header:function(e){return mt.test(e.nodeName)},input:function(e){return Et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,i){return[0>i?i+t:i]}),even:u(function(e,t){for(var i=0;t>i;i+=2)e.push(i);return e}),odd:u(function(e,t){for(var i=1;t>i;i+=2)e.push(i);return e}),lt:u(function(e,t,i){for(var r=0>i?i+t:i;--r>=0;)e.push(r);return e}),gt:u(function(e,t,i){for(var r=0>i?i+t:i;++r<t;)e.push(r);return e})}};L.pseudos.nth=L.pseudos.eq;for(N in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})L.pseudos[N]=a(N);for(N in{submit:!0,reset:!0})L.pseudos[N]=l(N);c.prototype=L.filters=L.pseudos;L.setFilters=new c;A=t.tokenize=function(e,i){var r,n,o,s,a,l,u,p=W[e+" "];if(p)return i?0:p.slice(0);a=e;l=[];u=L.preFilter;for(;a;){if(!r||(n=ut.exec(a))){n&&(a=a.slice(n[0].length)||a);l.push(o=[])}r=!1;if(n=pt.exec(a)){r=n.shift();o.push({value:r,type:n[0].replace(lt," ")});a=a.slice(r.length)}for(s in L.filter)if((n=ht[s].exec(a))&&(!u[s]||(n=u[s](n)))){r=n.shift();o.push({value:r,type:s,matches:n});a=a.slice(r.length)}if(!r)break}return i?a.length:a?t.error(e):W(e,l).slice(0)};S=t.compile=function(e,t){var i,r=[],n=[],o=q[e+" "];if(!o){t||(t=A(e));i=t.length;for(;i--;){o=v(t[i]);o[U]?r.push(o):n.push(o)}o=q(e,x(n,r));o.selector=e}return o};C=t.select=function(e,t,i,r){var n,o,s,a,l,u="function"==typeof e&&e,c=!r&&A(e=u.selector||e);i=i||[];if(1===c.length){o=c[0]=c[0].slice(0);if(o.length>2&&"ID"===(s=o[0]).type&&T.getById&&9===t.nodeType&&_&&L.relative[o[1].type]){t=(L.find.ID(s.matches[0].replace(Tt,Lt),t)||[])[0];if(!t)return i;u&&(t=t.parentNode);e=e.slice(o.shift().value.length)}n=ht.needsContext.test(e)?0:o.length;for(;n--;){s=o[n];if(L.relative[a=s.type])break;if((l=L.find[a])&&(r=l(s.matches[0].replace(Tt,Lt),xt.test(o[0].type)&&p(t.parentNode)||t))){o.splice(n,1);e=r.length&&d(o);if(!e){Z.apply(i,r);return i}break}}}(u||S(e,c))(r,t,!_,i,xt.test(e)&&p(t.parentNode)||t);return i};T.sortStable=U.split("").sort(z).join("")===U;T.detectDuplicates=!!O;P();T.sortDetached=n(function(e){return 1&e.compareDocumentPosition(D.createElement("div"))});n(function(e){e.innerHTML="<a href='#'></a>";return"#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,i){return i?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)});T.attributes&&n(function(e){e.innerHTML="<input/>";e.firstChild.setAttribute("value","");return""===e.firstChild.getAttribute("value")})||o("value",function(e,t,i){return i||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue});n(function(e){return null==e.getAttribute("disabled")})||o(tt,function(e,t,i){var r;return i?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null});return t}(t);ot.find=pt;ot.expr=pt.selectors;ot.expr[":"]=ot.expr.pseudos;ot.unique=pt.uniqueSort;ot.text=pt.getText;ot.isXMLDoc=pt.isXML;ot.contains=pt.contains;var ct=ot.expr.match.needsContext,dt=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,ft=/^.[^:#\[\.,]*$/;ot.filter=function(e,t,i){var r=t[0];i&&(e=":not("+e+")");return 1===t.length&&1===r.nodeType?ot.find.matchesSelector(r,e)?[r]:[]:ot.find.matches(e,ot.grep(t,function(e){return 1===e.nodeType}))};ot.fn.extend({find:function(e){var t,i=[],r=this,n=r.length;if("string"!=typeof e)return this.pushStack(ot(e).filter(function(){for(t=0;n>t;t++)if(ot.contains(r[t],this))return!0}));for(t=0;n>t;t++)ot.find(e,r[t],i);i=this.pushStack(n>1?ot.unique(i):i);i.selector=this.selector?this.selector+" "+e:e;return i},filter:function(e){return this.pushStack(n(this,e||[],!1))},not:function(e){return this.pushStack(n(this,e||[],!0))},is:function(e){return!!n(this,"string"==typeof e&&ct.test(e)?ot(e):e||[],!1).length}});var ht,Et=t.document,mt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,gt=ot.fn.init=function(e,t){var i,r;if(!e)return this;if("string"==typeof e){i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:mt.exec(e);if(!i||!i[1]&&t)return!t||t.jquery?(t||ht).find(e):this.constructor(t).find(e);if(i[1]){t=t instanceof ot?t[0]:t;ot.merge(this,ot.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:Et,!0));if(dt.test(i[1])&&ot.isPlainObject(t))for(i in t)ot.isFunction(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}r=Et.getElementById(i[2]);if(r&&r.parentNode){if(r.id!==i[2])return ht.find(e);this.length=1;this[0]=r}this.context=Et;this.selector=e;return this}if(e.nodeType){this.context=this[0]=e;this.length=1;return this}if(ot.isFunction(e))return"undefined"!=typeof ht.ready?ht.ready(e):e(ot);if(void 0!==e.selector){this.selector=e.selector;this.context=e.context}return ot.makeArray(e,this)};gt.prototype=ot.fn;ht=ot(Et);var vt=/^(?:parents|prev(?:Until|All))/,xt={children:!0,contents:!0,next:!0,prev:!0};ot.extend({dir:function(e,t,i){for(var r=[],n=e[t];n&&9!==n.nodeType&&(void 0===i||1!==n.nodeType||!ot(n).is(i));){1===n.nodeType&&r.push(n);n=n[t]}return r},sibling:function(e,t){for(var i=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&i.push(e);return i}});ot.fn.extend({has:function(e){var t,i=ot(e,this),r=i.length;return this.filter(function(){for(t=0;r>t;t++)if(ot.contains(this,i[t]))return!0})},closest:function(e,t){for(var i,r=0,n=this.length,o=[],s=ct.test(e)||"string"!=typeof e?ot(e,t||this.context):0;n>r;r++)for(i=this[r];i&&i!==t;i=i.parentNode)if(i.nodeType<11&&(s?s.index(i)>-1:1===i.nodeType&&ot.find.matchesSelector(i,e))){o.push(i);break}return this.pushStack(o.length>1?ot.unique(o):o)},index:function(e){return e?"string"==typeof e?ot.inArray(this[0],ot(e)):ot.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(ot.unique(ot.merge(this.get(),ot(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});ot.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return ot.dir(e,"parentNode")},parentsUntil:function(e,t,i){return ot.dir(e,"parentNode",i)},next:function(e){return o(e,"nextSibling")},prev:function(e){return o(e,"previousSibling")},nextAll:function(e){return ot.dir(e,"nextSibling")},prevAll:function(e){return ot.dir(e,"previousSibling")},nextUntil:function(e,t,i){return ot.dir(e,"nextSibling",i)},prevUntil:function(e,t,i){return ot.dir(e,"previousSibling",i)},siblings:function(e){return ot.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return ot.sibling(e.firstChild)},contents:function(e){return ot.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:ot.merge([],e.childNodes)}},function(e,t){ot.fn[e]=function(i,r){var n=ot.map(this,t,i);"Until"!==e.slice(-5)&&(r=i);r&&"string"==typeof r&&(n=ot.filter(r,n));if(this.length>1){xt[e]||(n=ot.unique(n));vt.test(e)&&(n=n.reverse())}return this.pushStack(n)}});var Nt=/\S+/g,Tt={};ot.Callbacks=function(e){e="string"==typeof e?Tt[e]||s(e):ot.extend({},e);var t,i,r,n,o,a,l=[],u=!e.once&&[],p=function(s){i=e.memory&&s;r=!0;o=a||0;a=0;n=l.length;t=!0;for(;l&&n>o;o++)if(l[o].apply(s[0],s[1])===!1&&e.stopOnFalse){i=!1;break}t=!1;l&&(u?u.length&&p(u.shift()):i?l=[]:c.disable())},c={add:function(){if(l){var r=l.length;(function o(t){ot.each(t,function(t,i){var r=ot.type(i);"function"===r?e.unique&&c.has(i)||l.push(i):i&&i.length&&"string"!==r&&o(i)})})(arguments);if(t)n=l.length;else if(i){a=r;p(i)}}return this},remove:function(){l&&ot.each(arguments,function(e,i){for(var r;(r=ot.inArray(i,l,r))>-1;){l.splice(r,1);if(t){n>=r&&n--;o>=r&&o--}}});return this},has:function(e){return e?ot.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){l=[];n=0;return this},disable:function(){l=u=i=void 0;return this},disabled:function(){return!l},lock:function(){u=void 0;i||c.disable();return this},locked:function(){return!u},fireWith:function(e,i){if(l&&(!r||u)){i=i||[];i=[e,i.slice?i.slice():i];t?u.push(i):p(i)}return this},fire:function(){c.fireWith(this,arguments);return this},fired:function(){return!!r}};return c};ot.extend({Deferred:function(e){var t=[["resolve","done",ot.Callbacks("once memory"),"resolved"],["reject","fail",ot.Callbacks("once memory"),"rejected"],["notify","progress",ot.Callbacks("memory")]],i="pending",r={state:function(){return i},always:function(){n.done(arguments).fail(arguments);return this},then:function(){var e=arguments;return ot.Deferred(function(i){ot.each(t,function(t,o){var s=ot.isFunction(e[t])&&e[t];n[o[1]](function(){var e=s&&s.apply(this,arguments);e&&ot.isFunction(e.promise)?e.promise().done(i.resolve).fail(i.reject).progress(i.notify):i[o[0]+"With"](this===r?i.promise():this,s?[e]:arguments)})});e=null}).promise()},promise:function(e){return null!=e?ot.extend(e,r):r}},n={};r.pipe=r.then;ot.each(t,function(e,o){var s=o[2],a=o[3];r[o[1]]=s.add;a&&s.add(function(){i=a},t[1^e][2].disable,t[2][2].lock);n[o[0]]=function(){n[o[0]+"With"](this===n?r:this,arguments);return this};n[o[0]+"With"]=s.fireWith});r.promise(n);e&&e.call(n,n);return n},when:function(e){var t,i,r,n=0,o=$.call(arguments),s=o.length,a=1!==s||e&&ot.isFunction(e.promise)?s:0,l=1===a?e:ot.Deferred(),u=function(e,i,r){return function(n){i[e]=this;r[e]=arguments.length>1?$.call(arguments):n;r===t?l.notifyWith(i,r):--a||l.resolveWith(i,r)}};if(s>1){t=new Array(s);i=new Array(s);r=new Array(s);for(;s>n;n++)o[n]&&ot.isFunction(o[n].promise)?o[n].promise().done(u(n,r,o)).fail(l.reject).progress(u(n,i,t)):--a}a||l.resolveWith(r,o);return l.promise()}});var Lt;ot.fn.ready=function(e){ot.ready.promise().done(e);return this};ot.extend({isReady:!1,readyWait:1,holdReady:function(e){e?ot.readyWait++:ot.ready(!0)},ready:function(e){if(e===!0?!--ot.readyWait:!ot.isReady){if(!Et.body)return setTimeout(ot.ready);ot.isReady=!0;if(!(e!==!0&&--ot.readyWait>0)){Lt.resolveWith(Et,[ot]);if(ot.fn.triggerHandler){ot(Et).triggerHandler("ready");ot(Et).off("ready")}}}}});ot.ready.promise=function(e){if(!Lt){Lt=ot.Deferred();if("complete"===Et.readyState)setTimeout(ot.ready);else if(Et.addEventListener){Et.addEventListener("DOMContentLoaded",l,!1);t.addEventListener("load",l,!1)}else{Et.attachEvent("onreadystatechange",l);t.attachEvent("onload",l);var i=!1;try{i=null==t.frameElement&&Et.documentElement}catch(r){}i&&i.doScroll&&function n(){if(!ot.isReady){try{i.doScroll("left")}catch(e){return setTimeout(n,50)}a();ot.ready()}}()}}return Lt.promise(e)};var It,yt="undefined";for(It in ot(rt))break;rt.ownLast="0"!==It;rt.inlineBlockNeedsLayout=!1;ot(function(){var e,t,i,r;i=Et.getElementsByTagName("body")[0];if(i&&i.style){t=Et.createElement("div");r=Et.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(r).appendChild(t);if(typeof t.style.zoom!==yt){t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";rt.inlineBlockNeedsLayout=e=3===t.offsetWidth;e&&(i.style.zoom=1)}i.removeChild(r)}});(function(){var e=Et.createElement("div");if(null==rt.deleteExpando){rt.deleteExpando=!0;try{delete e.test}catch(t){rt.deleteExpando=!1}}e=null})();ot.acceptData=function(e){var t=ot.noData[(e.nodeName+" ").toLowerCase()],i=+e.nodeType||1;return 1!==i&&9!==i?!1:!t||t!==!0&&e.getAttribute("classid")===t};var At=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,St=/([A-Z])/g;ot.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){e=e.nodeType?ot.cache[e[ot.expando]]:e[ot.expando];return!!e&&!p(e)},data:function(e,t,i){return c(e,t,i)},removeData:function(e,t){return d(e,t)},_data:function(e,t,i){return c(e,t,i,!0)},_removeData:function(e,t){return d(e,t,!0)}});ot.fn.extend({data:function(e,t){var i,r,n,o=this[0],s=o&&o.attributes;if(void 0===e){if(this.length){n=ot.data(o);if(1===o.nodeType&&!ot._data(o,"parsedAttrs")){i=s.length;for(;i--;)if(s[i]){r=s[i].name;if(0===r.indexOf("data-")){r=ot.camelCase(r.slice(5));u(o,r,n[r])}}ot._data(o,"parsedAttrs",!0)}}return n}return"object"==typeof e?this.each(function(){ot.data(this,e)}):arguments.length>1?this.each(function(){ot.data(this,e,t)}):o?u(o,e,ot.data(o,e)):void 0},removeData:function(e){return this.each(function(){ot.removeData(this,e)})}});ot.extend({queue:function(e,t,i){var r;if(e){t=(t||"fx")+"queue";r=ot._data(e,t);i&&(!r||ot.isArray(i)?r=ot._data(e,t,ot.makeArray(i)):r.push(i));return r||[]}},dequeue:function(e,t){t=t||"fx";var i=ot.queue(e,t),r=i.length,n=i.shift(),o=ot._queueHooks(e,t),s=function(){ot.dequeue(e,t)};if("inprogress"===n){n=i.shift();r--}if(n){"fx"===t&&i.unshift("inprogress");delete o.stop;n.call(e,s,o)}!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var i=t+"queueHooks";return ot._data(e,i)||ot._data(e,i,{empty:ot.Callbacks("once memory").add(function(){ot._removeData(e,t+"queue");ot._removeData(e,i)})})}});ot.fn.extend({queue:function(e,t){var i=2;if("string"!=typeof e){t=e;e="fx";i--}return arguments.length<i?ot.queue(this[0],e):void 0===t?this:this.each(function(){var i=ot.queue(this,e,t);ot._queueHooks(this,e);"fx"===e&&"inprogress"!==i[0]&&ot.dequeue(this,e)})},dequeue:function(e){return this.each(function(){ot.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var i,r=1,n=ot.Deferred(),o=this,s=this.length,a=function(){--r||n.resolveWith(o,[o])};if("string"!=typeof e){t=e;e=void 0}e=e||"fx";for(;s--;){i=ot._data(o[s],e+"queueHooks");if(i&&i.empty){r++;i.empty.add(a)}}a();return n.promise(t)}});var Ct=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Rt=["Top","Right","Bottom","Left"],bt=function(e,t){e=t||e;return"none"===ot.css(e,"display")||!ot.contains(e.ownerDocument,e)},Ot=ot.access=function(e,t,i,r,n,o,s){var a=0,l=e.length,u=null==i;if("object"===ot.type(i)){n=!0;for(a in i)ot.access(e,t,a,i[a],!0,o,s)}else if(void 0!==r){n=!0;ot.isFunction(r)||(s=!0);if(u)if(s){t.call(e,r);t=null}else{u=t;t=function(e,t,i){return u.call(ot(e),i)}}if(t)for(;l>a;a++)t(e[a],i,s?r:r.call(e[a],a,t(e[a],i)))}return n?e:u?t.call(e):l?t(e[0],i):o},Pt=/^(?:checkbox|radio)$/i;(function(){var e=Et.createElement("input"),t=Et.createElement("div"),i=Et.createDocumentFragment();t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";rt.leadingWhitespace=3===t.firstChild.nodeType;rt.tbody=!t.getElementsByTagName("tbody").length;rt.htmlSerialize=!!t.getElementsByTagName("link").length;rt.html5Clone="<:nav></:nav>"!==Et.createElement("nav").cloneNode(!0).outerHTML;e.type="checkbox";e.checked=!0;i.appendChild(e);rt.appendChecked=e.checked;t.innerHTML="<textarea>x</textarea>";rt.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue;i.appendChild(t);t.innerHTML="<input type='radio' checked='checked' name='t'/>";rt.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked;rt.noCloneEvent=!0;if(t.attachEvent){t.attachEvent("onclick",function(){rt.noCloneEvent=!1});t.cloneNode(!0).click()}if(null==rt.deleteExpando){rt.deleteExpando=!0;try{delete t.test}catch(r){rt.deleteExpando=!1}}})();(function(){var e,i,r=Et.createElement("div");for(e in{submit:!0,change:!0,focusin:!0}){i="on"+e;if(!(rt[e+"Bubbles"]=i in t)){r.setAttribute(i,"t");rt[e+"Bubbles"]=r.attributes[i].expando===!1}}r=null})();var Dt=/^(?:input|select|textarea)$/i,wt=/^key/,_t=/^(?:mouse|pointer|contextmenu)|click/,Mt=/^(?:focusinfocus|focusoutblur)$/,kt=/^([^.]*)(?:\.(.+)|)$/;ot.event={global:{},add:function(e,t,i,r,n){var o,s,a,l,u,p,c,d,f,h,E,m=ot._data(e);if(m){if(i.handler){l=i;i=l.handler;n=l.selector}i.guid||(i.guid=ot.guid++);(s=m.events)||(s=m.events={});if(!(p=m.handle)){p=m.handle=function(e){return typeof ot===yt||e&&ot.event.triggered===e.type?void 0:ot.event.dispatch.apply(p.elem,arguments)};p.elem=e}t=(t||"").match(Nt)||[""];a=t.length;for(;a--;){o=kt.exec(t[a])||[];f=E=o[1];h=(o[2]||"").split(".").sort();if(f){u=ot.event.special[f]||{};f=(n?u.delegateType:u.bindType)||f;u=ot.event.special[f]||{};c=ot.extend({type:f,origType:E,data:r,handler:i,guid:i.guid,selector:n,needsContext:n&&ot.expr.match.needsContext.test(n),namespace:h.join(".")},l);if(!(d=s[f])){d=s[f]=[];d.delegateCount=0;u.setup&&u.setup.call(e,r,h,p)!==!1||(e.addEventListener?e.addEventListener(f,p,!1):e.attachEvent&&e.attachEvent("on"+f,p))}if(u.add){u.add.call(e,c);c.handler.guid||(c.handler.guid=i.guid)}n?d.splice(d.delegateCount++,0,c):d.push(c);ot.event.global[f]=!0}}e=null}},remove:function(e,t,i,r,n){var o,s,a,l,u,p,c,d,f,h,E,m=ot.hasData(e)&&ot._data(e);if(m&&(p=m.events)){t=(t||"").match(Nt)||[""];u=t.length;for(;u--;){a=kt.exec(t[u])||[];f=E=a[1];h=(a[2]||"").split(".").sort();if(f){c=ot.event.special[f]||{};f=(r?c.delegateType:c.bindType)||f;d=p[f]||[];a=a[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)");l=o=d.length;for(;o--;){s=d[o];if(!(!n&&E!==s.origType||i&&i.guid!==s.guid||a&&!a.test(s.namespace)||r&&r!==s.selector&&("**"!==r||!s.selector))){d.splice(o,1);s.selector&&d.delegateCount--;c.remove&&c.remove.call(e,s)}}if(l&&!d.length){c.teardown&&c.teardown.call(e,h,m.handle)!==!1||ot.removeEvent(e,f,m.handle);delete p[f]}}else for(f in p)ot.event.remove(e,f+t[u],i,r,!0)}if(ot.isEmptyObject(p)){delete m.handle;ot._removeData(e,"events")}}},trigger:function(e,i,r,n){var o,s,a,l,u,p,c,d=[r||Et],f=it.call(e,"type")?e.type:e,h=it.call(e,"namespace")?e.namespace.split("."):[];a=p=r=r||Et;if(3!==r.nodeType&&8!==r.nodeType&&!Mt.test(f+ot.event.triggered)){if(f.indexOf(".")>=0){h=f.split(".");f=h.shift();h.sort()}s=f.indexOf(":")<0&&"on"+f;e=e[ot.expando]?e:new ot.Event(f,"object"==typeof e&&e);e.isTrigger=n?2:3;e.namespace=h.join(".");e.namespace_re=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;e.result=void 0;e.target||(e.target=r);i=null==i?[e]:ot.makeArray(i,[e]);u=ot.event.special[f]||{};if(n||!u.trigger||u.trigger.apply(r,i)!==!1){if(!n&&!u.noBubble&&!ot.isWindow(r)){l=u.delegateType||f;Mt.test(l+f)||(a=a.parentNode);for(;a;a=a.parentNode){d.push(a);p=a}p===(r.ownerDocument||Et)&&d.push(p.defaultView||p.parentWindow||t)}c=0;for(;(a=d[c++])&&!e.isPropagationStopped();){e.type=c>1?l:u.bindType||f;o=(ot._data(a,"events")||{})[e.type]&&ot._data(a,"handle");o&&o.apply(a,i);o=s&&a[s];if(o&&o.apply&&ot.acceptData(a)){e.result=o.apply(a,i);e.result===!1&&e.preventDefault()}}e.type=f;if(!n&&!e.isDefaultPrevented()&&(!u._default||u._default.apply(d.pop(),i)===!1)&&ot.acceptData(r)&&s&&r[f]&&!ot.isWindow(r)){p=r[s];p&&(r[s]=null);ot.event.triggered=f;try{r[f]()}catch(E){}ot.event.triggered=void 0;p&&(r[s]=p)}return e.result}}},dispatch:function(e){e=ot.event.fix(e);var t,i,r,n,o,s=[],a=$.call(arguments),l=(ot._data(this,"events")||{})[e.type]||[],u=ot.event.special[e.type]||{};a[0]=e;e.delegateTarget=this;if(!u.preDispatch||u.preDispatch.call(this,e)!==!1){s=ot.event.handlers.call(this,e,l);t=0;for(;(n=s[t++])&&!e.isPropagationStopped();){e.currentTarget=n.elem;o=0;for(;(r=n.handlers[o++])&&!e.isImmediatePropagationStopped();)if(!e.namespace_re||e.namespace_re.test(r.namespace)){e.handleObj=r;e.data=r.data;i=((ot.event.special[r.origType]||{}).handle||r.handler).apply(n.elem,a);if(void 0!==i&&(e.result=i)===!1){e.preventDefault();e.stopPropagation()}}}u.postDispatch&&u.postDispatch.call(this,e);return e.result}},handlers:function(e,t){var i,r,n,o,s=[],a=t.delegateCount,l=e.target;if(a&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){n=[];for(o=0;a>o;o++){r=t[o];i=r.selector+" ";void 0===n[i]&&(n[i]=r.needsContext?ot(i,this).index(l)>=0:ot.find(i,this,null,[l]).length);n[i]&&n.push(r)}n.length&&s.push({elem:l,handlers:n})}a<t.length&&s.push({elem:this,handlers:t.slice(a)});return s},fix:function(e){if(e[ot.expando])return e;var t,i,r,n=e.type,o=e,s=this.fixHooks[n];s||(this.fixHooks[n]=s=_t.test(n)?this.mouseHooks:wt.test(n)?this.keyHooks:{});r=s.props?this.props.concat(s.props):this.props;e=new ot.Event(o);t=r.length;for(;t--;){i=r[t];e[i]=o[i]}e.target||(e.target=o.srcElement||Et);3===e.target.nodeType&&(e.target=e.target.parentNode);e.metaKey=!!e.metaKey;return s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode);return e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var i,r,n,o=t.button,s=t.fromElement;if(null==e.pageX&&null!=t.clientX){r=e.target.ownerDocument||Et;n=r.documentElement;i=r.body;e.pageX=t.clientX+(n&&n.scrollLeft||i&&i.scrollLeft||0)-(n&&n.clientLeft||i&&i.clientLeft||0);e.pageY=t.clientY+(n&&n.scrollTop||i&&i.scrollTop||0)-(n&&n.clientTop||i&&i.clientTop||0)}!e.relatedTarget&&s&&(e.relatedTarget=s===e.target?t.toElement:s);e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0);return e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==E()&&this.focus)try{this.focus();return!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){if(this===E()&&this.blur){this.blur();return!1}},delegateType:"focusout"},click:{trigger:function(){if(ot.nodeName(this,"input")&&"checkbox"===this.type&&this.click){this.click();return!1}},_default:function(e){return ot.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,i,r){var n=ot.extend(new ot.Event,i,{type:e,isSimulated:!0,originalEvent:{}});r?ot.event.trigger(n,null,t):ot.event.dispatch.call(t,n);n.isDefaultPrevented()&&i.preventDefault()}};ot.removeEvent=Et.removeEventListener?function(e,t,i){e.removeEventListener&&e.removeEventListener(t,i,!1)}:function(e,t,i){var r="on"+t;if(e.detachEvent){typeof e[r]===yt&&(e[r]=null);e.detachEvent(r,i)}};ot.Event=function(e,t){if(!(this instanceof ot.Event))return new ot.Event(e,t);if(e&&e.type){this.originalEvent=e;this.type=e.type;this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?f:h}else this.type=e;t&&ot.extend(this,t);this.timeStamp=e&&e.timeStamp||ot.now();this[ot.expando]=!0};ot.Event.prototype={isDefaultPrevented:h,isPropagationStopped:h,isImmediatePropagationStopped:h,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=f;e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=f;if(e){e.stopPropagation&&e.stopPropagation();e.cancelBubble=!0}},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=f;e&&e.stopImmediatePropagation&&e.stopImmediatePropagation();this.stopPropagation()}};ot.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){ot.event.special[e]={delegateType:t,bindType:t,handle:function(e){var i,r=this,n=e.relatedTarget,o=e.handleObj;if(!n||n!==r&&!ot.contains(r,n)){e.type=o.origType;i=o.handler.apply(this,arguments);e.type=t}return i}}});rt.submitBubbles||(ot.event.special.submit={setup:function(){if(ot.nodeName(this,"form"))return!1;ot.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,i=ot.nodeName(t,"input")||ot.nodeName(t,"button")?t.form:void 0;if(i&&!ot._data(i,"submitBubbles")){ot.event.add(i,"submit._submit",function(e){e._submit_bubble=!0});ot._data(i,"submitBubbles",!0)}});return void 0},postDispatch:function(e){if(e._submit_bubble){delete e._submit_bubble;this.parentNode&&!e.isTrigger&&ot.event.simulate("submit",this.parentNode,e,!0)}},teardown:function(){if(ot.nodeName(this,"form"))return!1;ot.event.remove(this,"._submit");return void 0}});rt.changeBubbles||(ot.event.special.change={setup:function(){if(Dt.test(this.nodeName)){if("checkbox"===this.type||"radio"===this.type){ot.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)});ot.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1);ot.event.simulate("change",this,e,!0)})}return!1}ot.event.add(this,"beforeactivate._change",function(e){var t=e.target;if(Dt.test(t.nodeName)&&!ot._data(t,"changeBubbles")){ot.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||ot.event.simulate("change",this.parentNode,e,!0)});ot._data(t,"changeBubbles",!0)}})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){ot.event.remove(this,"._change");return!Dt.test(this.nodeName)}});rt.focusinBubbles||ot.each({focus:"focusin",blur:"focusout"},function(e,t){var i=function(e){ot.event.simulate(t,e.target,ot.event.fix(e),!0)};ot.event.special[t]={setup:function(){var r=this.ownerDocument||this,n=ot._data(r,t);n||r.addEventListener(e,i,!0);ot._data(r,t,(n||0)+1)},teardown:function(){var r=this.ownerDocument||this,n=ot._data(r,t)-1;if(n)ot._data(r,t,n);else{r.removeEventListener(e,i,!0);ot._removeData(r,t)}}}});ot.fn.extend({on:function(e,t,i,r,n){var o,s;if("object"==typeof e){if("string"!=typeof t){i=i||t;t=void 0}for(o in e)this.on(o,t,i,e[o],n);return this}if(null==i&&null==r){r=t;i=t=void 0}else if(null==r)if("string"==typeof t){r=i;i=void 0}else{r=i;i=t;t=void 0}if(r===!1)r=h;else if(!r)return this;if(1===n){s=r;r=function(e){ot().off(e);return s.apply(this,arguments)};r.guid=s.guid||(s.guid=ot.guid++)}return this.each(function(){ot.event.add(this,e,r,i,t)})},one:function(e,t,i,r){return this.on(e,t,i,r,1)},off:function(e,t,i){var r,n;if(e&&e.preventDefault&&e.handleObj){r=e.handleObj;ot(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler);return this}if("object"==typeof e){for(n in e)this.off(n,t,e[n]);return this}if(t===!1||"function"==typeof t){i=t;t=void 0}i===!1&&(i=h);return this.each(function(){ot.event.remove(this,e,i,t)})},trigger:function(e,t){return this.each(function(){ot.event.trigger(e,t,this)})},triggerHandler:function(e,t){var i=this[0];return i?ot.event.trigger(e,t,i,!0):void 0}});var Gt="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Bt=/ jQuery\d+="(?:null|\d+)"/g,Ut=new RegExp("<(?:"+Gt+")[\\s/>]","i"),Vt=/^\s+/,Ft=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Ht=/<([\w:]+)/,jt=/<tbody/i,Wt=/<|&#?\w+;/,qt=/<(?:script|style|link)/i,zt=/checked\s*(?:[^=]|=\s*.checked.)/i,Xt=/^$|\/(?:java|ecma)script/i,Yt=/^true\/(.*)/,Kt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,$t={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:rt.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Qt=m(Et),Zt=Qt.appendChild(Et.createElement("div"));$t.optgroup=$t.option;$t.tbody=$t.tfoot=$t.colgroup=$t.caption=$t.thead;$t.th=$t.td;ot.extend({clone:function(e,t,i){var r,n,o,s,a,l=ot.contains(e.ownerDocument,e);if(rt.html5Clone||ot.isXMLDoc(e)||!Ut.test("<"+e.nodeName+">"))o=e.cloneNode(!0);else{Zt.innerHTML=e.outerHTML;Zt.removeChild(o=Zt.firstChild)}if(!(rt.noCloneEvent&&rt.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||ot.isXMLDoc(e))){r=g(o);a=g(e);for(s=0;null!=(n=a[s]);++s)r[s]&&y(n,r[s])}if(t)if(i){a=a||g(e);r=r||g(o);for(s=0;null!=(n=a[s]);s++)I(n,r[s])}else I(e,o);r=g(o,"script");r.length>0&&L(r,!l&&g(e,"script"));r=a=n=null;return o},buildFragment:function(e,t,i,r){for(var n,o,s,a,l,u,p,c=e.length,d=m(t),f=[],h=0;c>h;h++){o=e[h];if(o||0===o)if("object"===ot.type(o))ot.merge(f,o.nodeType?[o]:o);else if(Wt.test(o)){a=a||d.appendChild(t.createElement("div"));l=(Ht.exec(o)||["",""])[1].toLowerCase();p=$t[l]||$t._default;a.innerHTML=p[1]+o.replace(Ft,"<$1></$2>")+p[2];n=p[0];for(;n--;)a=a.lastChild;!rt.leadingWhitespace&&Vt.test(o)&&f.push(t.createTextNode(Vt.exec(o)[0]));if(!rt.tbody){o="table"!==l||jt.test(o)?"<table>"!==p[1]||jt.test(o)?0:a:a.firstChild;n=o&&o.childNodes.length;for(;n--;)ot.nodeName(u=o.childNodes[n],"tbody")&&!u.childNodes.length&&o.removeChild(u) }ot.merge(f,a.childNodes);a.textContent="";for(;a.firstChild;)a.removeChild(a.firstChild);a=d.lastChild}else f.push(t.createTextNode(o))}a&&d.removeChild(a);rt.appendChecked||ot.grep(g(f,"input"),v);h=0;for(;o=f[h++];)if(!r||-1===ot.inArray(o,r)){s=ot.contains(o.ownerDocument,o);a=g(d.appendChild(o),"script");s&&L(a);if(i){n=0;for(;o=a[n++];)Xt.test(o.type||"")&&i.push(o)}}a=null;return d},cleanData:function(e,t){for(var i,r,n,o,s=0,a=ot.expando,l=ot.cache,u=rt.deleteExpando,p=ot.event.special;null!=(i=e[s]);s++)if(t||ot.acceptData(i)){n=i[a];o=n&&l[n];if(o){if(o.events)for(r in o.events)p[r]?ot.event.remove(i,r):ot.removeEvent(i,r,o.handle);if(l[n]){delete l[n];u?delete i[a]:typeof i.removeAttribute!==yt?i.removeAttribute(a):i[a]=null;K.push(n)}}}}});ot.fn.extend({text:function(e){return Ot(this,function(e){return void 0===e?ot.text(this):this.empty().append((this[0]&&this[0].ownerDocument||Et).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=x(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=x(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var i,r=e?ot.filter(e,this):this,n=0;null!=(i=r[n]);n++){t||1!==i.nodeType||ot.cleanData(g(i));if(i.parentNode){t&&ot.contains(i.ownerDocument,i)&&L(g(i,"script"));i.parentNode.removeChild(i)}}return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){1===e.nodeType&&ot.cleanData(g(e,!1));for(;e.firstChild;)e.removeChild(e.firstChild);e.options&&ot.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){e=null==e?!1:e;t=null==t?e:t;return this.map(function(){return ot.clone(this,e,t)})},html:function(e){return Ot(this,function(e){var t=this[0]||{},i=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Bt,""):void 0;if(!("string"!=typeof e||qt.test(e)||!rt.htmlSerialize&&Ut.test(e)||!rt.leadingWhitespace&&Vt.test(e)||$t[(Ht.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Ft,"<$1></$2>");try{for(;r>i;i++){t=this[i]||{};if(1===t.nodeType){ot.cleanData(g(t,!1));t.innerHTML=e}}t=0}catch(n){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];this.domManip(arguments,function(t){e=this.parentNode;ot.cleanData(g(this));e&&e.replaceChild(t,this)});return e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=Q.apply([],e);var i,r,n,o,s,a,l=0,u=this.length,p=this,c=u-1,d=e[0],f=ot.isFunction(d);if(f||u>1&&"string"==typeof d&&!rt.checkClone&&zt.test(d))return this.each(function(i){var r=p.eq(i);f&&(e[0]=d.call(this,i,r.html()));r.domManip(e,t)});if(u){a=ot.buildFragment(e,this[0].ownerDocument,!1,this);i=a.firstChild;1===a.childNodes.length&&(a=i);if(i){o=ot.map(g(a,"script"),N);n=o.length;for(;u>l;l++){r=a;if(l!==c){r=ot.clone(r,!0,!0);n&&ot.merge(o,g(r,"script"))}t.call(this[l],r,l)}if(n){s=o[o.length-1].ownerDocument;ot.map(o,T);for(l=0;n>l;l++){r=o[l];Xt.test(r.type||"")&&!ot._data(r,"globalEval")&&ot.contains(s,r)&&(r.src?ot._evalUrl&&ot._evalUrl(r.src):ot.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Kt,"")))}}a=i=null}}return this}});ot.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){ot.fn[e]=function(e){for(var i,r=0,n=[],o=ot(e),s=o.length-1;s>=r;r++){i=r===s?this:this.clone(!0);ot(o[r])[t](i);Z.apply(n,i.get())}return this.pushStack(n)}});var Jt,ei={};(function(){var e;rt.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,i,r;i=Et.getElementsByTagName("body")[0];if(i&&i.style){t=Et.createElement("div");r=Et.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(r).appendChild(t);if(typeof t.style.zoom!==yt){t.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";t.appendChild(Et.createElement("div")).style.width="5px";e=3!==t.offsetWidth}i.removeChild(r);return e}}})();var ti,ii,ri=/^margin/,ni=new RegExp("^("+Ct+")(?!px)[a-z%]+$","i"),oi=/^(top|right|bottom|left)$/;if(t.getComputedStyle){ti=function(e){return e.ownerDocument.defaultView.opener?e.ownerDocument.defaultView.getComputedStyle(e,null):t.getComputedStyle(e,null)};ii=function(e,t,i){var r,n,o,s,a=e.style;i=i||ti(e);s=i?i.getPropertyValue(t)||i[t]:void 0;if(i){""!==s||ot.contains(e.ownerDocument,e)||(s=ot.style(e,t));if(ni.test(s)&&ri.test(t)){r=a.width;n=a.minWidth;o=a.maxWidth;a.minWidth=a.maxWidth=a.width=s;s=i.width;a.width=r;a.minWidth=n;a.maxWidth=o}}return void 0===s?s:s+""}}else if(Et.documentElement.currentStyle){ti=function(e){return e.currentStyle};ii=function(e,t,i){var r,n,o,s,a=e.style;i=i||ti(e);s=i?i[t]:void 0;null==s&&a&&a[t]&&(s=a[t]);if(ni.test(s)&&!oi.test(t)){r=a.left;n=e.runtimeStyle;o=n&&n.left;o&&(n.left=e.currentStyle.left);a.left="fontSize"===t?"1em":s;s=a.pixelLeft+"px";a.left=r;o&&(n.left=o)}return void 0===s?s:s+""||"auto"}}(function(){function e(){var e,i,r,n;i=Et.getElementsByTagName("body")[0];if(i&&i.style){e=Et.createElement("div");r=Et.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(r).appendChild(e);e.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";o=s=!1;l=!0;if(t.getComputedStyle){o="1%"!==(t.getComputedStyle(e,null)||{}).top;s="4px"===(t.getComputedStyle(e,null)||{width:"4px"}).width;n=e.appendChild(Et.createElement("div"));n.style.cssText=e.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0";n.style.marginRight=n.style.width="0";e.style.width="1px";l=!parseFloat((t.getComputedStyle(n,null)||{}).marginRight);e.removeChild(n)}e.innerHTML="<table><tr><td></td><td>t</td></tr></table>";n=e.getElementsByTagName("td");n[0].style.cssText="margin:0;border:0;padding:0;display:none";a=0===n[0].offsetHeight;if(a){n[0].style.display="";n[1].style.display="none";a=0===n[0].offsetHeight}i.removeChild(r)}}var i,r,n,o,s,a,l;i=Et.createElement("div");i.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";n=i.getElementsByTagName("a")[0];r=n&&n.style;if(r){r.cssText="float:left;opacity:.5";rt.opacity="0.5"===r.opacity;rt.cssFloat=!!r.cssFloat;i.style.backgroundClip="content-box";i.cloneNode(!0).style.backgroundClip="";rt.clearCloneStyle="content-box"===i.style.backgroundClip;rt.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing;ot.extend(rt,{reliableHiddenOffsets:function(){null==a&&e();return a},boxSizingReliable:function(){null==s&&e();return s},pixelPosition:function(){null==o&&e();return o},reliableMarginRight:function(){null==l&&e();return l}})}})();ot.swap=function(e,t,i,r){var n,o,s={};for(o in t){s[o]=e.style[o];e.style[o]=t[o]}n=i.apply(e,r||[]);for(o in t)e.style[o]=s[o];return n};var si=/alpha\([^)]*\)/i,ai=/opacity\s*=\s*([^)]*)/,li=/^(none|table(?!-c[ea]).+)/,ui=new RegExp("^("+Ct+")(.*)$","i"),pi=new RegExp("^([+-])=("+Ct+")","i"),ci={position:"absolute",visibility:"hidden",display:"block"},di={letterSpacing:"0",fontWeight:"400"},fi=["Webkit","O","Moz","ms"];ot.extend({cssHooks:{opacity:{get:function(e,t){if(t){var i=ii(e,"opacity");return""===i?"1":i}}}},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":rt.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,i,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var n,o,s,a=ot.camelCase(t),l=e.style;t=ot.cssProps[a]||(ot.cssProps[a]=R(l,a));s=ot.cssHooks[t]||ot.cssHooks[a];if(void 0===i)return s&&"get"in s&&void 0!==(n=s.get(e,!1,r))?n:l[t];o=typeof i;if("string"===o&&(n=pi.exec(i))){i=(n[1]+1)*n[2]+parseFloat(ot.css(e,t));o="number"}if(null!=i&&i===i){"number"!==o||ot.cssNumber[a]||(i+="px");rt.clearCloneStyle||""!==i||0!==t.indexOf("background")||(l[t]="inherit");if(!(s&&"set"in s&&void 0===(i=s.set(e,i,r))))try{l[t]=i}catch(u){}}}},css:function(e,t,i,r){var n,o,s,a=ot.camelCase(t);t=ot.cssProps[a]||(ot.cssProps[a]=R(e.style,a));s=ot.cssHooks[t]||ot.cssHooks[a];s&&"get"in s&&(o=s.get(e,!0,i));void 0===o&&(o=ii(e,t,r));"normal"===o&&t in di&&(o=di[t]);if(""===i||i){n=parseFloat(o);return i===!0||ot.isNumeric(n)?n||0:o}return o}});ot.each(["height","width"],function(e,t){ot.cssHooks[t]={get:function(e,i,r){return i?li.test(ot.css(e,"display"))&&0===e.offsetWidth?ot.swap(e,ci,function(){return D(e,t,r)}):D(e,t,r):void 0},set:function(e,i,r){var n=r&&ti(e);return O(e,i,r?P(e,t,r,rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,n),n):0)}}});rt.opacity||(ot.cssHooks.opacity={get:function(e,t){return ai.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var i=e.style,r=e.currentStyle,n=ot.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||i.filter||"";i.zoom=1;if((t>=1||""===t)&&""===ot.trim(o.replace(si,""))&&i.removeAttribute){i.removeAttribute("filter");if(""===t||r&&!r.filter)return}i.filter=si.test(o)?o.replace(si,n):o+" "+n}});ot.cssHooks.marginRight=C(rt.reliableMarginRight,function(e,t){return t?ot.swap(e,{display:"inline-block"},ii,[e,"marginRight"]):void 0});ot.each({margin:"",padding:"",border:"Width"},function(e,t){ot.cssHooks[e+t]={expand:function(i){for(var r=0,n={},o="string"==typeof i?i.split(" "):[i];4>r;r++)n[e+Rt[r]+t]=o[r]||o[r-2]||o[0];return n}};ri.test(e)||(ot.cssHooks[e+t].set=O)});ot.fn.extend({css:function(e,t){return Ot(this,function(e,t,i){var r,n,o={},s=0;if(ot.isArray(t)){r=ti(e);n=t.length;for(;n>s;s++)o[t[s]]=ot.css(e,t[s],!1,r);return o}return void 0!==i?ot.style(e,t,i):ot.css(e,t)},e,t,arguments.length>1)},show:function(){return b(this,!0)},hide:function(){return b(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){bt(this)?ot(this).show():ot(this).hide()})}});ot.Tween=w;w.prototype={constructor:w,init:function(e,t,i,r,n,o){this.elem=e;this.prop=i;this.easing=n||"swing";this.options=t;this.start=this.now=this.cur();this.end=r;this.unit=o||(ot.cssNumber[i]?"":"px")},cur:function(){var e=w.propHooks[this.prop];return e&&e.get?e.get(this):w.propHooks._default.get(this)},run:function(e){var t,i=w.propHooks[this.prop];this.pos=t=this.options.duration?ot.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e;this.now=(this.end-this.start)*t+this.start;this.options.step&&this.options.step.call(this.elem,this.now,this);i&&i.set?i.set(this):w.propHooks._default.set(this);return this}};w.prototype.init.prototype=w.prototype;w.propHooks={_default:{get:function(e){var t;if(null!=e.elem[e.prop]&&(!e.elem.style||null==e.elem.style[e.prop]))return e.elem[e.prop];t=ot.css(e.elem,e.prop,"");return t&&"auto"!==t?t:0},set:function(e){ot.fx.step[e.prop]?ot.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[ot.cssProps[e.prop]]||ot.cssHooks[e.prop])?ot.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}};w.propHooks.scrollTop=w.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}};ot.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}};ot.fx=w.prototype.init;ot.fx.step={};var hi,Ei,mi=/^(?:toggle|show|hide)$/,gi=new RegExp("^(?:([+-])=|)("+Ct+")([a-z%]*)$","i"),vi=/queueHooks$/,xi=[G],Ni={"*":[function(e,t){var i=this.createTween(e,t),r=i.cur(),n=gi.exec(t),o=n&&n[3]||(ot.cssNumber[e]?"":"px"),s=(ot.cssNumber[e]||"px"!==o&&+r)&&gi.exec(ot.css(i.elem,e)),a=1,l=20;if(s&&s[3]!==o){o=o||s[3];n=n||[];s=+r||1;do{a=a||".5";s/=a;ot.style(i.elem,e,s+o)}while(a!==(a=i.cur()/r)&&1!==a&&--l)}if(n){s=i.start=+s||+r||0;i.unit=o;i.end=n[1]?s+(n[1]+1)*n[2]:+n[2]}return i}]};ot.Animation=ot.extend(U,{tweener:function(e,t){if(ot.isFunction(e)){t=e;e=["*"]}else e=e.split(" ");for(var i,r=0,n=e.length;n>r;r++){i=e[r];Ni[i]=Ni[i]||[];Ni[i].unshift(t)}},prefilter:function(e,t){t?xi.unshift(e):xi.push(e)}});ot.speed=function(e,t,i){var r=e&&"object"==typeof e?ot.extend({},e):{complete:i||!i&&t||ot.isFunction(e)&&e,duration:e,easing:i&&t||t&&!ot.isFunction(t)&&t};r.duration=ot.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in ot.fx.speeds?ot.fx.speeds[r.duration]:ot.fx.speeds._default;(null==r.queue||r.queue===!0)&&(r.queue="fx");r.old=r.complete;r.complete=function(){ot.isFunction(r.old)&&r.old.call(this);r.queue&&ot.dequeue(this,r.queue)};return r};ot.fn.extend({fadeTo:function(e,t,i,r){return this.filter(bt).css("opacity",0).show().end().animate({opacity:t},e,i,r)},animate:function(e,t,i,r){var n=ot.isEmptyObject(e),o=ot.speed(t,i,r),s=function(){var t=U(this,ot.extend({},e),o);(n||ot._data(this,"finish"))&&t.stop(!0)};s.finish=s;return n||o.queue===!1?this.each(s):this.queue(o.queue,s)},stop:function(e,t,i){var r=function(e){var t=e.stop;delete e.stop;t(i)};if("string"!=typeof e){i=t;t=e;e=void 0}t&&e!==!1&&this.queue(e||"fx",[]);return this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=ot.timers,s=ot._data(this);if(n)s[n]&&s[n].stop&&r(s[n]);else for(n in s)s[n]&&s[n].stop&&vi.test(n)&&r(s[n]);for(n=o.length;n--;)if(o[n].elem===this&&(null==e||o[n].queue===e)){o[n].anim.stop(i);t=!1;o.splice(n,1)}(t||!i)&&ot.dequeue(this,e)})},finish:function(e){e!==!1&&(e=e||"fx");return this.each(function(){var t,i=ot._data(this),r=i[e+"queue"],n=i[e+"queueHooks"],o=ot.timers,s=r?r.length:0;i.finish=!0;ot.queue(this,e,[]);n&&n.stop&&n.stop.call(this,!0);for(t=o.length;t--;)if(o[t].elem===this&&o[t].queue===e){o[t].anim.stop(!0);o.splice(t,1)}for(t=0;s>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete i.finish})}});ot.each(["toggle","show","hide"],function(e,t){var i=ot.fn[t];ot.fn[t]=function(e,r,n){return null==e||"boolean"==typeof e?i.apply(this,arguments):this.animate(M(t,!0),e,r,n)}});ot.each({slideDown:M("show"),slideUp:M("hide"),slideToggle:M("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){ot.fn[e]=function(e,i,r){return this.animate(t,e,i,r)}});ot.timers=[];ot.fx.tick=function(){var e,t=ot.timers,i=0;hi=ot.now();for(;i<t.length;i++){e=t[i];e()||t[i]!==e||t.splice(i--,1)}t.length||ot.fx.stop();hi=void 0};ot.fx.timer=function(e){ot.timers.push(e);e()?ot.fx.start():ot.timers.pop()};ot.fx.interval=13;ot.fx.start=function(){Ei||(Ei=setInterval(ot.fx.tick,ot.fx.interval))};ot.fx.stop=function(){clearInterval(Ei);Ei=null};ot.fx.speeds={slow:600,fast:200,_default:400};ot.fn.delay=function(e,t){e=ot.fx?ot.fx.speeds[e]||e:e;t=t||"fx";return this.queue(t,function(t,i){var r=setTimeout(t,e);i.stop=function(){clearTimeout(r)}})};(function(){var e,t,i,r,n;t=Et.createElement("div");t.setAttribute("className","t");t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";r=t.getElementsByTagName("a")[0];i=Et.createElement("select");n=i.appendChild(Et.createElement("option"));e=t.getElementsByTagName("input")[0];r.style.cssText="top:1px";rt.getSetAttribute="t"!==t.className;rt.style=/top/.test(r.getAttribute("style"));rt.hrefNormalized="/a"===r.getAttribute("href");rt.checkOn=!!e.value;rt.optSelected=n.selected;rt.enctype=!!Et.createElement("form").enctype;i.disabled=!0;rt.optDisabled=!n.disabled;e=Et.createElement("input");e.setAttribute("value","");rt.input=""===e.getAttribute("value");e.value="t";e.setAttribute("type","radio");rt.radioValue="t"===e.value})();var Ti=/\r/g;ot.fn.extend({val:function(e){var t,i,r,n=this[0];if(arguments.length){r=ot.isFunction(e);return this.each(function(i){var n;if(1===this.nodeType){n=r?e.call(this,i,ot(this).val()):e;null==n?n="":"number"==typeof n?n+="":ot.isArray(n)&&(n=ot.map(n,function(e){return null==e?"":e+""}));t=ot.valHooks[this.type]||ot.valHooks[this.nodeName.toLowerCase()];t&&"set"in t&&void 0!==t.set(this,n,"value")||(this.value=n)}})}if(n){t=ot.valHooks[n.type]||ot.valHooks[n.nodeName.toLowerCase()];if(t&&"get"in t&&void 0!==(i=t.get(n,"value")))return i;i=n.value;return"string"==typeof i?i.replace(Ti,""):null==i?"":i}}});ot.extend({valHooks:{option:{get:function(e){var t=ot.find.attr(e,"value");return null!=t?t:ot.trim(ot.text(e))}},select:{get:function(e){for(var t,i,r=e.options,n=e.selectedIndex,o="select-one"===e.type||0>n,s=o?null:[],a=o?n+1:r.length,l=0>n?a:o?n:0;a>l;l++){i=r[l];if(!(!i.selected&&l!==n||(rt.optDisabled?i.disabled:null!==i.getAttribute("disabled"))||i.parentNode.disabled&&ot.nodeName(i.parentNode,"optgroup"))){t=ot(i).val();if(o)return t;s.push(t)}}return s},set:function(e,t){for(var i,r,n=e.options,o=ot.makeArray(t),s=n.length;s--;){r=n[s];if(ot.inArray(ot.valHooks.option.get(r),o)>=0)try{r.selected=i=!0}catch(a){r.scrollHeight}else r.selected=!1}i||(e.selectedIndex=-1);return n}}}});ot.each(["radio","checkbox"],function(){ot.valHooks[this]={set:function(e,t){return ot.isArray(t)?e.checked=ot.inArray(ot(e).val(),t)>=0:void 0}};rt.checkOn||(ot.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Li,Ii,yi=ot.expr.attrHandle,Ai=/^(?:checked|selected)$/i,Si=rt.getSetAttribute,Ci=rt.input;ot.fn.extend({attr:function(e,t){return Ot(this,ot.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){ot.removeAttr(this,e)})}});ot.extend({attr:function(e,t,i){var r,n,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o){if(typeof e.getAttribute===yt)return ot.prop(e,t,i);if(1!==o||!ot.isXMLDoc(e)){t=t.toLowerCase();r=ot.attrHooks[t]||(ot.expr.match.bool.test(t)?Ii:Li)}if(void 0===i){if(r&&"get"in r&&null!==(n=r.get(e,t)))return n;n=ot.find.attr(e,t);return null==n?void 0:n}if(null!==i){if(r&&"set"in r&&void 0!==(n=r.set(e,i,t)))return n;e.setAttribute(t,i+"");return i}ot.removeAttr(e,t)}},removeAttr:function(e,t){var i,r,n=0,o=t&&t.match(Nt);if(o&&1===e.nodeType)for(;i=o[n++];){r=ot.propFix[i]||i;ot.expr.match.bool.test(i)?Ci&&Si||!Ai.test(i)?e[r]=!1:e[ot.camelCase("default-"+i)]=e[r]=!1:ot.attr(e,i,"");e.removeAttribute(Si?i:r)}},attrHooks:{type:{set:function(e,t){if(!rt.radioValue&&"radio"===t&&ot.nodeName(e,"input")){var i=e.value;e.setAttribute("type",t);i&&(e.value=i);return t}}}}});Ii={set:function(e,t,i){t===!1?ot.removeAttr(e,i):Ci&&Si||!Ai.test(i)?e.setAttribute(!Si&&ot.propFix[i]||i,i):e[ot.camelCase("default-"+i)]=e[i]=!0;return i}};ot.each(ot.expr.match.bool.source.match(/\w+/g),function(e,t){var i=yi[t]||ot.find.attr;yi[t]=Ci&&Si||!Ai.test(t)?function(e,t,r){var n,o;if(!r){o=yi[t];yi[t]=n;n=null!=i(e,t,r)?t.toLowerCase():null;yi[t]=o}return n}:function(e,t,i){return i?void 0:e[ot.camelCase("default-"+t)]?t.toLowerCase():null}});Ci&&Si||(ot.attrHooks.value={set:function(e,t,i){if(!ot.nodeName(e,"input"))return Li&&Li.set(e,t,i);e.defaultValue=t;return void 0}});if(!Si){Li={set:function(e,t,i){var r=e.getAttributeNode(i);r||e.setAttributeNode(r=e.ownerDocument.createAttribute(i));r.value=t+="";return"value"===i||t===e.getAttribute(i)?t:void 0}};yi.id=yi.name=yi.coords=function(e,t,i){var r;return i?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null};ot.valHooks.button={get:function(e,t){var i=e.getAttributeNode(t);return i&&i.specified?i.value:void 0},set:Li.set};ot.attrHooks.contenteditable={set:function(e,t,i){Li.set(e,""===t?!1:t,i)}};ot.each(["width","height"],function(e,t){ot.attrHooks[t]={set:function(e,i){if(""===i){e.setAttribute(t,"auto");return i}}}})}rt.style||(ot.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var Ri=/^(?:input|select|textarea|button|object)$/i,bi=/^(?:a|area)$/i;ot.fn.extend({prop:function(e,t){return Ot(this,ot.prop,e,t,arguments.length>1)},removeProp:function(e){e=ot.propFix[e]||e;return this.each(function(){try{this[e]=void 0;delete this[e]}catch(t){}})}});ot.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,i){var r,n,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s){o=1!==s||!ot.isXMLDoc(e);if(o){t=ot.propFix[t]||t;n=ot.propHooks[t]}return void 0!==i?n&&"set"in n&&void 0!==(r=n.set(e,i,t))?r:e[t]=i:n&&"get"in n&&null!==(r=n.get(e,t))?r:e[t]}},propHooks:{tabIndex:{get:function(e){var t=ot.find.attr(e,"tabindex");return t?parseInt(t,10):Ri.test(e.nodeName)||bi.test(e.nodeName)&&e.href?0:-1}}}});rt.hrefNormalized||ot.each(["href","src"],function(e,t){ot.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}});rt.optSelected||(ot.propHooks.selected={get:function(e){var t=e.parentNode;if(t){t.selectedIndex;t.parentNode&&t.parentNode.selectedIndex}return null}});ot.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ot.propFix[this.toLowerCase()]=this});rt.enctype||(ot.propFix.enctype="encoding");var Oi=/[\t\r\n\f]/g;ot.fn.extend({addClass:function(e){var t,i,r,n,o,s,a=0,l=this.length,u="string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).addClass(e.call(this,t,this.className))});if(u){t=(e||"").match(Nt)||[];for(;l>a;a++){i=this[a];r=1===i.nodeType&&(i.className?(" "+i.className+" ").replace(Oi," "):" ");if(r){o=0;for(;n=t[o++];)r.indexOf(" "+n+" ")<0&&(r+=n+" ");s=ot.trim(r);i.className!==s&&(i.className=s)}}}return this},removeClass:function(e){var t,i,r,n,o,s,a=0,l=this.length,u=0===arguments.length||"string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).removeClass(e.call(this,t,this.className))});if(u){t=(e||"").match(Nt)||[];for(;l>a;a++){i=this[a];r=1===i.nodeType&&(i.className?(" "+i.className+" ").replace(Oi," "):"");if(r){o=0;for(;n=t[o++];)for(;r.indexOf(" "+n+" ")>=0;)r=r.replace(" "+n+" "," ");s=e?ot.trim(r):"";i.className!==s&&(i.className=s)}}}return this},toggleClass:function(e,t){var i=typeof e;return"boolean"==typeof t&&"string"===i?t?this.addClass(e):this.removeClass(e):this.each(ot.isFunction(e)?function(i){ot(this).toggleClass(e.call(this,i,this.className,t),t)}:function(){if("string"===i)for(var t,r=0,n=ot(this),o=e.match(Nt)||[];t=o[r++];)n.hasClass(t)?n.removeClass(t):n.addClass(t);else if(i===yt||"boolean"===i){this.className&&ot._data(this,"__className__",this.className);this.className=this.className||e===!1?"":ot._data(this,"__className__")||""}})},hasClass:function(e){for(var t=" "+e+" ",i=0,r=this.length;r>i;i++)if(1===this[i].nodeType&&(" "+this[i].className+" ").replace(Oi," ").indexOf(t)>=0)return!0;return!1}});ot.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){ot.fn[t]=function(e,i){return arguments.length>0?this.on(t,null,e,i):this.trigger(t)}});ot.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,i){return this.on(e,null,t,i)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,i,r){return this.on(t,e,i,r)},undelegate:function(e,t,i){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",i)}});var Pi=ot.now(),Di=/\?/,wi=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;ot.parseJSON=function(e){if(t.JSON&&t.JSON.parse)return t.JSON.parse(e+"");var i,r=null,n=ot.trim(e+"");return n&&!ot.trim(n.replace(wi,function(e,t,n,o){i&&t&&(r=0);if(0===r)return e;i=n||t;r+=!o-!n;return""}))?Function("return "+n)():ot.error("Invalid JSON: "+e)};ot.parseXML=function(e){var i,r;if(!e||"string"!=typeof e)return null;try{if(t.DOMParser){r=new DOMParser;i=r.parseFromString(e,"text/xml")}else{i=new ActiveXObject("Microsoft.XMLDOM");i.async="false";i.loadXML(e)}}catch(n){i=void 0}i&&i.documentElement&&!i.getElementsByTagName("parsererror").length||ot.error("Invalid XML: "+e);return i};var _i,Mi,ki=/#.*$/,Gi=/([?&])_=[^&]*/,Bi=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ui=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Vi=/^(?:GET|HEAD)$/,Fi=/^\/\//,Hi=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,ji={},Wi={},qi="*/".concat("*");try{Mi=location.href}catch(zi){Mi=Et.createElement("a");Mi.href="";Mi=Mi.href}_i=Hi.exec(Mi.toLowerCase())||[];ot.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Mi,type:"GET",isLocal:Ui.test(_i[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":qi,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":ot.parseJSON,"text xml":ot.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?H(H(e,ot.ajaxSettings),t):H(ot.ajaxSettings,e)},ajaxPrefilter:V(ji),ajaxTransport:V(Wi),ajax:function(e,t){function i(e,t,i,r){var n,p,g,v,N,L=t;if(2!==x){x=2;a&&clearTimeout(a);u=void 0;s=r||"";T.readyState=e>0?4:0;n=e>=200&&300>e||304===e;i&&(v=j(c,T,i));v=W(c,v,T,n);if(n){if(c.ifModified){N=T.getResponseHeader("Last-Modified");N&&(ot.lastModified[o]=N);N=T.getResponseHeader("etag");N&&(ot.etag[o]=N)}if(204===e||"HEAD"===c.type)L="nocontent";else if(304===e)L="notmodified";else{L=v.state;p=v.data;g=v.error;n=!g}}else{g=L;if(e||!L){L="error";0>e&&(e=0)}}T.status=e;T.statusText=(t||L)+"";n?h.resolveWith(d,[p,L,T]):h.rejectWith(d,[T,L,g]);T.statusCode(m);m=void 0;l&&f.trigger(n?"ajaxSuccess":"ajaxError",[T,c,n?p:g]);E.fireWith(d,[T,L]);if(l){f.trigger("ajaxComplete",[T,c]);--ot.active||ot.event.trigger("ajaxStop")}}}if("object"==typeof e){t=e;e=void 0}t=t||{};var r,n,o,s,a,l,u,p,c=ot.ajaxSetup({},t),d=c.context||c,f=c.context&&(d.nodeType||d.jquery)?ot(d):ot.event,h=ot.Deferred(),E=ot.Callbacks("once memory"),m=c.statusCode||{},g={},v={},x=0,N="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!p){p={};for(;t=Bi.exec(s);)p[t[1].toLowerCase()]=t[2]}t=p[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?s:null},setRequestHeader:function(e,t){var i=e.toLowerCase();if(!x){e=v[i]=v[i]||e;g[e]=t}return this},overrideMimeType:function(e){x||(c.mimeType=e);return this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else T.always(e[T.status]);return this},abort:function(e){var t=e||N;u&&u.abort(t);i(0,t);return this}};h.promise(T).complete=E.add;T.success=T.done;T.error=T.fail;c.url=((e||c.url||Mi)+"").replace(ki,"").replace(Fi,_i[1]+"//");c.type=t.method||t.type||c.method||c.type;c.dataTypes=ot.trim(c.dataType||"*").toLowerCase().match(Nt)||[""];if(null==c.crossDomain){r=Hi.exec(c.url.toLowerCase());c.crossDomain=!(!r||r[1]===_i[1]&&r[2]===_i[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(_i[3]||("http:"===_i[1]?"80":"443")))}c.data&&c.processData&&"string"!=typeof c.data&&(c.data=ot.param(c.data,c.traditional));F(ji,c,t,T);if(2===x)return T;l=ot.event&&c.global;l&&0===ot.active++&&ot.event.trigger("ajaxStart");c.type=c.type.toUpperCase();c.hasContent=!Vi.test(c.type);o=c.url;if(!c.hasContent){if(c.data){o=c.url+=(Di.test(o)?"&":"?")+c.data;delete c.data}c.cache===!1&&(c.url=Gi.test(o)?o.replace(Gi,"$1_="+Pi++):o+(Di.test(o)?"&":"?")+"_="+Pi++)}if(c.ifModified){ot.lastModified[o]&&T.setRequestHeader("If-Modified-Since",ot.lastModified[o]);ot.etag[o]&&T.setRequestHeader("If-None-Match",ot.etag[o])}(c.data&&c.hasContent&&c.contentType!==!1||t.contentType)&&T.setRequestHeader("Content-Type",c.contentType);T.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+("*"!==c.dataTypes[0]?", "+qi+"; q=0.01":""):c.accepts["*"]);for(n in c.headers)T.setRequestHeader(n,c.headers[n]);if(c.beforeSend&&(c.beforeSend.call(d,T,c)===!1||2===x))return T.abort();N="abort";for(n in{success:1,error:1,complete:1})T[n](c[n]);u=F(Wi,c,t,T);if(u){T.readyState=1;l&&f.trigger("ajaxSend",[T,c]);c.async&&c.timeout>0&&(a=setTimeout(function(){T.abort("timeout")},c.timeout));try{x=1;u.send(g,i)}catch(L){if(!(2>x))throw L;i(-1,L)}}else i(-1,"No Transport");return T},getJSON:function(e,t,i){return ot.get(e,t,i,"json")},getScript:function(e,t){return ot.get(e,void 0,t,"script")}});ot.each(["get","post"],function(e,t){ot[t]=function(e,i,r,n){if(ot.isFunction(i)){n=n||r;r=i;i=void 0}return ot.ajax({url:e,type:t,dataType:n,data:i,success:r})}});ot._evalUrl=function(e){return ot.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})};ot.fn.extend({wrapAll:function(e){if(ot.isFunction(e))return this.each(function(t){ot(this).wrapAll(e.call(this,t))});if(this[0]){var t=ot(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]);t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return this.each(ot.isFunction(e)?function(t){ot(this).wrapInner(e.call(this,t))}:function(){var t=ot(this),i=t.contents();i.length?i.wrapAll(e):t.append(e)})},wrap:function(e){var t=ot.isFunction(e);return this.each(function(i){ot(this).wrapAll(t?e.call(this,i):e)})},unwrap:function(){return this.parent().each(function(){ot.nodeName(this,"body")||ot(this).replaceWith(this.childNodes)}).end()}});ot.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!rt.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||ot.css(e,"display"))};ot.expr.filters.visible=function(e){return!ot.expr.filters.hidden(e)};var Xi=/%20/g,Yi=/\[\]$/,Ki=/\r?\n/g,$i=/^(?:submit|button|image|reset|file)$/i,Qi=/^(?:input|select|textarea|keygen)/i;ot.param=function(e,t){var i,r=[],n=function(e,t){t=ot.isFunction(t)?t():null==t?"":t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};void 0===t&&(t=ot.ajaxSettings&&ot.ajaxSettings.traditional);if(ot.isArray(e)||e.jquery&&!ot.isPlainObject(e))ot.each(e,function(){n(this.name,this.value)});else for(i in e)q(i,e[i],t,n);return r.join("&").replace(Xi,"+")};ot.fn.extend({serialize:function(){return ot.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=ot.prop(this,"elements");return e?ot.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!ot(this).is(":disabled")&&Qi.test(this.nodeName)&&!$i.test(e)&&(this.checked||!Pt.test(e))}).map(function(e,t){var i=ot(this).val();return null==i?null:ot.isArray(i)?ot.map(i,function(e){return{name:t.name,value:e.replace(Ki,"\r\n")}}):{name:t.name,value:i.replace(Ki,"\r\n")}}).get()}});ot.ajaxSettings.xhr=void 0!==t.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&z()||X()}:z;var Zi=0,Ji={},er=ot.ajaxSettings.xhr();t.attachEvent&&t.attachEvent("onunload",function(){for(var e in Ji)Ji[e](void 0,!0)});rt.cors=!!er&&"withCredentials"in er;er=rt.ajax=!!er;er&&ot.ajaxTransport(function(e){if(!e.crossDomain||rt.cors){var t;return{send:function(i,r){var n,o=e.xhr(),s=++Zi;o.open(e.type,e.url,e.async,e.username,e.password);if(e.xhrFields)for(n in e.xhrFields)o[n]=e.xhrFields[n];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType);e.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(n in i)void 0!==i[n]&&o.setRequestHeader(n,i[n]+"");o.send(e.hasContent&&e.data||null);t=function(i,n){var a,l,u;if(t&&(n||4===o.readyState)){delete Ji[s];t=void 0;o.onreadystatechange=ot.noop;if(n)4!==o.readyState&&o.abort();else{u={};a=o.status;"string"==typeof o.responseText&&(u.text=o.responseText);try{l=o.statusText }catch(p){l=""}a||!e.isLocal||e.crossDomain?1223===a&&(a=204):a=u.text?200:404}}u&&r(a,l,u,o.getAllResponseHeaders())};e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=Ji[s]=t:t()},abort:function(){t&&t(void 0,!0)}}}});ot.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){ot.globalEval(e);return e}}});ot.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1);if(e.crossDomain){e.type="GET";e.global=!1}});ot.ajaxTransport("script",function(e){if(e.crossDomain){var t,i=Et.head||ot("head")[0]||Et.documentElement;return{send:function(r,n){t=Et.createElement("script");t.async=!0;e.scriptCharset&&(t.charset=e.scriptCharset);t.src=e.url;t.onload=t.onreadystatechange=function(e,i){if(i||!t.readyState||/loaded|complete/.test(t.readyState)){t.onload=t.onreadystatechange=null;t.parentNode&&t.parentNode.removeChild(t);t=null;i||n(200,"success")}};i.insertBefore(t,i.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var tr=[],ir=/(=)\?(?=&|$)|\?\?/;ot.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=tr.pop()||ot.expando+"_"+Pi++;this[e]=!0;return e}});ot.ajaxPrefilter("json jsonp",function(e,i,r){var n,o,s,a=e.jsonp!==!1&&(ir.test(e.url)?"url":"string"==typeof e.data&&!(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&ir.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0]){n=e.jsonpCallback=ot.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback;a?e[a]=e[a].replace(ir,"$1"+n):e.jsonp!==!1&&(e.url+=(Di.test(e.url)?"&":"?")+e.jsonp+"="+n);e.converters["script json"]=function(){s||ot.error(n+" was not called");return s[0]};e.dataTypes[0]="json";o=t[n];t[n]=function(){s=arguments};r.always(function(){t[n]=o;if(e[n]){e.jsonpCallback=i.jsonpCallback;tr.push(n)}s&&ot.isFunction(o)&&o(s[0]);s=o=void 0});return"script"}});ot.parseHTML=function(e,t,i){if(!e||"string"!=typeof e)return null;if("boolean"==typeof t){i=t;t=!1}t=t||Et;var r=dt.exec(e),n=!i&&[];if(r)return[t.createElement(r[1])];r=ot.buildFragment([e],t,n);n&&n.length&&ot(n).remove();return ot.merge([],r.childNodes)};var rr=ot.fn.load;ot.fn.load=function(e,t,i){if("string"!=typeof e&&rr)return rr.apply(this,arguments);var r,n,o,s=this,a=e.indexOf(" ");if(a>=0){r=ot.trim(e.slice(a,e.length));e=e.slice(0,a)}if(ot.isFunction(t)){i=t;t=void 0}else t&&"object"==typeof t&&(o="POST");s.length>0&&ot.ajax({url:e,type:o,dataType:"html",data:t}).done(function(e){n=arguments;s.html(r?ot("<div>").append(ot.parseHTML(e)).find(r):e)}).complete(i&&function(e,t){s.each(i,n||[e.responseText,t,e])});return this};ot.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ot.fn[t]=function(e){return this.on(t,e)}});ot.expr.filters.animated=function(e){return ot.grep(ot.timers,function(t){return e===t.elem}).length};var nr=t.document.documentElement;ot.offset={setOffset:function(e,t,i){var r,n,o,s,a,l,u,p=ot.css(e,"position"),c=ot(e),d={};"static"===p&&(e.style.position="relative");a=c.offset();o=ot.css(e,"top");l=ot.css(e,"left");u=("absolute"===p||"fixed"===p)&&ot.inArray("auto",[o,l])>-1;if(u){r=c.position();s=r.top;n=r.left}else{s=parseFloat(o)||0;n=parseFloat(l)||0}ot.isFunction(t)&&(t=t.call(e,i,a));null!=t.top&&(d.top=t.top-a.top+s);null!=t.left&&(d.left=t.left-a.left+n);"using"in t?t.using.call(e,d):c.css(d)}};ot.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){ot.offset.setOffset(this,e,t)});var t,i,r={top:0,left:0},n=this[0],o=n&&n.ownerDocument;if(o){t=o.documentElement;if(!ot.contains(t,n))return r;typeof n.getBoundingClientRect!==yt&&(r=n.getBoundingClientRect());i=Y(o);return{top:r.top+(i.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(i.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}}},position:function(){if(this[0]){var e,t,i={top:0,left:0},r=this[0];if("fixed"===ot.css(r,"position"))t=r.getBoundingClientRect();else{e=this.offsetParent();t=this.offset();ot.nodeName(e[0],"html")||(i=e.offset());i.top+=ot.css(e[0],"borderTopWidth",!0);i.left+=ot.css(e[0],"borderLeftWidth",!0)}return{top:t.top-i.top-ot.css(r,"marginTop",!0),left:t.left-i.left-ot.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||nr;e&&!ot.nodeName(e,"html")&&"static"===ot.css(e,"position");)e=e.offsetParent;return e||nr})}});ot.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var i=/Y/.test(t);ot.fn[e]=function(r){return Ot(this,function(e,r,n){var o=Y(e);if(void 0===n)return o?t in o?o[t]:o.document.documentElement[r]:e[r];o?o.scrollTo(i?ot(o).scrollLeft():n,i?n:ot(o).scrollTop()):e[r]=n;return void 0},e,r,arguments.length,null)}});ot.each(["top","left"],function(e,t){ot.cssHooks[t]=C(rt.pixelPosition,function(e,i){if(i){i=ii(e,t);return ni.test(i)?ot(e).position()[t]+"px":i}})});ot.each({Height:"height",Width:"width"},function(e,t){ot.each({padding:"inner"+e,content:t,"":"outer"+e},function(i,r){ot.fn[r]=function(r,n){var o=arguments.length&&(i||"boolean"!=typeof r),s=i||(r===!0||n===!0?"margin":"border");return Ot(this,function(t,i,r){var n;if(ot.isWindow(t))return t.document.documentElement["client"+e];if(9===t.nodeType){n=t.documentElement;return Math.max(t.body["scroll"+e],n["scroll"+e],t.body["offset"+e],n["offset"+e],n["client"+e])}return void 0===r?ot.css(t,i,s):ot.style(t,i,r,s)},t,o?r:void 0,o,null)}})});ot.fn.size=function(){return this.length};ot.fn.andSelf=ot.fn.addBack;"function"==typeof e&&e.amd&&e("jquery",[],function(){return ot});var or=t.jQuery,sr=t.$;ot.noConflict=function(e){t.$===ot&&(t.$=sr);e&&t.jQuery===ot&&(t.jQuery=or);return ot};typeof i===yt&&(t.jQuery=t.$=ot);return ot})},{}],16:[function(t,i){(function(t){function r(){try{return l in t&&t[l]}catch(e){return!1}}function n(e){return e.replace(/^d/,"___$&").replace(h,"___")}var o,s={},a=t.document,l="localStorage",u="script";s.disabled=!1;s.version="1.3.17";s.set=function(){};s.get=function(){};s.has=function(e){return void 0!==s.get(e)};s.remove=function(){};s.clear=function(){};s.transact=function(e,t,i){if(null==i){i=t;t=null}null==t&&(t={});var r=s.get(e,t);i(r);s.set(e,r)};s.getAll=function(){};s.forEach=function(){};s.serialize=function(e){return JSON.stringify(e)};s.deserialize=function(e){if("string"!=typeof e)return void 0;try{return JSON.parse(e)}catch(t){return e||void 0}};if(r()){o=t[l];s.set=function(e,t){if(void 0===t)return s.remove(e);o.setItem(e,s.serialize(t));return t};s.get=function(e,t){var i=s.deserialize(o.getItem(e));return void 0===i?t:i};s.remove=function(e){o.removeItem(e)};s.clear=function(){o.clear()};s.getAll=function(){var e={};s.forEach(function(t,i){e[t]=i});return e};s.forEach=function(e){for(var t=0;t<o.length;t++){var i=o.key(t);e(i,s.get(i))}}}else if(a.documentElement.addBehavior){var p,c;try{c=new ActiveXObject("htmlfile");c.open();c.write("<"+u+">document.w=window</"+u+'><iframe src="/favicon.ico"></iframe>');c.close();p=c.w.frames[0].document;o=p.createElement("div")}catch(d){o=a.createElement("div");p=a.body}var f=function(e){return function(){var t=Array.prototype.slice.call(arguments,0);t.unshift(o);p.appendChild(o);o.addBehavior("#default#userData");o.load(l);var i=e.apply(s,t);p.removeChild(o);return i}},h=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");s.set=f(function(e,t,i){t=n(t);if(void 0===i)return s.remove(t);e.setAttribute(t,s.serialize(i));e.save(l);return i});s.get=f(function(e,t,i){t=n(t);var r=s.deserialize(e.getAttribute(t));return void 0===r?i:r});s.remove=f(function(e,t){t=n(t);e.removeAttribute(t);e.save(l)});s.clear=f(function(e){var t=e.XMLDocument.documentElement.attributes;e.load(l);for(var i,r=0;i=t[r];r++)e.removeAttribute(i.name);e.save(l)});s.getAll=function(){var e={};s.forEach(function(t,i){e[t]=i});return e};s.forEach=f(function(e,t){for(var i,r=e.XMLDocument.documentElement.attributes,n=0;i=r[n];++n)t(i.name,s.deserialize(e.getAttribute(i.name)))})}try{var E="__storejs__";s.set(E,E);s.get(E)!=E&&(s.disabled=!0);s.remove(E)}catch(d){s.disabled=!0}s.enabled=!s.disabled;"undefined"!=typeof i&&i.exports&&this.module!==i?i.exports=s:"function"==typeof e&&e.amd?e(s):t.store=s})(Function("return this")())},{}],17:[function(e,t){t.exports={name:"yasgui-utils",version:"1.5.0",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:"Laurens Rietveld",maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{store:"^1.3.14"}}},{}],18:[function(e,t){window.console=window.console||{log:function(){}};t.exports={storage:e("./storage.js"),svg:e("./svg.js"),version:{"yasgui-utils":e("../package.json").version}}},{"../package.json":17,"./storage.js":19,"./svg.js":20}],19:[function(e,t){{var i=e("store"),r={day:function(){return 864e5},month:function(){30*r.day()},year:function(){12*r.month()}};t.exports={set:function(e,t,n){if(i.enabled&&e&&t){"string"==typeof n&&(n=r[n]());t.documentElement&&(t=(new XMLSerializer).serializeToString(t.documentElement));i.set(e,{val:t,exp:n,time:(new Date).getTime()})}},remove:function(e){i.enabled&&e&&i.remove(e)},get:function(e){if(!i.enabled)return null;if(e){var t=i.get(e);return t?t.exp&&(new Date).getTime()-t.time>t.exp?null:t.val:null}return null}}}},{store:16}],20:[function(e,t){t.exports={draw:function(e,i){if(e){var r=t.exports.getElement(i);r&&(e.append?e.append(r):e.appendChild(r))}},getElement:function(e){if(e&&0==e.indexOf("<svg")){var t=new DOMParser,i=t.parseFromString(e,"text/xml"),r=i.documentElement,n=document.createElement("div");n.className="svgImg";n.appendChild(r);return n}return!1}}},{}],21:[function(e,t){t.exports={name:"yasgui-yasqe",description:"Yet Another SPARQL Query Editor",version:"2.3.5",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasqe.yasgui.org/license.txt"}],author:"Laurens Rietveld",homepage:"http://yasqe.yasgui.org",devDependencies:{browserify:"^6.1.0",gulp:"~3.6.0","gulp-bump":"^0.1.11","gulp-concat":"^2.4.1","gulp-connect":"^2.0.5","gulp-embedlr":"^0.5.2","gulp-filter":"^1.0.2","gulp-git":"^0.5.2","gulp-jsvalidate":"^0.2.0","gulp-livereload":"^1.3.1","gulp-minify-css":"0.3.11","gulp-notify":"^2.0.1","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^1.0.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-sourcemaps":"^1.2.8",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","bootstrap-sass":"^3.3.1","browserify-transform-tools":"^1.2.1","gulp-cssimport":"^1.3.1"},bugs:"https://github.com/YASGUI/YASQE/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASQE.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.7.0","yasgui-utils":"^1.4.1"},optionalShim:{codemirror:{require:"codemirror",global:"CodeMirror"},jquery:{require:"jquery",global:"jQuery"},"../../lib/codemirror":{require:"codemirror",global:"CodeMirror"}}}},{}],22:[function(e,t){"use strict";var i=e("jquery"),r=e("../utils.js"),n=e("yasgui-utils"),o=e("../../lib/trie.js");t.exports=function(e,t){var a={},l={},u={};t.on("cursorActivity",function(){d(!0)});t.on("change",function(){var e=[];for(var r in a)a[r].is(":visible")&&e.push(a[r]);if(e.length>0){var n=i(t.getWrapperElement()).find(".CodeMirror-vscrollbar"),o=0;n.is(":visible")&&(o=n.outerWidth());e.forEach(function(e){e.css("right",o)})}});var p=function(e,i){u[e.name]=new o;for(var s=0;s<i.length;s++)u[e.name].insert(i[s]);var a=r.getPersistencyId(t,e.persistent);a&&n.storage.set(a,i,"month")},c=function(e,i){var o=l[e]=new i(t,e);o.name=e;if(o.bulk){var s=function(e){e&&e instanceof Array&&e.length>0&&p(o,e)};if(o.get instanceof Array)s(o.get);else{var a=null,u=r.getPersistencyId(t,o.persistent);u&&(a=n.storage.get(u));a&&a.length>0?s(a):o.get instanceof Function&&(o.async?o.get(null,s):s(o.get()))}}},d=function(r){if(!t.somethingSelected()){var n=function(i){if(r&&(!i.autoShow||!i.bulk&&i.async))return!1;var n={closeCharacters:/(?=a)b/,completeSingle:!1};!i.bulk&&i.async&&(n.async=!0);{var o=function(e,t){return f(i,t)};e.showHint(t,o,n)}return!0};for(var o in l)if(-1!=i.inArray(o,t.options.autocompleters)){var s=l[o];if(s.isValidCompletionPosition)if(s.isValidCompletionPosition()){if(!s.callbacks||!s.callbacks.validPosition||s.callbacks.validPosition(t,s)!==!1){var a=n(s);if(a)break}}else s.callbacks&&s.callbacks.invalidPosition&&s.callbacks.invalidPosition(t,s)}}},f=function(e,i){var r=function(t){var i=t.autocompletionString||t.string,r=[];if(u[e.name])r=u[e.name].autoComplete(i);else if("function"==typeof e.get&&0==e.async)r=e.get(i);else if("object"==typeof e.get)for(var n=i.length,o=0;o<e.get.length;o++){var s=e.get[o];s.slice(0,n)==i&&r.push(s)}return h(r,e,t)},n=t.getCompleteToken();e.preProcessToken&&(n=e.preProcessToken(n));if(n){if(e.bulk||!e.async)return r(n);var o=function(t){i(h(t,e,n))};e.get(n,o)}},h=function(e,i,r){for(var n=[],o=0;o<e.length;o++){var a=e[o];i.postProcessToken&&(a=i.postProcessToken(r,a));n.push({text:a,displayText:a,hint:s})}var l=t.getCursor(),u={completionToken:r.string,list:n,from:{line:l.line,ch:r.start},to:{line:l.line,ch:r.end}};if(i.callbacks)for(var p in i.callbacks)i.callbacks[p]&&t.on(u,p,i.callbacks[p]);return u};return{init:c,completers:l,notifications:{getEl:function(e){return i(a[e.name])},show:function(e,t){if(!t.autoshow){a[t.name]||(a[t.name]=i("<div class='completionNotification'></div>"));a[t.name].show().text("Press "+(-1!=navigator.userAgent.indexOf("Mac OS X")?"CMD":"CTRL")+" - <spacebar> to autocomplete").appendTo(i(e.getWrapperElement()))}},hide:function(e,t){a[t.name]&&a[t.name].hide()}},autoComplete:d,getTrie:function(e){return"string"==typeof e?u[e]:u[e.name]}}};var s=function(e,t,i){i.text!=e.getTokenAt(e.getCursor()).string&&e.replaceRange(i.text,t.from,t.to)}},{"../../lib/trie.js":4,"../utils.js":35,jquery:15,"yasgui-utils":18}],23:[function(e,t){"use strict";e("jquery");t.exports=function(i,r){return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(i)},get:function(t,r){return e("./utils").fetchFromLov(i,this,t,r)},preProcessToken:function(e){return t.exports.preProcessToken(i,e)},postProcessToken:function(e,r){return t.exports.postProcessToken(i,e,r)},async:!0,bulk:!1,autoShow:!1,persistent:r,callbacks:{validPosition:i.autocompleters.notifications.show,invalidPosition:i.autocompleters.notifications.hide}}};t.exports.isValidCompletionPosition=function(e){var t=e.getCompleteToken();if(0==t.string.indexOf("?"))return!1;var i=e.getCursor(),r=e.getPreviousNonWsToken(i.line,t);return"a"==r.string?!0:"rdf:type"==r.string?!0:"rdfs:domain"==r.string?!0:"rdfs:range"==r.string?!0:!1};t.exports.preProcessToken=function(t,i){return e("./utils.js").preprocessResourceTokenForCompletion(t,i)};t.exports.postProcessToken=function(t,i,r){return e("./utils.js").postprocessResourceTokenForCompletion(t,i,r)}},{"./utils":26,"./utils.js":26,jquery:15}],24:[function(e,t){"use strict";var i=e("jquery"),r={"string-2":"prefixed",atom:"var"};t.exports=function(e,r){e.on("change",function(){t.exports.appendPrefixIfNeeded(e,r)});return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(e)},get:function(e,t){i.get("http://prefix.cc/popular/all.file.json",function(e){var i=[];for(var r in e)if("bif"!=r){var n=r+": <"+e[r]+">";i.push(n)}i.sort();t(i)})},preProcessToken:function(i){return t.exports.preprocessPrefixTokenForCompletion(e,i)},async:!0,bulk:!0,autoShow:!0,persistent:r}};t.exports.isValidCompletionPosition=function(e){var t=e.getCursor(),r=e.getTokenAt(t);if(e.getLine(t.line).length>t.ch)return!1;"ws"!=r.type&&(r=e.getCompleteToken());if(0==!r.string.indexOf("a")&&-1==i.inArray("PNAME_NS",r.state.possibleCurrent))return!1;var n=e.getPreviousNonWsToken(t.line,r);return n&&"PREFIX"==n.string.toUpperCase()?!0:!1};t.exports.preprocessPrefixTokenForCompletion=function(e,t){var i=e.getPreviousNonWsToken(e.getCursor().line,t);i&&i.string&&":"==i.string.slice(-1)&&(t={start:i.start,end:t.end,string:i.string+" "+t.string,state:t.state});return t};t.exports.appendPrefixIfNeeded=function(e,t){if(e.autocompleters.getTrie(t)&&e.options.autocompleters&&-1!=e.options.autocompleters.indexOf(t)){var i=e.getCursor(),n=e.getTokenAt(i);if("prefixed"==r[n.type]){var o=n.string.indexOf(":");if(-1!==o){var s=e.getPreviousNonWsToken(i.line,n).string.toUpperCase(),a=e.getTokenAt({line:i.line,ch:n.start});if("PREFIX"!=s&&("ws"==a.type||null==a.type)){var l=n.string.substring(0,o+1),u=e.getPrefixesFromQuery();if(null==u[l.slice(0,-1)]){var p=e.autocompleters.getTrie(t).autoComplete(l);p.length>0&&e.addPrefixes(p[0])}}}}}}},{jquery:15}],25:[function(e,t){"use strict";var i=e("jquery");t.exports=function(i,r){return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(i)},get:function(t,r){return e("./utils").fetchFromLov(i,this,t,r)},preProcessToken:function(e){return t.exports.preProcessToken(i,e)},postProcessToken:function(e,r){return t.exports.postProcessToken(i,e,r)},async:!0,bulk:!1,autoShow:!1,persistent:r,callbacks:{validPosition:i.autocompleters.notifications.show,invalidPosition:i.autocompleters.notifications.hide}}};t.exports.isValidCompletionPosition=function(e){var t=e.getCompleteToken();if(0==t.string.length)return!1;if(0==t.string.indexOf("?"))return!1;if(i.inArray("a",t.state.possibleCurrent)>=0)return!0;var r=e.getCursor(),n=e.getPreviousNonWsToken(r.line,t);return"rdfs:subPropertyOf"==n.string?!0:!1};t.exports.preProcessToken=function(t,i){return e("./utils.js").preprocessResourceTokenForCompletion(t,i)};t.exports.postProcessToken=function(t,i,r){return e("./utils.js").postprocessResourceTokenForCompletion(t,i,r)}},{"./utils":26,"./utils.js":26,jquery:15}],26:[function(e,t){"use strict";var i=e("jquery"),r=(e("./utils.js"),e("yasgui-utils")),n=function(e,t){var i=e.getPrefixesFromQuery();if(0==!t.string.indexOf("<")){t.tokenPrefix=t.string.substring(0,t.string.indexOf(":")+1);null!=i[t.tokenPrefix.slice(0,-1)]&&(t.tokenPrefixUri=i[t.tokenPrefix.slice(0,-1)])}t.autocompletionString=t.string.trim();if(0==!t.string.indexOf("<")&&t.string.indexOf(":")>-1)for(var r in i)if(0==t.string.indexOf(r)){t.autocompletionString=i[r];t.autocompletionString+=t.string.substring(r.length+1);break}0==t.autocompletionString.indexOf("<")&&(t.autocompletionString=t.autocompletionString.substring(1));-1!==t.autocompletionString.indexOf(">",t.length-1)&&(t.autocompletionString=t.autocompletionString.substring(0,t.autocompletionString.length-1));return t},o=function(e,t,i){i=t.tokenPrefix&&t.autocompletionString&&t.tokenPrefixUri?t.tokenPrefix+i.substring(t.tokenPrefixUri.length):"<"+i+">";return i},s=function(t,n,o,s){if(!o||!o.string||0==o.string.trim().length){t.autocompleters.notifications.getEl(n).empty().append("Nothing to autocomplete yet!");return!1}var a=50,l={q:o.autocompletionString,page:1};l.type="classes"==n.name?"class":"property";var u=[],p="",c=function(){p="http://lov.okfn.org/dataset/lov/api/v2/autocomplete/terms?"+i.param(l)};c();var d=function(){l.page++;c()},f=function(){i.get(p,function(e){for(var r=0;r<e.results.length;r++)u.push(i.isArray(e.results[r].uri)&&e.results[r].uri.length>0?e.results[r].uri[0]:e.results[r].uri);if(u.length<e.total_results&&u.length<a){d();f()}else{u.length>0?t.autocompleters.notifications.hide(t,n):t.autocompleters.notifications.getEl(n).text("0 matches found...");s(u)}}).fail(function(){t.autocompleters.notifications.getEl(n).empty().append("Failed fetching suggestions..")})};t.autocompleters.notifications.getEl(n).empty().append(i("<span>Fetchting autocompletions &nbsp;</span>")).append(i(r.svg.getElement(e("../imgs.js").loader)).addClass("notificationLoader"));f()};t.exports={fetchFromLov:s,preprocessResourceTokenForCompletion:n,postprocessResourceTokenForCompletion:o}},{"../imgs.js":29,"./utils.js":26,jquery:15,"yasgui-utils":18}],27:[function(e,t){"use strict";var i=e("jquery");t.exports=function(e){return{isValidCompletionPosition:function(){var t=e.getTokenAt(e.getCursor());if("ws"!=t.type){t=e.getCompleteToken(t);if(t&&0==t.string.indexOf("?"))return!0}return!1},get:function(t){if(0==t.trim().length)return[];var r={};i(e.getWrapperElement()).find(".cm-atom").each(function(){var e=this.innerHTML;if(0==e.indexOf("?")){var n=i(this).next(),o=n.attr("class");o&&n.attr("class").indexOf("cm-atom")>=0&&(e+=n.text());if(e.length<=1)return;if(0!==e.indexOf(t))return;if(e==t)return;r[e]=!0}});var n=[];for(var o in r)n.push(o);n.sort();return n},async:!1,bulk:!1,autoShow:!0}}},{jquery:15}],28:[function(e){var t=e("jquery"),i=e("./main.js");i.defaults=t.extend(!0,{},i.defaults,{mode:"sparql11",value:"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nSELECT * WHERE {\n ?sub ?pred ?obj .\n} \nLIMIT 10",highlightSelectionMatches:{showToken:/\w/},tabMode:"indent",lineNumbers:!0,lineWrapping:!0,foldGutter:{rangeFinder:i.fold.brace},gutters:["gutterErrorBar","CodeMirror-linenumbers","CodeMirror-foldgutter"],matchBrackets:!0,fixedGutter:!0,syntaxErrorCheck:!0,extraKeys:{"Ctrl-Space":i.autoComplete,"Cmd-Space":i.autoComplete,"Ctrl-D":i.deleteLine,"Ctrl-K":i.deleteLine,"Cmd-D":i.deleteLine,"Cmd-K":i.deleteLine,"Ctrl-/":i.commentLines,"Cmd-/":i.commentLines,"Ctrl-Alt-Down":i.copyLineDown,"Ctrl-Alt-Up":i.copyLineUp,"Cmd-Alt-Down":i.copyLineDown,"Cmd-Alt-Up":i.copyLineUp,"Shift-Ctrl-F":i.doAutoFormat,"Shift-Cmd-F":i.doAutoFormat,"Ctrl-]":i.indentMore,"Cmd-]":i.indentMore,"Ctrl-[":i.indentLess,"Cmd-[":i.indentLess,"Ctrl-S":i.storeQuery,"Cmd-S":i.storeQuery,"Ctrl-Enter":i.executeQuery,"Cmd-Enter":i.executeQuery,F11:function(e){e.setOption("fullScreen",!e.getOption("fullScreen"))},Esc:function(e){e.getOption("fullScreen")&&e.setOption("fullScreen",!1)}},cursorHeight:.9,createShareLink:i.createShareLink,consumeShareLink:i.consumeShareLink,persistent:function(e){return"yasqe_"+t(e.getWrapperElement()).closest("[id]").attr("id")+"_queryVal"},sparql:{showQueryButton:!1,endpoint:"http://dbpedia.org/sparql",requestMethod:"POST",acceptHeaderGraph:"text/turtle,*/*;q=0.9",acceptHeaderSelect:"application/sparql-results+json,*/*;q=0.9",acceptHeaderUpdate:"text/plain,*/*;q=0.9",namedGraphs:[],defaultGraphs:[],args:[],headers:{},callbacks:{beforeSend:null,complete:null,error:null,success:null},handlers:{}}})},{"./main.js":30,jquery:15}],29:[function(e,t){"use strict";t.exports={loader:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" fill="black"> <circle cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(45 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.125s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(90 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.25s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(135 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.375s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(225 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.625s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(270 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.75s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(315 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.875s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle></svg>',query:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 80 80" enable-background="new 0 0 80 80" xml:space="preserve"><g ></g><g > <path d="M64.622,2.411H14.995c-6.627,0-12,5.373-12,12v49.897c0,6.627,5.373,12,12,12h49.627c6.627,0,12-5.373,12-12V14.411 C76.622,7.783,71.249,2.411,64.622,2.411z M24.125,63.906V15.093L61,39.168L24.125,63.906z"/></g></svg>',queryInvalid:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 73.627 73.897" enable-background="new 0 0 80 80" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="warning.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" inkscape:zoom="3.1936344" inkscape:cx="36.8135" inkscape:cy="36.9485" inkscape:window-x="2625" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="svg2" /><g transform="translate(-2.995,-2.411)" /><g transform="translate(-2.995,-2.411)" ><path d="M 64.622,2.411 H 14.995 c -6.627,0 -12,5.373 -12,12 v 49.897 c 0,6.627 5.373,12 12,12 h 49.627 c 6.627,0 12,-5.373 12,-12 V 14.411 c 0,-6.628 -5.373,-12 -12,-12 z M 24.125,63.906 V 15.093 L 61,39.168 24.125,63.906 z" inkscape:connector-curvature="0" /></g><path d="M 66.129381,65.903784 H 49.769875 c -1.64721,0 -2.889385,-0.581146 -3.498678,-1.63595 -0.609293,-1.055608 -0.491079,-2.422161 0.332391,-3.848223 l 8.179753,-14.167069 c 0.822934,-1.42633 1.9477,-2.211737 3.166018,-2.211737 1.218319,0 2.343086,0.785407 3.166019,2.211737 l 8.179751,14.167069 c 0.823472,1.426062 0.941686,2.792615 0.33239,3.848223 -0.609023,1.054804 -1.851197,1.63595 -3.498138,1.63595 z M 59.618815,60.91766 c 0,-0.850276 -0.68944,-1.539719 -1.539717,-1.539719 -0.850276,0 -1.539718,0.689443 -1.539718,1.539719 0,0.850277 0.689442,1.539718 1.539718,1.539718 0.850277,0 1.539717,-0.689441 1.539717,-1.539718 z m 0.04155,-9.265919 c 0,-0.873061 -0.707939,-1.580998 -1.580999,-1.580998 -0.873061,0 -1.580999,0.707937 -1.580999,1.580998 l 0.373403,5.610965 h 0.0051 c 0.05415,0.619747 0.568548,1.10761 1.202504,1.10761 0.586239,0 1.075443,-0.415756 1.188563,-0.968489 0.0092,-0.04476 0.0099,-0.09248 0.01392,-0.138854 h 0.01072 l 0.367776,-5.611232 z" inkscape:connector-curvature="0" style="fill:#aa8800" /></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g ></g><g > <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>',share:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve"><path d="M36.764,50c0,0.308-0.07,0.598-0.088,0.905l32.247,16.119c2.76-2.338,6.293-3.797,10.195-3.797 C87.89,63.228,95,70.338,95,79.109C95,87.89,87.89,95,79.118,95c-8.78,0-15.882-7.11-15.882-15.891c0-0.316,0.07-0.598,0.088-0.905 L31.077,62.085c-2.769,2.329-6.293,3.788-10.195,3.788C12.11,65.873,5,58.771,5,50c0-8.78,7.11-15.891,15.882-15.891 c3.902,0,7.427,1.468,10.195,3.797l32.247-16.119c-0.018-0.308-0.088-0.598-0.088-0.914C63.236,12.11,70.338,5,79.118,5 C87.89,5,95,12.11,95,20.873c0,8.78-7.11,15.891-15.882,15.891c-3.911,0-7.436-1.468-10.195-3.806L36.676,49.086 C36.693,49.394,36.764,49.684,36.764,50z"/></svg>',warning:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" viewBox="0 0 66.399998 66.399998" enable-background="new 0 0 69.3 69.3" xml:space="preserve" height="100%" width="100%" inkscape:version="0.48.4 r9939" ><g transform="translate(-1.5,-1.5)" style="fill:#ff0000"><path d="M 34.7,1.5 C 16.4,1.5 1.5,16.4 1.5,34.7 1.5,53 16.4,67.9 34.7,67.9 53,67.9 67.9,53 67.9,34.7 67.9,16.4 53,1.5 34.7,1.5 z m 0,59.4 C 20.2,60.9 8.5,49.1 8.5,34.7 8.5,20.2 20.3,8.5 34.7,8.5 c 14.4,0 26.2,11.8 26.2,26.2 0,14.4 -11.8,26.2 -26.2,26.2 z" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.6,47.1 c -1.4,0 -2.5,0.5 -3.5,1.5 -0.9,1 -1.4,2.2 -1.4,3.6 0,1.6 0.5,2.8 1.5,3.8 1,0.9 2.1,1.3 3.4,1.3 1.3,0 2.4,-0.5 3.4,-1.4 1,-0.9 1.5,-2.2 1.5,-3.7 0,-1.4 -0.5,-2.6 -1.4,-3.6 -0.9,-1 -2.1,-1.5 -3.5,-1.5 z" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.8,13.9 c -1.5,0 -2.8,0.5 -3.7,1.6 -0.9,1 -1.4,2.4 -1.4,4.2 0,1.1 0.1,2.9 0.2,5.6 l 0.8,13.1 c 0.2,1.8 0.4,3.2 0.9,4.1 0.5,1.2 1.5,1.8 2.9,1.8 1.3,0 2.3,-0.7 2.9,-1.9 0.5,-1 0.7,-2.3 0.9,-4 L 39.4,25 c 0.1,-1.3 0.2,-2.5 0.2,-3.8 0,-2.2 -0.3,-3.9 -0.8,-5.1 -0.5,-1 -1.6,-2.2 -4,-2.2 z" inkscape:connector-curvature="0" style="fill:#ff0000" /></g></svg>',fullscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="640" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><path d="m -7.962963,-10 v 38.889 l 16.667,-16.667 16.667,16.667 5.555,-5.555 -16.667,-16.667 16.667,-16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 92.037037,-10 v 38.889 l -16.667,-16.667 -16.666,16.667 -5.556,-5.555 16.666,-16.667 -16.666,-16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M -7.962963,90 V 51.111 l 16.667,16.666 16.667,-16.666 5.555,5.556 -16.667,16.666 16.667,16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M 92.037037,90 V 51.111 l -16.667,16.666 -16.666,-16.666 -5.556,5.556 16.666,16.666 -16.666,16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>',smallscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="Layer_1" /><path d="m 30.926037,28.889 0,-38.889 -16.667,16.667 -16.667,-16.667 -5.555,5.555 16.667,16.667 -16.667,16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,28.889 0,-38.889 16.667,16.667 16.666,-16.667 5.556,5.555 -16.666,16.667 16.666,16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 30.926037,51.111 0,38.889 -16.667,-16.666 -16.667,16.666 -5.555,-5.556 16.667,-16.666 -16.667,-16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,51.111 0,38.889 16.667,-16.666 16.666,16.666 5.556,-5.556 -16.666,-16.666 16.666,-16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>'} },{}],30:[function(e,t){"use strict";window.console=window.console||{log:function(){}};var i=e("jquery"),r=e("codemirror"),n=e("./utils.js"),o=e("yasgui-utils"),s=e("./imgs.js");e("../lib/deparam.js");e("codemirror/addon/fold/foldcode.js");e("codemirror/addon/fold/foldgutter.js");e("codemirror/addon/fold/xml-fold.js");e("codemirror/addon/fold/brace-fold.js");e("codemirror/addon/hint/show-hint.js");e("codemirror/addon/search/searchcursor.js");e("codemirror/addon/edit/matchbrackets.js");e("codemirror/addon/runmode/runmode.js");e("codemirror/addon/display/fullscreen.js");e("../lib/flint.js");var a=t.exports=function(e,t){var n=i("<div>",{"class":"yasqe"}).appendTo(i(e));t=l(t);var o=u(r(n[0],t));d(o);return o},l=function(e){var t=i.extend(!0,{},a.defaults,e);return t},u=function(t){t.autocompleters=e("./autocompleters/autocompleterBase.js")(a,t);t.options.autocompleters&&t.options.autocompleters.forEach(function(e){a.Autocompleters[e]&&t.autocompleters.init(e,a.Autocompleters[e])});t.getCompleteToken=function(i,r){return e("./tokenUtils.js").getCompleteToken(t,i,r)};t.getPreviousNonWsToken=function(i,r){return e("./tokenUtils.js").getPreviousNonWsToken(t,i,r)};t.getNextNonWsToken=function(i,r){return e("./tokenUtils.js").getNextNonWsToken(t,i,r)};t.query=function(e){a.executeQuery(t,e)};t.getUrlArguments=function(e){return a.getUrlArguments(t,e)};t.getPrefixesFromQuery=function(){return e("./prefixUtils.js").getPrefixesFromQuery(t)};t.addPrefixes=function(i){return e("./prefixUtils.js").addPrefixes(t,i)};t.removePrefixes=function(i){return e("./prefixUtils.js").removePrefixes(t,i)};t.getValueWithoutComments=function(){var e="";a.runMode(t.getValue(),"sparql11",function(t,i){"comment"!=i&&(e+=t)});return e};t.getQueryType=function(){return t.queryType};t.getQueryMode=function(){var e=t.getQueryType();return"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e?"update":"query"};t.setCheckSyntaxErrors=function(e){t.options.syntaxErrorCheck=e;h(t)};t.enableCompleter=function(e){p(t.options,e);a.Autocompleters[e]&&t.autocompleters.init(e,a.Autocompleters[e])};t.disableCompleter=function(e){c(t.options,e)};return t},p=function(e,t){e.autocompleters||(e.autocompleters=[]);e.autocompleters.push(t)},c=function(e,t){if("object"==typeof e.autocompleters){var r=i.inArray(t,e.autocompleters);if(r>=0){e.autocompleters.splice(r,1);c(e,t)}}},d=function(e){var t=n.getPersistencyId(e,e.options.persistent);if(t){var r=o.storage.get(t);r&&e.setValue(r)}a.drawButtons(e);e.on("blur",function(e){a.storeQuery(e)});e.on("change",function(e){h(e);a.updateQueryButton(e);a.positionButtons(e)});e.on("changes",function(){h(e);a.updateQueryButton(e);a.positionButtons(e)});e.on("cursorActivity",function(e){f(e)});e.prevQueryValid=!1;h(e);a.positionButtons(e);if(e.options.consumeShareLink){var s=i.deparam(window.location.search.substring(1));e.options.consumeShareLink(e,s)}},f=function(e){e.cursor=i(".CodeMirror-cursor");e.buttons&&e.buttons.is(":visible")&&e.cursor.length>0&&(n.elementsOverlap(e.cursor,e.buttons)?e.buttons.find("svg").attr("opacity","0.2"):e.buttons.find("svg").attr("opacity","1.0"))},h=function(t,r){t.queryValid=!0;t.clearGutter("gutterErrorBar");for(var n=null,a=0;a<t.lineCount();++a){var l=!1;t.prevQueryValid||(l=!0);var u=t.getTokenAt({line:a,ch:t.getLine(a).length},l),n=u.state;t.queryType=n.queryType;if(0==n.OK){if(!t.options.syntaxErrorCheck){i(t.getWrapperElement).find(".sp-error").css("color","black");return}var p=o.svg.getElement(s.warning);n.possibleCurrent&&n.possibleCurrent.length>0&&e("./tooltip")(t,p,function(){var e=[];n.possibleCurrent.forEach(function(t){e.push("<strong style='text-decoration:underline'>"+i("<div/>").text(t).html()+"</strong>")});return"This line is invalid. Expected: "+e.join(", ")});p.style.marginTop="2px";p.style.marginLeft="2px";p.className="parseErrorIcon";t.setGutterMarker(a,"gutterErrorBar",p);t.queryValid=!1;break}}t.prevQueryValid=t.queryValid;if(r&&null!=n&&void 0!=n.stack){var c=n.stack,d=n.stack.length;d>1?t.queryValid=!1:1==d&&"solutionModifier"!=c[0]&&"?limitOffsetClauses"!=c[0]&&"?offsetClause"!=c[0]&&(t.queryValid=!1)}};i.extend(a,r);a.Autocompleters={};a.registerAutocompleter=function(e,t){a.Autocompleters[e]=t;p(a.defaults,e)};a.autoComplete=function(e){e.autocompleters.autoComplete(!1)};a.registerAutocompleter("prefixes",e("./autocompleters/prefixes.js"));a.registerAutocompleter("properties",e("./autocompleters/properties.js"));a.registerAutocompleter("classes",e("./autocompleters/classes.js"));a.registerAutocompleter("variables",e("./autocompleters/variables.js"));a.positionButtons=function(e){var t=i(e.getWrapperElement()).find(".CodeMirror-vscrollbar"),r=0;t.is(":visible")&&(r=t.outerWidth());e.buttons.is(":visible")&&e.buttons.css("right",r+6)};a.createShareLink=function(e){var t=i.deparam(window.location.search.substring(1));t.query=e.getValue();return t};a.consumeShareLink=function(e,t){t.query&&e.setValue(t.query)};a.drawButtons=function(e){e.buttons=i("<div class='yasqe_buttons'></div>").appendTo(i(e.getWrapperElement()));if(e.options.createShareLink){var t=i(o.svg.getElement(s.share));t.click(function(r){r.stopPropagation();var n=i("<div class='yasqe_sharePopup'></div>").appendTo(e.buttons);i("html").click(function(){n&&n.remove()});n.click(function(e){e.stopPropagation()});var o=i("<textarea></textarea>").val(location.protocol+"//"+location.host+location.pathname+"?"+i.param(e.options.createShareLink(e)));o.focus(function(){var e=i(this);e.select();e.mouseup(function(){e.unbind("mouseup");return!1})});n.empty().append(o);var s=t.position();n.css("top",s.top+t.outerHeight()+"px").css("left",s.left+t.outerWidth()-n.outerWidth()+"px")}).addClass("yasqe_share").attr("title","Share your query").appendTo(e.buttons)}var r=i("<div>",{"class":"fullscreenToggleBtns"}).append(i(o.svg.getElement(s.fullscreen)).addClass("yasqe_fullscreenBtn").attr("title","Set editor full screen").click(function(){e.setOption("fullScreen",!0)})).append(i(o.svg.getElement(s.smallscreen)).addClass("yasqe_smallscreenBtn").attr("title","Set editor to normale size").click(function(){e.setOption("fullScreen",!1)}));e.buttons.append(r);if(e.options.sparql.showQueryButton){i("<div>",{"class":"yasqe_queryButton"}).click(function(){if(i(this).hasClass("query_busy")){e.xhr&&e.xhr.abort();a.updateQueryButton(e)}else e.query()}).appendTo(e.buttons);a.updateQueryButton(e)}};var E={busy:"loader",valid:"query",error:"queryInvalid"};a.updateQueryButton=function(e,t){var r=i(e.getWrapperElement()).find(".yasqe_queryButton");if(0!=r.length){if(!t){t="valid";e.queryValid===!1&&(t="error")}if(t!=e.queryStatus&&("busy"==t||"valid"==t||"error"==t)){r.empty().removeClass(function(e,t){return t.split(" ").filter(function(e){return 0==e.indexOf("query_")}).join(" ")}).addClass("query_"+t);o.svg.draw(r,s[E[t]]);e.queryStatus=t}}};a.fromTextArea=function(e,t){t=l(t);var n=(i("<div>",{"class":"yasqe"}).insertBefore(i(e)).append(i(e)),u(r.fromTextArea(e,t)));d(n);return n};a.storeQuery=function(e){var t=n.getPersistencyId(e,e.options.persistent);t&&o.storage.set(t,e.getValue(),"month")};a.commentLines=function(e){for(var t=e.getCursor(!0).line,i=e.getCursor(!1).line,r=Math.min(t,i),n=Math.max(t,i),o=!0,s=r;n>=s;s++){var a=e.getLine(s);if(0==a.length||"#"!=a.substring(0,1)){o=!1;break}}for(var s=r;n>=s;s++)o?e.replaceRange("",{line:s,ch:0},{line:s,ch:1}):e.replaceRange("#",{line:s,ch:0})};a.copyLineUp=function(e){var t=e.getCursor(),i=e.lineCount();e.replaceRange("\n",{line:i-1,ch:e.getLine(i-1).length});for(var r=i;r>t.line;r--){var n=e.getLine(r-1);e.replaceRange(n,{line:r,ch:0},{line:r,ch:e.getLine(r).length})}};a.copyLineDown=function(e){a.copyLineUp(e);var t=e.getCursor();t.line++;e.setCursor(t)};a.doAutoFormat=function(e){if(e.somethingSelected()){var t={line:e.getCursor(!1).line,ch:e.getSelection().length};m(e,e.getCursor(!0),t)}else{var i=e.lineCount(),r=e.getTextArea().value.length;m(e,{line:0,ch:0},{line:i,ch:r})}};var m=function(e,t,i){var r=e.indexFromPos(t),n=e.indexFromPos(i),o=g(e.getValue(),r,n);e.operation(function(){e.replaceRange(o,t,i);for(var n=e.posFromIndex(r).line,s=e.posFromIndex(r+o.length).line,a=n;s>=a;a++)e.indentLine(a,"smart")})},g=function(e,t,n){e=e.substring(t,n);var o=[["keyword","ws","prefixed","ws","uri"],["keyword","ws","uri"]],s=["{",".",";"],a=["}"],l=function(e){for(var t=0;t<o.length;t++)if(c.valueOf().toString()==o[t].valueOf().toString())return 1;for(var t=0;t<s.length;t++)if(e==s[t])return 1;for(var t=0;t<a.length;t++)if(""!=i.trim(p)&&e==a[t])return-1;return 0},u="",p="",c=[];r.runMode(e,"sparql11",function(e,t){c.push(t);var i=l(e,t);if(0!=i){if(1==i){u+=e+"\n";p=""}else{u+="\n"+e;p=e}c=[]}else{p+=e;u+=e}1==c.length&&"sp-ws"==c[0]&&(c=[])});return i.trim(u.replace(/\n\s*\n/g,"\n"))};e("./sparql.js"),e("./defaults.js");a.version={CodeMirror:r.version,YASQE:e("../package.json").version,jquery:i.fn.jquery,"yasgui-utils":o.version}},{"../lib/deparam.js":2,"../lib/flint.js":3,"../package.json":21,"./autocompleters/autocompleterBase.js":22,"./autocompleters/classes.js":23,"./autocompleters/prefixes.js":24,"./autocompleters/properties.js":25,"./autocompleters/variables.js":27,"./defaults.js":28,"./imgs.js":29,"./prefixUtils.js":31,"./sparql.js":32,"./tokenUtils.js":33,"./tooltip":34,"./utils.js":35,codemirror:14,"codemirror/addon/display/fullscreen.js":5,"codemirror/addon/edit/matchbrackets.js":6,"codemirror/addon/fold/brace-fold.js":7,"codemirror/addon/fold/foldcode.js":8,"codemirror/addon/fold/foldgutter.js":9,"codemirror/addon/fold/xml-fold.js":10,"codemirror/addon/hint/show-hint.js":11,"codemirror/addon/runmode/runmode.js":12,"codemirror/addon/search/searchcursor.js":13,jquery:15,"yasgui-utils":18}],31:[function(e,t){"use strict";var i=function(e,t){var i=e.getPrefixesFromQuery();if("string"==typeof t)r(e,t);else for(var n in t)n in i||r(e,n+": <"+t[n]+">")},r=function(e,t){for(var i=null,r=0,n=e.lineCount(),o=0;n>o;o++){var a=e.getNextNonWsToken(o);if(null!=a&&("PREFIX"==a.string||"BASE"==a.string)){i=a;r=o}}if(null==i)e.replaceRange("PREFIX "+t+"\n",{line:0,ch:0});else{var l=s(e,r);e.replaceRange("\n"+l+"PREFIX "+t,{line:r})}},n=function(e,t){var i=function(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")};for(var r in t)e.setValue(e.getValue().replace(new RegExp("PREFIX\\s*"+r+":\\s*"+i("<"+t[r]+">")+"\\s*","ig"),""))},o=function(e){for(var t={},i=!0,r=function(n,s){if(i){s||(s=1);var a=e.getNextNonWsToken(o,s);if(a){-1==a.state.possibleCurrent.indexOf("PREFIX")&&-1==a.state.possibleNext.indexOf("PREFIX")&&(i=!1);if("PREFIX"==a.string.toUpperCase()){var l=e.getNextNonWsToken(o,a.end+1);if(l){var u=e.getNextNonWsToken(o,l.end+1);if(u){var p=u.string;0==p.indexOf("<")&&(p=p.substring(1));">"==p.slice(-1)&&(p=p.substring(0,p.length-1));t[l.string.slice(0,-1)]=p;r(n,u.end+1)}else r(n,l.end+1)}else r(n,a.end+1)}else r(n,a.end+1)}}},n=e.lineCount(),o=0;n>o&&i;o++)r(o);return t},s=function(e,t,i){void 0==i&&(i=1);var r=e.getTokenAt({line:t,ch:i});return null==r||void 0==r||"ws"!=r.type?"":r.string+s(e,t,r.end+1)};t.exports={addPrefixes:i,getPrefixesFromQuery:o,removePrefixes:n}},{}],32:[function(e){"use strict";var t=e("jquery"),i=e("./main.js");i.executeQuery=function(e,n){var o="function"==typeof n?n:null,s="object"==typeof n?n:{};e.options.sparql&&(s=t.extend({},e.options.sparql,s));s.handlers&&t.extend(!0,s.callbacks,s.handlers);if(s.endpoint&&0!=s.endpoint.length){var a={url:"function"==typeof s.endpoint?s.endpoint(e):s.endpoint,type:"function"==typeof s.requestMethod?s.requestMethod(e):s.requestMethod,headers:{Accept:r(e,s)}},l=!1;if(s.callbacks)for(var u in s.callbacks)if(s.callbacks[u]){l=!0;a[u]=s.callbacks[u]}a.data=e.getUrlArguments(s);if(l||o){o&&(a.complete=o);s.headers&&!t.isEmptyObject(s.headers)&&t.extend(a.headers,s.headers);i.updateQueryButton(e,"busy");var p=function(){i.updateQueryButton(e)};a.complete=a.complete?[p,a.complete]:p;e.xhr=t.ajax(a)}}};i.getUrlArguments=function(e,i){var r=e.getQueryMode(),n=[{name:e.getQueryMode(),value:e.getValue()}];if(i.namedGraphs&&i.namedGraphs.length>0)for(var o="query"==r?"named-graph-uri":"using-named-graph-uri ",s=0;s<i.namedGraphs.length;s++)n.push({name:o,value:i.namedGraphs[s]});if(i.defaultGraphs&&i.defaultGraphs.length>0)for(var o="query"==r?"default-graph-uri":"using-graph-uri ",s=0;s<i.defaultGraphs.length;s++)n.push({name:o,value:i.defaultGraphs[s]});i.args&&i.args.length>0&&t.merge(n,i.args);return n};var r=function(e,t){var i=null;if(!t.acceptHeader||t.acceptHeaderGraph||t.acceptHeaderSelect||t.acceptHeaderUpdate)if("update"==e.getQueryMode())i="function"==typeof t.acceptHeader?t.acceptHeaderUpdate(e):t.acceptHeaderUpdate;else{var r=e.getQueryType();i="DESCRIBE"==r||"CONSTRUCT"==r?"function"==typeof t.acceptHeaderGraph?t.acceptHeaderGraph(e):t.acceptHeaderGraph:"function"==typeof t.acceptHeaderSelect?t.acceptHeaderSelect(e):t.acceptHeaderSelect}else i="function"==typeof t.acceptHeader?t.acceptHeader(e):t.acceptHeader;return i}},{"./main.js":30,jquery:15}],33:[function(e,t){"use strict";var i=function(e,t,r){r||(r=e.getCursor());t||(t=e.getTokenAt(r));var n=e.getTokenAt({line:r.line,ch:t.start});if(null!=n.type&&"ws"!=n.type&&null!=t.type&&"ws"!=t.type){t.start=n.start;t.string=n.string+t.string;return i(e,t,{line:r.line,ch:n.start})}if(null!=t.type&&"ws"==t.type){t.start=t.start+1;t.string=t.string.substring(1);return t}return t},r=function(e,t,i){var n=e.getTokenAt({line:t,ch:i.start});null!=n&&"ws"==n.type&&(n=r(e,t,n));return n},n=function(e,t,i){void 0==i&&(i=1);var r=e.getTokenAt({line:t,ch:i});return null==r||void 0==r||r.end<i?null:"ws"==r.type?n(e,t,r.end+1):r};t.exports={getPreviousNonWsToken:r,getCompleteToken:i,getNextNonWsToken:n}},{}],34:[function(e,t){"use strict";{var i=e("jquery");e("./utils.js")}t.exports=function(e,t,r){var n,t=i(t);t.hover(function(){"function"==typeof r&&(r=r());n=i("<div>").addClass("yasqe_tooltip").html(r).appendTo(t);o()},function(){i(".yasqe_tooltip").remove()});var o=function(){if(i(e.getWrapperElement()).offset().top>=n.offset().top){n.css("bottom","auto");n.css("top","26px")}}}},{"./utils.js":35,jquery:15}],35:[function(e,t){"use strict";var i=e("jquery"),r=function(e,t){var i=!1;try{void 0!==e[t]&&(i=!0)}catch(r){}return i},n=function(e,t){var i=null;t&&(i="string"==typeof t?t:t(e));return i},o=function(){function e(e){var t,r,n;t=i(e).offset();r=i(e).width();n=i(e).height();return[[t.left,t.left+r],[t.top,t.top+n]]}function t(e,t){var i,r;i=e[0]<t[0]?e:t;r=e[0]<t[0]?t:e;return i[1]>r[0]||i[0]===r[0]}return function(i,r){var n=e(i),o=e(r);return t(n[0],o[0])&&t(n[1],o[1])}}();t.exports={keyExists:r,getPersistencyId:n,elementsOverlap:o}},{jquery:15}]},{},[1])(1)}); //# sourceMappingURL=yasqe.bundled.min.js.map